Properly displaying thumbnails with the_post_thumbnail()

I have created a custom post type named bateau in functions.php. I also created a page where all the posts that belong to the bateau custom post type are displayed, showing some of the most important fields. Finally, when I click on one of those posts, a link sends me to the related custom post page, i.e. a particular type of boat.

The custom post bateau has its own custom fields, a thumbnail, and also its custom taxonomies.

Read More

I want to retrieve and display, when I’m on the page of a particular boat, not only the most important but all its custom fields, its thumbnail and its taxonomy.

So, in the functions.php, I have written this filter :

add_filter('the_content','add_text');

    function add_text($text) {

        global $post;
        $text = "";

        if($post->post_type == 'bateau') { 

        $text.= "<h1 class="bateau-entry-title">".get_post_meta( $post->ID, 'bateau_nom', true )."</h1>";
        return $text;
        }
    }   

It works fine, provided that I don’t write plain HTML text within closing and opening PHP tags, i.e. it only works if I wrap all the HTML in a PHP text var. If I don’t do so, the content is also displayed at the beginning of the header, not once, but twice. Strange, isn’t it ?

If I add this line :

$text.= "<img class="thumb" src="the_post_thumbnail();

the thumbnail displays properly in the “article”…but, guess what, also at the beginning of the header, not once, but twice !!! I just can’t find why the thumbnail behaves like this. Anyone can help please ?

Related posts

2 comments

  1. In WordPress, the page you called:

    when I’m on the page of a particular boat

    is called single. instead of putting a filter on the_content using

    add_filter('the_content','add_text');
    

    you would better add whatever you want to the loop. To do so, you may create a file called single-bateau.php (this is a protocol, so you need to name it exactly as this) in your current theme’s root directory and there you may have your loop:

    if(have_posts()){
        while(have_posts()){
            the_post();
            the_title();
            if( has_post_thumbnail() ){
                the_post_thumbnail( $thumb_size );
            }
            the_taxonomies();
            the_category();
            the_tags();
        }
    }
    
  2. I don’t think you need the img tag if you’re using the_post_thumbnail().

    Try doing something like:

    if ( has_post_thumbnail() ) 
        the_post_thumbnail();
    

Comments are closed.