I'm using this in my page template to get posts by their category:
<?php
if (is_page(19)){
?>
<ul>
<?php
global $post;
$args = array( 'category' => 'Testimonial' );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li class="testimonial"><?php the_content(); ?></li><br/>
<?php endforeach; ?>
</ul>
<?php } ?>
but it's retrieving all posts instead. Not just the ones labeled Testimonial. Any idea what I'm doing wrong?
To display your custom post types on the same category page as your default posts, you need to add this code into your theme's functions. php or a site-specific plugin. $post_type = array ( 'nav_menu_item' , 'post' , 'movies' ); // don't forget nav_menu_item to allow menus to work!
wp_reset_postdata() restores the global $post variable to the current post in the main query (contained in the global $wp_query variable as opposed to the $sec_query variable), so that the template tags refer to the main query loop by default again. Example. Copy Expand code.
WordPress get_posts is a powerful function allowing developers to retrieve pieces of content from the WordPress database. You can specify in the finest detail which posts, pages, and custom post types you're looking for, get your custom result set, then filter and order the items like a PHP/MySQL ninja.
'category_name'=>'this cat' also works but isn't printed in the WP docs
Check here : https://developer.wordpress.org/reference/functions/get_posts/
Note: The category parameter needs to be the ID of the category, and not the category name.
You can use 'category_name' in parameters. http://codex.wordpress.org/Template_Tags/get_posts
Note: The category_name parameter needs to be a string, in this case, the category name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With