WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Unable to retrieve the_content from custom post type (4 posts)

  1. delFUEGO
    Member
    Posted 4 years ago #

    So, I created a custom Post Type named "fact" and added this bit of code into the sidebar to display one randomly...

    <?php
    	$random_posts = get_posts('numberposts=2&orderby=rand&post_type=fact');
    	foreach( $random_posts as $post ) :
    ?>
    <?php the_title();?>
    <?php the_content();?>
    <img src="<?php the_post_thumbnail(); ?>">
    <?php endforeach; ?>

    ...and it works almost fine. It retrieves the title of the custom post and the attached image, but "the_content" it retrieves belongs to a regular post, not the custom post type.

    1) Any clues why its happening or how to fix it?
    Also, while we are at it:
    2) How to grab the attached image only if there is one assigned? I hate seeing and empty <img src=""> tag on the source code of the page.

  2. delFUEGO
    Member
    Posted 4 years ago #

    Never mind question 1, I googled a little bit more and found that a lot of WP methods use globals. I had to add this to narrow it to what I needed...

    setup_postdata($post);

    Still, question 2 remains, any clues?

  3. mfalaha
    Member
    Posted 4 years ago #

    Just use has_post_thumbnail

    <?php if(has_post_thumbnail()) {?>
    <img src="<?php the_post_thumbnail();?> />
    <?php } ?>

    More info: http://codex.wordpress.org/Function_Reference/has_post_thumbnail

  4. delFUEGO
    Member
    Posted 3 years ago #

    Thank you very much, that should do it, you rock!

Topic Closed

This topic has been closed to new replies.

About this Topic