Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP -- Get posts by category?

Tags:

php

wordpress

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?

like image 512
jordan Avatar asked Aug 10 '12 21:08

jordan


People also ask

How do I display custom post type category wise in WordPress?

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!

What is Wp_reset_postdata ()?

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.

What is Get_post in WordPress?

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.


3 Answers

'category_name'=>'this cat' also works but isn't printed in the WP docs

like image 198
tim Avatar answered Oct 24 '22 10:10

tim


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.

like image 36
Eray Avatar answered Oct 24 '22 11:10

Eray


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.

like image 2
KregHEk Avatar answered Oct 24 '22 09:10

KregHEk