If featured image doesn’t exist, show post content

Before deciding to ask this question, I googled and searched this forum, but found no answer to my question, even though it may seem like a duplicate.

Anyway, I made custom post type that uses its featured image. Now, I would like to set if no featured image exists, show post content and by that I mean show whatever it is in my post ( in my case it is embedded youtube video).

So far I added to functions.php the following:

function zm_get_backend_preview_thumb($post_ID) {
    $post_thumbnail_id = get_post_thumbnail_id($post_ID);
    if ($post_thumbnail_id) {
        $post_thumbnail_img = wp_get_attachment_image_src($post_thumbnail_id, 'thumbnail');
        return $post_thumbnail_img[0];
    }
}

function zm_preview_thumb_column_head($defaults) {
    $defaults['featured_image'] = 'Image';
    return $defaults;
}

add_filter('manage_posts_columns', 'zm_preview_thumb_column_head');

function zm_preview_thumb_column($column_name, $post_ID) {
    if ($column_name == 'featured_image') {
        $post_featured_image = zm_get_backend_preview_thumb($post_ID);
            if ($post_featured_image) {
                echo '<img src="' . $post_featured_image . '" />';
            }

    }
}

add_action('manage_posts_custom_column', 'zm_preview_thumb_column', 10, 2);
}

And in my page where I would like to show the video instead featured image, I have the following code:

<?php
// WP_Query arguments
$args = array (
    'post_type'              => array( 'zm_gallery' ),
);
// The Query
$query_gallery = new WP_Query( $args );

// The Loop
if ( $query_gallery->have_posts() ) {

    while ( $query_gallery->have_posts() ) {
        $query_gallery->the_post();

        echo '<ul>';
        echo '<li>';
        $name = get_post_meta($post->ID, 'ExternalUrl', true);

        if( $name ) { ?>
            <a href="https://wordpress.stackexchange.com/questions/241880/<?php echo $name; ?>"target="_blank"><?php the_post_thumbnail(); ?></a>
           <?php
        } else {
            the_post_thumbnail();
        }   

        echo '</li>';
        echo '</ul>';
    }    
} else {
    if ( "" === $post->post_content ) {
        the_post_thumbnail();
    } else {
        the_content();
    }
}

// Restore original Post Data
wp_reset_postdata();
?>

Your help would be highly appreciated. Thank you all in advance.

2 Answers
2

the_post_thumbnail will echo out the thumbnail so maybe try

if ( has_post_thumbnail() ) {
  the_post_thumbnail();
} else {
  the_content();
}

Hope this helps

Leave a Comment