Wordpress:按类别获取帖子

时间:2014-11-15 19:01:50

标签: php wordpress

我是一个wordpress新手,并试图找到我想要做的好解决方案。基本上我要获得一个具有特定标签' detination'的类别列表。一旦我这样做,我想查询具有上述过滤器的所有帖子。

所以我现在拥有的是这样的:

$destCategories = get_categories( array('tag' => 'destination' , 'exclude' => '1') );
$posts = get_posts($destCategories);

但是,get_categories会返回一个类别特定信息数组,这些信息无法真正用作get_posts的过滤器。有没有人有关于如何解决这个问题的建议?我本可以手动迭代destCategories数组并构造一个包含所有类别名称的字符串,并将其用作get帖子中的过滤器,但我想知道是否有更优雅的解决方案可用。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

get_categories()没有标记参数:http://codex.wordpress.org/Function_Reference/get_categories#Parameters 我想你可以尝试传递一个分类数组,但我不知道它会如何解决。 如果您想按标记获取帖子,可以使用get_posts():http://codex.wordpress.org/Template_Tags/get_posts#Taxonomy_Parameters

您可以尝试这样的事情:

$args = array(
    'post_type' => 'post',
    'tag' => 'destination',
);
$query = new WP_Query( $args );

if ($query->have_posts()):
    while ($query->have_posts()): $query->the_post(); ?>
        <?php the_title(); ?>
<?php
    endwhile;
endif;
?>

答案 1 :(得分:0)

好的,所以我最终得到了类似的东西,这似乎有效:

    $query = get_posts( $myfilter );
    $destCategories = get_categories( array('tag' => 'destination' , 'exclude' => '1') );

?>

<div id="main">
    <div id="content clearfix">
        <p>this is using front-page.php</p>
        <?php //echo var_dump($destCategories) ?>
        <?php 
        if ( have_posts( $myfilter ) ) {
            foreach ( $destCategories as $category ) :
                $posts = get_posts( array('category_name' => $category->slug) );
                    foreach ( $posts as  $post ) :
 ?>
               <h3><a href="<?php the_permalink(); ?>"> <?php echo the_title(); ?> </a></h3>

                <?php
                    endforeach;
                    wp_reset_postdata();
                    //the_content();
            endforeach;
?>
相关问题