Pages

Tuesday, July 30, 2013

Wordpress image upload using url or from external site



     
      $filepath = dirname(__FILE__) . '/' . $filename;

$wp_filetype = wp_check_filetype($filepath, null );
$uploads = wp_upload_dir();

$fullpathfilename = $uploads['path'] . "/" . $filename;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, get_template_directory_uri().'/youtubeupload/'.$filename);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$image_string = curl_exec($ch);
curl_close($ch);

$fileSaved = file_put_contents($uploads['path'] . "/" . $filename, $image_string);
if ( !$fileSaved ) {
echo "The file cannot be saved.";
}

$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $uploads['url'] . "/" . $filename
);
$attach_id = wp_insert_attachment( $attachment, $fullpathfilename );
if ( !$attach_id ) {
echo "Failed to save record into database.";
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullpathfilename );
wp_update_attachment_metadata( $attach_id,  $attach_data );

set_post_thumbnail( $post_id, $attach_id );

Tuesday, July 16, 2013

jQuery Countdown time - show timer with two digits

If you are using countdown jquery from "http://keith-wood.name/countdown.html" then please open "jquery.countdown.js" and replace below code:

line no: 520 - 528

Original Code

var showFull = function(period) {
var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])];
return ((!inst.options.significant && show[period]) ||
(inst.options.significant && showSignificant[period]) ?
'<span class="' + plugin._sectionClass + '">' +
'<span class="' + plugin._amountClass + '">' +
self._translateDigits(inst, inst._periods[period]) + '</span><br/>' +
(labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
};



New Code

var showFull = function(period) {
var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])];

return ((!inst.options.significant && show[period]) ||
(inst.options.significant && showSignificant[period]) ?
'<span class="' + plugin._sectionClass + '">' +
'<span class="' + plugin._amountClass + '">' + ((self._translateDigits(inst, inst._periods[period]) <= 9 )?'0'+self._translateDigits(inst, inst._periods[period]):self._translateDigits(inst, inst._periods[period])) + '</span><br/>' +
(labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
};



Monday, July 15, 2013

PHP code to add st, nd, rd or th to a number



function wp_get_ordinal($input_number)
{
  $number            = (string) $input_number;
  $last_digit        = substr($number, -1);
  $second_last_digit = substr($number, -2, 1);
  $suffix            = 'th';
  if ($second_last_digit != '1')
  {
    switch ($last_digit)
    {
      case '1':
        $suffix = 'st';
        break;
      case '2':
        $suffix = 'nd';
        break;
      case '3':
        $suffix = 'rd';
        break;
      default:
        break;
    }
  }
  if ((string) $number === '1') $suffix = 'st';
  return $number.$suffix;
}

Friday, July 12, 2013

mysql count like and dislike average from one column


likes_id video_id Descending user_id like_status like_ip datetime
13 290 2 y 2013-07-01 17:15:29
25 290 3 y 2013-07-01 17:26:12
42 290 9 y 2013-07-01 17:30:35
58 290 10 n 183.182.91.153 2013-07-12 04:52:44

SELECT `like_status` , count( * ) FROM video_likes WHERE video_id = 290 GROUP BY `like_status`



like_status count( * )
y 3
n 1

SELECT SUM( CASE WHEN like_status = 'y' THEN 1 ELSE -1 END) as `counts` FROM `wp_video_likes`  WHERE video_id = 290;

PHP Cron setup




/usr/local/bin/php /home/ABC/public_html/plonk/cron.php>/home/ABC/public_html/cron/cronlog_`date "+\%Y-\%m-\%d_\%H-\%M"`.txt

Thursday, July 11, 2013

How to get youtube video duration from id - PHP



function parseVideoEntry($video_id) {    
    $obj= new stdClass;

$url = 'http://gdata.youtube.com/feeds/api/videos/'.$video_id;
$categoriesArray = array();
$xml = simplexml_load_file($url);


    $media = $xml->children('http://search.yahoo.com/mrss/');
    $obj->title = $media->group->title;
    $obj->description = $media->group->description;
     
    $yt = $media->children('http://gdata.youtube.com/schemas/2007');
    $attrs = $yt->duration->attributes();

    $obj->length = $attrs['seconds'];
    $VideoSeconds = $obj->length;
    return $VideoSeconds;    
}

echo $video = parseVideoEntry("nVhM3IYMF8o");

Convert seconds to hours, minutes and seconds - PHP


function secondsToWords($seconds)
{
    /*** return value ***/
    $ret = "";

    /*** get the hours ***/
    $hours = intval(intval($seconds) / 3600);
    if($hours > 0)   {
        if($hours <= 9) { $ret .= "0".$hours.":";}
else {       $ret .= $hours.":";}
    }
    /*** get the minutes ***/
    $minutes = bcmod((intval($seconds) / 60),60);
    if($hours > 0 || $minutes > 0)
    {
if($minutes <= 9) { $ret .= "0".$minutes.":";}
else {       $ret .= $minutes.":";}
    }
 
    /*** get the seconds ***/
    $seconds = bcmod(intval($seconds),60);
if($seconds <= 9) { $ret .= "0".$seconds;}
else {       $ret .= $seconds;}

    return $ret;
}

echo secondsToWords(3725);

How to detect video file duration in minutes with PHP?



ob_start();
 passthru("D:/wamp/www/ffmpeg/ffmpeg.exe -i D:/wamp/www/video5.mp4  2>&1");
 $duration = ob_get_contents();
 $full = ob_get_contents();
 ob_end_clean();
 $search = "/Duration.*?([0-9]{1,}):([0-9]{1,}):([0-9]{1,})/";
 print_r($duration);
 $duration = preg_match($search, $duration, $matches, PREG_OFFSET_CAPTURE, 3);

 print_r($matches);
 print_r($matches[1][0]);

Monday, July 8, 2013

Get Youtube video id from embaded code - PHP

function parse_youtube($link){

    $regexstr = '~
        # Match Youtube link and embed code
        (?:                             # Group to match embed codes
            (?:<iframe [^>]*src=")?       # If iframe match up to first quote of src
            |(?:                        # Group to match if older embed
                (?:<object .*>)?      # Match opening Object tag
                (?:<param .*</param>)*  # Match all param tags
                (?:<embed [^>]*src=")?  # Match embed tag to the first quote of src
            )?                          # End older embed code group
        )?                              # End embed code groups
        (?:                             # Group youtube url
            https?:\/\/                 # Either http or https
            (?:[\w]+\.)*                # Optional subdomains
            (?:                         # Group host alternatives.
            youtu\.be/                  # Either youtu.be,
            | youtube\.com              # or youtube.com
            | youtube-nocookie\.com     # or youtube-nocookie.com
            )                           # End Host Group
            (?:\S*[^\w\-\s])?           # Extra stuff up to VIDEO_ID
            ([\w\-]{11})                # $1: VIDEO_ID is numeric
            [^\s]*                      # Not a space
        )                               # End group
        "?                              # Match end quote if part of src
        (?:[^>]*>)?                       # Match any extra stuff up to close brace
        (?:                             # Group to match last embed code
            </iframe>                 # Match the end of the iframe
            |</embed></object>          # or Match the end of the older embed
        )?                              # End Group of last bit of embed code
        ~ix';

    preg_match($regexstr, $link, $matches);
    return $matches[1];
}

function get_youtube_id($embadedcode){
 if(strpos($embadedcode,'iframe') !== false){
  return parse_youtube($embadedcode);
 } else if(strpos($embadedcode,'object') !== false){
  preg_match('#(?<=youtube\.com/v/)\w+#', $embadedcode, $matches);
  return $matches[0];
 }
}

Wordpress Upload media file from front-end


$filename = rand(1000, 10000) . str_replace(" ","-",$_FILES["video_thumbnail"]["name"]);


require_once(ABSPATH . '/wp-load.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/image.php');

$upload_overrides = array( 'test_form' => FALSE );
$uploads = wp_upload_dir();

$file_array = array(
'name' => $filename,
'type' => $_FILES['video_thumbnail']['type'],
'tmp_name' => $_FILES['video_thumbnail']['tmp_name'],
'error' => $_FILES['video_thumbnail']['error'],
'size' => $_FILES['video_thumbnail']['size'],
);

$uploaded_file = wp_handle_upload( $file_array, $upload_overrides );

$wp_filetype = wp_check_filetype( basename( $uploaded_file['file'] ), null );

$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$uploadfile = $uploads['path'].'/' . basename( $filename );

$attachment_id = wp_insert_attachment( $attachment, $uploadfile );

$attach_data = wp_generate_attachment_metadata( $attachment_id, $uploadfile );

$attachimage_url = $uploads['url'].'/'.basename( $filename ) ;
wp_update_attachment_metadata( $attachment_id, $attach_data );

echo json_encode(array($attachment_id, $attachimage_url));