WP — Get posts by category?

2019-04-04 09:17发布

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?

标签: php wordpress
6条回答
够拽才男人
2楼-- · 2019-04-04 09:55

Create a taxonomy field category (field name = post_category) and import it in your template as shown below:

<?php
          $categ = get_field('post_category');  
          $args = array( 'posts_per_page' => 6,
         'category_name' => $categ->slug );
          $myposts = get_posts( $args );
          foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
            //your code here
          <?php endforeach; 
          wp_reset_postdata();?>
查看更多
ら.Afraid
3楼-- · 2019-04-04 09:56
add_shortcode( 'seriesposts', 'series_posts' );

function series_posts( $atts )
{ ob_start();

$myseriesoption = get_option( '_myseries', null );

$type = $myseriesoption;
$args=array(  'post_type' => $type,  'post_status' => 'publish',  'posts_per_page' => 5,  'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>'; 
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>'; 
endwhile;
echo '</ul>'; 
}
wp_reset_query();




return ob_get_clean(); }

//this will generate a shortcode function to be used on your site [seriesposts]

查看更多
走好不送
4楼-- · 2019-04-04 10:04

Check here : http://codex.wordpress.org/Template_Tags/get_posts

Note: The category parameter needs to be the ID of the category, and not the category name.

查看更多
甜甜的少女心
5楼-- · 2019-04-04 10:07

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.

查看更多
相关推荐>>
6楼-- · 2019-04-04 10:08

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

查看更多
做自己的国王
7楼-- · 2019-04-04 10:20

Use WP_Query,

$args = array(
   'category_name'=>'your-category-slug',
    'posts_per_page'=> 10,
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
    //Post data
    echo get_the_post_thumbnail(get_the_ID());
endwhile;

For reference, see here

查看更多
登录 后发表回答