I thought this was going to be quick and easy, but naturally it's turning out to be more complicated. I'm writing a simple plugin that creates a custom post type "Ad", and then puts a random ad at the bottom of posts.

So I've created my custom post type - that's easy. Then I created a few ads, and I want to put the featured image from a random ad at the bottom of a post. So I wrote a function to get a random ad's featured image, and then I wrote a function to filter the content and put the ad at the bottom of the post.

Here's what I have:

function wpa_choose_ad() {
    $args = array( 
        'post_type' => 'ad',
        'posts_per_page' => 1,  
        'orderby' => 'rand',             
    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) : $the_query->the_post();
        $the_ad = the_post_thumbnail();

    return $the_ad;

function wpa_bottom_ad($content) {
    $ad = wpa_choose_ad();

    if( is_single() && is_main_query() ) {
        $content .= $ad;
    return $content;
add_filter('the_content', 'wpa_bottom_ad');

This puts the ad at the top of the post, and does nothing at the bottom of the post. I think somehow it's running my wp_query at the beginning of the post.

What am I doing wrong?

  • The code works for me. I am guessing you have a markup/CSS issue.
    – s_ha_dum
    Feb 7, 2013 at 0:43
  • Interesting... I am installing this on a site with an extraordinarily old theme - I suppose it's possible that that's the problem....
    – Morgan Kay
    Feb 7, 2013 at 0:45
  • Nope - I just tried it on a site with TwentyEleven, and I see the same problem - the ad appears at the top of the post instead of at the bottom.
    – Morgan Kay
    Feb 7, 2013 at 0:48
  • Try replacing return $the_ad; with return 'fake-ad';. That should tell you if the ad is being placed at the end of the post. If 'fake-ad' shows up at the end of the post the code works and you have an HTML/CSS formatting problem.
    – s_ha_dum
    Feb 7, 2013 at 0:48
  • If I replace return $the_ad' with return 'fake-ad', then "fake-ad" shows up at the bottom of the post, and the ad still shows at the top. So the wpa_choose_ad function is apparently displaying the ad, then the content is getting filtered.
    – Morgan Kay
    Feb 7, 2013 at 0:53

1 Answer 1


the_post_thumbnail is echoing content. You need get_the_post_thumbnail instead. That is your problem.

I believe you should be able to swap this: $the_ad = the_post_thumbnail();, for this: $the_ad = get_the_post_thumbnail();

  • Yes, of course! I should have thought of that. Thank you so much!!
    – Morgan Kay
    Feb 7, 2013 at 1:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.