1

I'm developing a WordPress theme. I am selecting one post as a 'featured post' from the customizer settings. I want to display this post differently on home page. I'm using following code to get the post on home.php:

$featured_post = get_post( get_theme_mod( 'featured_post_id' ) );

This code works perfectly to get the post. But, after selecting this post as a featured post, if I trash it, it still gets displayed as a featured post on home page. If I 'Delete it Permanently', it doesn't get displayed.

How do I use get_post() to get the post that is not trashed?

3

That's not how get_post() works. Trashing the post doesn't change the value of the theme mod, and the theme mod is still going to point to that post in the database, so get_post() will dutifully retrieve it as long as it's there.

It's up to you to make sure its status is what you want before display:

$featured_post = get_post( get_theme_mod( 'featured_post_id' ) );

if ( $featured_post && $featured_post->post_status === 'publish' ) {
    // Display post
}

You could also do a WP_Query or get_posts() (plural) to query posts with the status publish and the ID that you have, but it's probably going to end up more lines of code and slightly slower than just checking the status anyway.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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