Updating wordpress custom field after extracting youtube thumbnail - php

I am using a shortcode to display video from custom field "tube_video_url".
Now what I wish to do is to automaticly add mqdefault image to custom filed "fifu_image_url" of the same video.
I made this shortcode for myself...
function video( $atts, $content = "" ) {
$string = get_post_meta(get_the_ID(), 'tube_video_url', TRUE);
$search = '/youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
$replace = 'youtube.com/embed/$1';
$content = preg_replace($search, $replace, $string);
return '<iframe id="video-frame" width="560" height="315" src="'.$content.'" frameborder="0" allowfullscreen></iframe>';
}
add_shortcode( 'video', 'video' );
Now I am not sure how to turn this...
https://www.youtube.com/watch?v=2yJS-byLHrU
into this...
https://i.ytimg.com/vi/2yJS-byLHrU/mqdefault.jpg
I tried something like
$string = 'https://www.youtube.com/watch?v=2yJS-byLHrU';
$search = '/youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
$replace = 'i.ytimg.com/vi/$1/mqdefault.jpg';
$content = preg_replace($search, $replace, $string);
echo $content;
Result comes to https://www.i.ytimg.com/vi/2yJS/mqdefault.jpg-byLHrU, note how -byLHrUis put after jpg, and also how do I fill the custom field "fifu_image_url' with this value of image once submit button is pressed or at first post visit?

You can extract youtube video id using url as following
$link = "https://www.youtube.com/watch?v=2yJS-byLHrU";
$video_id = explode("?v=", $link);
if (empty($video_id[1]))
$video_id = explode("/v/", $link);
$video_id = explode("&", $video_id[1]);
$video_id = $video_id[0]; // will print the output -> 2yJS-byLHrU

Found answer, I will post it if anyone needs in future...
/* Do something with the data entered */
add_action( 'save_post', 'myplugin_save_postdata' );
/* When the post is saved, saves our custom data */
function myplugin_save_postdata( $post_id ) {
// First we need to check if the current user is authorised to do this action.
if ( 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) )
return;
} else {
if ( ! current_user_can( 'edit_post', $post_id ) )
return;
}
$url = get_post_meta(get_the_ID(), 'tube_video_url', TRUE);
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
$mydata = 'https://i.ytimg.com/vi/'. $youtube_id. '/mqdefault.jpg'; // Do something with $mydata
update_post_meta( $post_id, 'fifu_image_url', $mydata );
}
Unfortunatelly this works only posting from back-end.

Related

Why html_entity_decode won't bring formatted HTML in WordPress?

I have this shortcode:
I do this shortcode in template, I tried several WordPress themes, and it does not return HTML, but just text in continuous row.
I used this shortcode way abck and it worked, I do not know what happened meanwhile in a year so it does not work in WordPress anymore.
Anyone has a clue?
function paywall_level_b( $atts, $content = null ) {
$post = get_queried_object();
if ( function_exists( 'pmpro_has_membership_access' )) {
// Check if the user has access to the post.
$hasaccess = pmpro_has_membership_access( $post->ID );
// Display Content if the user has access to the post.
if( ! empty( $hasaccess ) ) {
$content = apply_filters('the_content', get_the_content());
echo $content;
// Display Text if the user has no access to the post, but is logged in.
} elseif ( is_user_logged_in() ) {
$content = apply_filters('the_content', get_the_content());
$sentences = explode(".", $content);
$first_slice = implode(".", array_splice($sentences, 0, 5));
$second_slice = implode(".", array_splice($sentences, 0));
echo '<div class="non-paywall">'. html_entity_decode ( $first_slice ) .'.</div><div class="pmpro_content_message">Text</div>';
// Display Text if the user has no access to the post, and is not logged in.
} else {
$content = apply_filters('the_content', get_the_content());
$sentences = explode(".", $content);
$first_slice = implode(".", array_splice($sentences, 0, 5));
$second_slice = implode(".", array_splice($sentences, 0));
echo '<div class="non-paywall">'. html_entity_decode ( $first_slice ) .'.</div><div class="pmpro_content_message">Text 2</div>';
}
}
}
add_shortcode( 'paywall_level_b', 'paywall_level_b' );

Wordpress get_avatar() $id_or_email

I am trying to create my custom front-end upload of users avatars.
I created form and created custom fields/meta data for it but I have problems with overriding get_avatar() wordpress function and I occurred with next problems.
My function can't get userId and size, I tried multiple solutions but I can't find solution why my get_avatar wont accept size and userID or userEmail
Code in functions.php
add_filter( 'get_avatar' , 'my_get_avatar' );
function my_get_avatar( $user_id, $size = '', $default = '', $alt = false ) {
var_dump($size);
if ( empty( $size ) || ! is_numeric( $size ) ) {
$size = 96;
}
$custom_avatar = get_user_meta( $user_id, '_user_avatar', true );
if(!($custom_avatar))
{
$url = "https://webkit.org/demos/srcset/image-src.png";
}
var_dump($custom_avatar);
$html = sprintf('<img src="%s" width="%s" height="%s" class="Avatarmss">', $url, $size,$size);
return $html;
}
When I put var_dump of $userID i get string with img tag and gavatar source
<img alt='' src='http://1.gravatar.com/avatar/d10ca8d11301c2f4993ac2279ce4b930?s=32&d=mm&r=g' .....
For dumping of size I get empty string.
I found solution.. Every core function is called before functions.php so I created custom plugin for this
try
add_filter( 'get_avatar','my_get_avatar' , 10, 5 );

Remove exact embed code(wordpress) with preg_replace

I'm using the following code to find first YouTube/Vimeo embed in the post content:
function compare_by_offset( $a, $b ) {
return $a['order'] - $b['order'];
}
function first_video_url($post_id = null) {
if ( $post_id == null OR $post_id == '' ) $post_id = get_the_ID();
$post_array = get_post( $post_id );
$markup = $post_array->post_content;
$regexes = array(
'#(?:https?:)?//www\.youtube(?:\-nocookie)?\.com/(?:v|e|embed)/([A-Za-z0-9\-_]+)#', // Comprehensive search for both iFrame and old school embeds
'#(?:https?(?:a|vh?)?://)?(?:www\.)?youtube(?:\-nocookie)?\.com/watch\?.*v=([A-Za-z0-9\-_]+)#', // Any YouTube URL. After http(s) support a or v for Youtube Lyte and v or vh for Smart Youtube plugin
'#(?:https?(?:a|vh?)?://)?youtu\.be/([A-Za-z0-9\-_]+)#', // Any shortened youtu.be URL. After http(s) a or v for Youtube Lyte and v or vh for Smart Youtube plugin
'#<div class="lyte" id="([A-Za-z0-9\-_]+)"#', // YouTube Lyte
'#data-youtube-id="([A-Za-z0-9\-_]+)"#', // LazyYT.js
'#<object[^>]+>.+?http://vimeo\.com/moogaloop.swf\?clip_id=([A-Za-z0-9\-_]+)&.+?</object>#s', // Standard Vimeo embed code
'#(?:https?:)?//player\.vimeo\.com/video/([0-9]+)#', // Vimeo iframe player
'#\[vimeo id=([A-Za-z0-9\-_]+)]#', // JR_embed shortcode
'#\[vimeo clip_id="([A-Za-z0-9\-_]+)"[^>]*]#', // Another shortcode
'#\[vimeo video_id="([A-Za-z0-9\-_]+)"[^>]*]#', // Yet another shortcode
'#(?:https?://)?(?:www\.)?vimeo\.com/([0-9]+)#', // Vimeo URL
'#(?:https?://)?(?:www\.)?vimeo\.com/channels/(?:[A-Za-z0-9]+)/([0-9]+)#' // Channel URL
);
$provider_videos = array();
foreach ( $regexes as $regex ) {
if ( preg_match_all( $regex, $markup, $matches, PREG_OFFSET_CAPTURE ) ) {
$provider_videos = array_merge( $provider_videos, $matches[0] );
}
}
if ( empty( $provider_videos ) ) return;
foreach ( $provider_videos as $video ) {
$videos[] = array(
'url' => $video[0],
'order' => $video[1]
);
}
usort( $videos, 'compare_by_offset' );
$first_video_url = current(array_column($videos, 'url'));
if ( empty( $first_video_url ) ) return;
return $first_video_url;
}
Now when I got the link to the first video in the post I want to remove it from the post content. And that's where I'm stuck. My attempt so far:
function remove_first_image ($content) {
$url = first_video_url();
$parsed = parse_url($url);
$video_id = $parsed['query'];
$embed_code = wp_oembed_get($url);
$pattern = 'a pattern for that embed which I fail to make';
$content = preg_replace($pattern, '', $content);
return $content;
}
add_filter('the_content', 'remove_first_image');
Thanks!
I guess one couldn't answer his own stupid question until he asks it. Here comes the answer:
function remove_first_image ($content) {
if ( is_single() && has_post_format('video') ) {
$url = first_video_url();
$embed_code = wp_oembed_get($url);
$content = str_replace($embed_code, '', $content);
}
return $content;
}
add_filter('the_content', 'remove_first_image');

Run function on posts sequentially

I have the following (resource intensive) function that I am triggering on the save_post action. It works perfectly when I save OR edit a single post. The problem is that I need to use it when importing multiple posts at the same time. I believe it is running this function across ALL imported (saved) posts at the same time.
How can I use the save_post action BUT only have this function execute on each post sequentially?
function getYouTubeTags( $post_id ) {
// Terminate if post has any tags
if ( has_term('', 'post_tag') ) {
return;
}
$out = null;
$video_id = get_post_meta( get_the_ID(), 'rfvi_video_id', true );
$tag_url = "http://www.youtube.com/watch?v=" . $video_id;
$sites_html = file_get_contents($tag_url, null, null, 700, 7000);
$html = new DOMDocument();
#$html->loadHTML($sites_html);
$meta_og_tag = null;
foreach( $html->getElementsByTagName('meta') as $meta ) {
if( $meta->getAttribute('property')==='og:video:tag' ){
$meta_og_tag = $meta->getAttribute('content');
$out[] = $meta_og_tag;
}
}
if ( !empty($out) ) {
return implode(',', $out);
} else {
return;
}
}
// Add YouTube tags to post
function rct_save_post_terms( $post_id ) {
$terms = getYouTubeTags( $post_id );
wp_set_post_terms( $post_id, $terms, 'post_tag', true );
}
add_action( 'save_post', 'rct_save_post_terms', 110, 1 );

WP / PHP function to extract the image doesn't work

I use often this function to extract the image of a post:
function first_post_image($content) {
$first_img = '';
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
$first_img = $matches [1] [0];
return $first_img;
}
then I show the image with the following code
<?php $postimage = first_post_image(get_the_content()); ?> // catch the image
<img src="<?php echo $postimage; ?>" /> //view the image
Now I tryed to use this function in my last template (wp), but the image doesn't appear. I can see the tag img and the src attribute, but it is empty.
Someone can help me? Thanks
Have you done a var_dump( $postimage ); to see what the function is returning?
Here is one that works and instead of returning an empty array if there are no images it will return false so you can specify a backup or default image.
/**
* Extracts the first image in the post content
*
* #param object $post the post object
* #return bool|string false if no images or img src
*/
function extract_image( $post ) {
$html = $post->post_content;
if ( stripos( $html, '<img' ) !== false ) {
$regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im';
preg_match( $regex, $html, $matches );
unset( $regex );
unset( $html );
if ( is_array( $matches ) && ! empty( $matches ) ) {
return $matches[2];
} else {
return false;
}
} else {
return false;
}
}
I have made some test and finally I solve the problem. I don't know if I make a mistake, but the code is the same and now work correctly.
Thanks.

Categories