im try something with the upload_dir filter
I check the current CPT with this function
function get_current_post_type() {
global $post, $typenow, $current_screen;
//we have a post so we can just get the post type from that
if ( $post && $post->post_type ) {
return $post->post_type;
} //check the global $typenow - set in admin.php
elseif ( $typenow ) {
return $typenow;
} //check the global $current_screen object - set in sceen.php
elseif ( $current_screen && $current_screen->post_type ) {
return $current_screen->post_type;
} //lastly check the post_type querystring
elseif ( isset( $_REQUEST['post_type'] ) ) {
return sanitize_key( $_REQUEST['post_type'] );
}
//we do not know the post type!
return NULL;
}
now i want to change the 'upload_dir' on at a certain cpt called "rsg_download"
add_action( 'admin_init', 'call_from_admin' );
function call_from_admin() {
//Here i get the Current custom Post type is the Post type = "rsg_download" then i want upload in a other folder called "rsg-uploads"
$currentCPT = get_current_post_type();
if ( $currentCPT = 'rsg_download' ) {
add_filter( 'upload_dir', 'change_upload_dir' );
}
}
When i use only
$currentCPT = get_current_post_type();
if ( $currentCPT = 'rsg_download' ) {
add_filter( 'upload_dir', 'change_upload_dir' );
}
The 'change_upload_dir' function is called twice dont know why also i call this from 'admin_init' with the function 'call_from_admin' and it calls only one time so far so good
i go to my CPT "rsg_download" and the uploade files are in the right place at wp-content/uploads/rsg-uploads/ this works so far
now i go to "Pages" and i upload a File but i want the files not in /rsg-upload but in the default path
Function to change the upload_dir this function should only be called when the custom post type is 'rsg_download':
function change_upload_dir( $param ) {
$mydir = '/rsg-uploads';
$param['path'] = $param['basedir'] . $mydir;
$param['url'] = $param['baseurl'] . $mydir;
return $param;
}
I found! this will only change the upload dir when upload in the "rsg_download" CPT
add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' );
function rsg_pre_upload( $file ) {
add_filter( 'upload_dir', 'rsg_custom_upload_dir' );
return $file;
}
function rsg_custom_upload_dir( $param ) {
$id = $_REQUEST['post_id'];
$parent = get_post( $id )->post_parent;
if( "rsg_download" == get_post_type( $id ) || "rsg_download" == get_post_type( $parent ) ) {
$mydir = '/rsg-uploads';
$param['path'] = $param['basedir'] . $mydir;
$param['url'] = $param['baseurl'] . $mydir;
}
return $param;
}
Related
Im new to RSS feed parsing and having a little trouble. How would I use simplepie to capture the following resource?
<enc:enclosure resource="http://images.craigslist.org/00202_lQ0CCpDIPk0_300x300.jpg" type="image/jpeg"/>
You would use the get_enclosures() function.
$feed = new SimplePie();
$feed->set_feed_url('http://simplepie.org/blog/feed/');
$feed->init();
$feed->handle_content_type();
foreach ($feed->get_items() as $item)
{
foreach ($item->get_enclosures() as $enclosure)
{
echo $enclosure->embed();
}
}
Previous responder doesn't realize how SimplePie works. You don't use the get_enclosures() because the XML is not formatted as <enclosure> ...
Instead you do it like this:
require( 'autoloader.php' );
$feed = new SimplePie();
$feed->set_feed_url('https://denver.craigslist.org/search/msa?format=rss&query=left%20handed%20%7C%20lefthanded%20%7C%20lefty');
$feed->init();
$feed->handle_content_type();
foreach ($feed->get_items() as $item) {
$encs = $item->get_item_tags( 'http://purl.oclc.org/net/rss_2.0/enc#', 'enclosure' );
if ( !isset( $encs ) )
continue;
foreach ( $encs as $enclosure){
if ( !isset( $enclosure['attribs'] ) )
continue;
foreach ( $enclosure['attribs'] as $attr ) {
echo "\n" . $attr['resource'];
}
}
}
I am saving records in a transaction using symfony1.4 and Doctrine.
The rows inserted are coming from a CSV file which is updated regularly. I have already got a method that checks if the records in the CSV match that in the DB and do not insert.
What I'm ideally wanting to do though, is to set a user flash telling them how many rows have been updated whenever they import the CSV file.
$conn = ProductTable::getInstance()->getConnection();
$conn->beginTransaction();
try {
$row = 1;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row > 1) {
$values = array(
'blah' => null
);
$obj= ProductTable::getInstance()->findOrCreateNewProduct(
$values['blah']
);
$obj->merge($values);
$obj->save($conn);
}
$row++;
}
$conn->commit();
} catch (Doctrine_Exception $e) {
$conn->rollback();
throw $e;
}
I'm wondering how I'd get these updated fields. Is it in the actions.class.php or is it in the actual form.class.php file?
Thanks
On the you can call a Doctrine_Record::getModified() which will give you an array of fields modified (with their values though that doesnt matter for you). Then you can call count on the returned array and keep a cumulative total outside your loop.
$conn = ProductTable::getInstance()->getConnection();
$conn->beginTransaction();
$nbModified = 0;
try {
$row = 1;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row > 1) {
$values = array(
'blah' => null
);
$obj= ProductTable::getInstance()->findOrCreateNewProduct(
$values['blah']
);
$obj->merge($values);
$nbModified += count($obj->getModified());
$obj->save($conn);
}
$row++;
}
$conn->commit();
// return $nbModified or otherwise do something with it here
} catch (Doctrine_Exception $e) {
$conn->rollback();
// youre rolling back so just for consistency set $nbModified to zero
$nbModified = 0;
throw $e;
}
Hi hope somone can help with this one. Ive had a birthday reminder app built, that aquires the usual permissions including offline access etc.
The app requires a daily cron job to be run on my server.
When I run the cron file a recieve the below error
Fatal error: Uncaught OAuthException: Invalid OAuth access token signature. thrown in blah/base_facebook.php on line 1140;
Is there a common reason for the error, am i doing anything wrong that stands out, and should i be displaying more code to get help from people?
below are the lines leading up to the error. My code ends on line 1140;
<?php
$name = 'api';
if (isset($READ_ONLY_CALLS[strtolower($method)])) {
$name = 'api_read';
} else if (strtolower($method) == 'video.upload') {
$name = 'api_video';
}
return self::getUrl($name, 'restserver.php');
}
protected function getUrl($name, $path='', $params=array())
{
$url = self::$DOMAIN_MAP[$name];
if ($path) {
if ($path[0] === '/') {
$path = substr($path, 1);
}
$url .= $path;
}
if ($params) {
$url .= '?' . http_build_query($params, null, '&');
}
return $url;
}
protected function getCurrentUrl() {
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$protocol = 'https://';
}
else {
$protocol = 'http://';
}
$currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$parts = parse_url($currentUrl);
$query = '';
if (!empty($parts['query'])) {
// drop known fb params
$params = explode('&', $parts['query']);
$retained_params = array();
foreach ($params as $param) {
if ($this->shouldRetainParam($param)) {
$retained_params[] = $param;
}
}
if (!empty($retained_params)) {
$query = '?'.implode($retained_params, '&');
}
}
// use port if non default
$port =
isset($parts['port']) &&
(($protocol === 'http://' && $parts['port'] !== 80) ||
($protocol === 'https://' && $parts['port'] !== 443))
? ':' . $parts['port'] : '';
// rebuild
return $protocol . $parts['host'] . $port . $parts['path'] . $query;
}
protected function shouldRetainParam($param) {
foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
if (strpos($param, $drop_query_param.'=') === 0) {
return false;
}
}
return true;
}
protected function throwAPIException($result) {
$e = new FacebookApiException($result);
?>
CRON.php
<?php
require_once("src/facebook.php");
include("custom.php");
set_time_limit(0);
$config = array();
$config['array'] = $appID;
$config['secret'] = $appSecret;
$facebook = new Facebook($config);
$day = abs(date("j"));
$month = abs(date("n"));
$result = mysql_query("SELECT uid, uid2, name2 FROM birthdays WHERE birthmonth = '$month' AND birthday = '$day'");
while(($row = mysql_fetch_assoc($result)) && mysql_num_rows($result)) {
$link = $hostURL.'post.php?uid='.$row['uid'].'&uid2='.$row['uid2'];
$facebook->api('/'.$row['uid'].'/feed', 'POST',
array(
'link' => $link,
'from' => '299185790135651',
'picture' => $hostURL.'image.php?id='.$row['uid2'],
'name' => 'Send Cake',
'message' => 'It\'s '.$row['name2'].'\'s birthday today! Send them a virtual cake!',
'caption' => 'Sponsored by Intercake Ltd'
));
}
?>
also... what is 'from' => '299185790135651', ?
want to check my developer has put the right number here. Thanks
The best way to handle this is to use a try...catch statement. As follows:
try {
// some code that calls Facebook
} catch ( Exception $e ) {
// $e will contain the error - do what you want with it here
// e.g. log it or send an email alert etc.
}
The 'from' => '299185790135651' is a User / Page ID that publishes the message to the Feed. In this case, it's pointing to a Test Facebook Page.
I'm using the code I found below to get the thumbnail url of a youtube video from a submitted url. The only problem is it doesn't work if someone uses the shortened version of the video url like http://youtube.be/HMYMSvlow_k. How can I modify this code so that it processes the youtube.be version as well as the other longer links?
function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
return false;
if( !isset( $type ) )
$type = '';
$url = esc_url( $url );
preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);
if( !isset( $vid_id[1] ) )
return false;
$img_server_num = 'i'. rand(1,4);
switch( $type ) {
case 'large':
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
break;
case 'first':
// Thumbnail of the first frame
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
break;
case 'small':
// Thumbnail of a later frame(i'm not sure how they determine this)
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
break;
case 'default':
case '':
default:
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
break;
}
if( $echo )
echo $img_link;
else
return $img_link;
}
function getVideoId($url)
{
$parsedUrl = parse_url($url);
if ($parsedUrl === false)
return false;
if (!empty($parsedUrl['query']))
{
$query = array();
parse_str($parsedUrl['query'], $query);
if (!empty($query['v']))
return $query['v'];
}
if (strtolower($parsedUrl['host']) == 'youtu.be')
return trim($parsedUrl['path'], '/');
return false;
}
$vid_id = getVideoId($video_code);
http://i3.ytimg.com/vi/<?php echo $vid_id; ?>/default.jpg
Im looking for a function that will pull the youtube duration of a video from the url. I read some tutorials but don't get it. I embed videos on my site using a url and I have a function that pulls the thumbnail and I just want something similar that gets the duration. Here's how I get the thumb...
function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
return false;
if( !isset( $type ) )
$type = '';
$url = esc_url( $url );
preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);
if( !isset( $vid_id[1] ) )
return false;
$img_server_num = 'i'. rand(1,4);
switch( $type ) {
case 'large':
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
break;
case 'first':
// Thumbnail of the first frame
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
break;
case 'small':
// Thumbnail of a later frame(i'm not sure how they determine this)
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
break;
case 'default':
case '':
default:
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
break;
}
if( $echo )
echo $img_link;
else
return $img_link;
}
You could use something like this:
<?php
function getDuration($url){
parse_str(parse_url($url,PHP_URL_QUERY),$arr);
$video_id=$arr['v'];
$data=#file_get_contents('http://gdata.youtube.com/feeds/api/videos/'.$video_id.'?v=2&alt=jsonc');
if (false===$data) return false;
$obj=json_decode($data);
return $obj->data->duration;
}
echo getDuration('http://www.youtube.com/watch?v=rFQc7VRJowk');
?>
that returns the duration in seconds of the video.
Reference: http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html
You can use a function like this one to change the seconds to hours, minutes, and seconds.
youtube api v3
usage
echo youtubeVideoDuration('video_url', 'your_api_key');
// output: 63 (seconds)
function
/**
* Return video duration in seconds.
*
* #param $video_url
* #param $api_key
* #return integer|null
*/
function youtubeVideoDuration($video_url, $api_key) {
// video id from url
parse_str(parse_url($video_url, PHP_URL_QUERY), $get_parameters);
$video_id = $get_parameters['v'];
// video json data
$json_result = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$video_id&key=$api_key");
$result = json_decode($json_result, true);
// video duration data
if (!count($result['items'])) {
return null;
}
$duration_encoded = $result['items'][0]['contentDetails']['duration'];
// duration
$interval = new DateInterval($duration_encoded);
$seconds = $interval->days * 86400 + $interval->h * 3600 + $interval->i * 60 + $interval->s;
return $seconds;
}
This is my function to get youtube duration in second.
he is fully 100% work.
you need just youtube id video and youtube api key.
how to add youtube api key show
this video https://www.youtube.com/watch?v=4AQ9UamPN6E
public static function getYoutubeDuration($id)
{
$Youtube_KEY='';
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={$id}&key={$Youtube_KEY}");
$vTime='';
$H=0;
$M=0;
$S=0;
$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
$vTime = $vidTime['contentDetails']['duration'];
}
$vTime = substr($vTime, 2);
$exp = explode("H",$vTime);
//if explode executed
if( $exp[0] != $vTime )
{
$H = $exp[0];
$vTime = $exp[1];
}
$exp = explode("M",$vTime);
if( $exp[0] != $vTime )
{
$M = $exp[0];
$vTime = $exp[1];
}
$exp = explode("S",$vTime);
$S = $exp[0];
$H = ($H*3600);
$M = ($M*60);
$S = ($H+$M+$S);
return $S;
}
This is my function to get youtube duration in second.
he is fully 100% work.
you need just youtube id video and youtube api key.
how to add youtube api key show
this video https://www.youtube.com/watch?v=4AQ9UamPN6E
You can simply use a time formater to change the seconds into whatever format you like.
i.e. return gmdate("H:i:s", $obj->data->duration);
function getYoutubeDuration($videoid) {
$xml = simplexml_load_file('https://gdata.youtube.com/feeds/api/videos/' . $videoid . '?v=2');
$result = $xml->xpath('//yt:duration[#seconds]');
$total_seconds = (int) $result[0]->attributes()->seconds;
return $total_seconds;
}
//now call this pretty function.
//As parameter I gave a video id to my function and bam!
echo getYoutubeDuration("y5nKxHn4yVA");
1) You will need an API key. Go to https://developers.google.com/ and log in or create an account, if necessary. After logging in go to this link https://console.developers.google.com/project and click on the blue CREATE PROJECT button. Wait a moment as Google prepares your project.
2) You will need a web host that is running PHP with file_get_content supported. You can check by creating a new script with just "echo php_info();" and verifying that allow_url_fopen is set to On. If it is not, then change the configuration or talk to your web host.
<?php
$sYouTubeApiKey = "<enter the key you get>";
//Replace This With The Video ID. You can get it from the URL.
//ie https://www.youtube.com/XWuUdJo9ubM would be
$sVideoId = "XWuUdJo9ubM";
//Get The Video Details From The API.
function getVideoDetails ($sVideoId) {
global $sYouTubeApiKey;
//Generate The API URL
$sUrl = "https://www.googleapis.com/youtube/v3/videos?id=".$sVideoId."&key=".$sYouTubeApiKey."&part=contentDetails";
//Perform The Request
$sData = file_get_contents($sUrl);
//Decode The JSON Response
return json_decode($sData);
}
//Get The Video Duration In Seconds.
function getVideoDuration ($sVideoId) {
$oData = getVideoDetails($sVideoId);
//Deal With No Videos In List
if (count($oData->items) < 1) return false;
//Get The First Video
$oVideo = array_shift($oData->items);
//Extract The Duration
$sDuration = $oVideo->contentDetails->duration;
//Use Regular Expression To Parse The Length
$pFields = "'PT(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?'si";
if (preg_match($pFields, $sDuration, $aMatch)) {
//Add Up Hours, Minutes, and Seconds
return $aMatch[1]*3600 + $aMatch[2]*60 + $aMatch[3];
}
}
header("Content-Type: text/plain");
$oData = getVideoDetails($sVideoId);
print_r($oData);
echo "Length: ".getVideoDuration($sVideoId);
?>
Hope this helps!