WP - 按类别获取帖子?(WP — Get posts by category?)

2019-07-30 22:15发布

我在我的网页模板,以此来获得通过他们的类别的职位:

<?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 } ?>

但它检索所有的职位来代替。 不只是那些标记见证。 任何想法,我做错了什么?

Answer 1:

点击这里: http://codex.wordpress.org/Template_Tags/get_posts

注:类参数需要是该类别的ID,而不是类别名称。



Answer 2:

“CATEGORY_NAME” =>“这个猫”也工作,但没有在WP文档打印



Answer 3:

使用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;

作为参考, 在这里看到



Answer 4:

您可以在参数使用“CATEGORY_NAME”。 http://codex.wordpress.org/Template_Tags/get_posts

注:CATEGORY_NAME参数必须是一个字符串,在这种情况下,类别名称。



Answer 5:

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(); }

//这将产生一个短码功能,在您的网站上使用[seriesposts]



Answer 6:

创建一个分类字段类别(字段名= post_category),按照下图在你的模板导入:

<?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();?>


文章来源: WP — Get posts by category?
标签: php wordpress