WordPress get_post() Returns Wrong
There’s nothing more annoying than thinking you’re doing everything right and a function is not returning what you’d expect. Of course it’s you… in the back of your mind you know that’s true… but that doesn’t help when you just can’t figure something out!
I recently was working with get_post(), a built-in function in WordPress (and what you should use most of the time instead of query_posts()), and was coming across an issue.
Problem
You set the arguments for WordPress’s get_post() function and you aren’t getting the results you should be.
I personally had an issue with it not showing the correct category of posts and instead pulling from the custom post type.
Solution
Don’t throw your computer across the room yet! Instead just add
global $post;
directly before you call get_post().
The problem is that you’re calling the get post function after the page loop – and that will screw everything up. So you’ve got to “reset” it by using “global $post”.
Example Coding
<?php global $post; $args = array( 'posts_per_page' => 3,'category' => 8, 'post_type' => 'post' ); $catPost = get_posts( $args ); echo "<ul>"; foreach ($catPost as $post) { ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php } ?> </ul>
Check out the WordPress Documentation for get_posts() for more.