I've been working with a child theme and functions.php file to add an Image to the posts that have a specific Tag (Videos
in the code). I was trying to create the function but I have some issues, one is that in the site, when I load a Post with that tag, it crashes, looks like it stays in a loop, and after that I have to manually delete all the repeated images (I just want one) from the posts in the database (PhpMyAdmin)
Could you help me to solve the issue and have working code?
Important Update: I am using a RSS feed, and I require that Image to be in the feed too (I mean in the posts table database)
Here is my code in functions.php
:
/**
* Prepend image to post if it has a specific tag
*
* @param String $content - WP Post Content for display
*
* @return String $content - WP Post Content for display
*/
function theme_videos_append_image( $content ) {
global $post;
// It would be easier if you got this URL from Attachment ID
$upload_dir_arr = wp_upload_dir(); // Get upload directory array ( https://developer.wordpress.org/reference/functions/wp_upload_dir/#user-contributed-notes )
$static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg';
// Ensure we are viewing a Post, and it has the Videos tag
if( has_tag( 'Videos', $post->ID ) ) {
$has_image = get_post_meta( $post->ID, '_video_image_added', true ); // Check if our postmeta exists
// If is does not have our postmeta - add it
if( empty( $has_image ) ) {
$image = sprintf( '<p><img src="%1$s" alt="" class="img-responsive" /></p>', $static_image_url ); // Create image
$content = $image . $content; // prepend image
// Update post so we don't need to add the image again
$success = wp_update_post( array(
'ID' => $post->ID,
'post_content' => $image . $post->post_content,
) );
// If the post updated, create postmeta letting us know later it has the image
if( false !== $success && !is_wp_error( $success ) ) {
update_post_meta( $post->ID, '_video_image_added', true );
}
}
}
return $content;
}
add_filter( 'the_content', 'theme_videos_append_image' );