[英]List all posts in custom post type by taxonomy not working
我正在尝试按分类法获取自定义帖子类型中所有帖子的列表,我在这段代码上停留了 3 天,现在我和父亲一起学习,他给了我一个提示,为什么我的代码不起作用,他说我有太多的参数我会告诉你代码我希望任何人都可以帮助我理解为什么它不起作用,也许如果你真的用英语解释代码
print_r(Array(
"1"=>"first",
"2"=>"second"
));
// just try to remove args that you don't need
//actually you need only one
$args = array(
'tax_query' => array(
'taxonomy' => 'your-custom-taxonomy',
'field' => 'slug',
'terms' => array( 'your-term' )
),
'post_type' => 'your-post-type'
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
$term = $wp_query->queried_object;
while($loop->have_posts()) : $loop->the_post();
//Output what you want
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
}
your-post-type
的自定义帖子类型your-custom-taxonomy
,并且您your-term
的分类术语集的帖子。您设置 arguments 的方式是正确的。
注意:如果您想获取自定义帖子类型的所有帖子,则不需要整个代码'tax_query'
部分。
我添加了一些注释来描述代码的作用:
$args = array( // define your arguments for query
'post_type' => 'your-post-type', // standard post type is 'post', you use a custom one
'tax_query' => array( // you check for taxonomy field values
array(
'taxonomy' => 'your-custom-taxonomy', // standard is 'category' you use a custom one
'field' => 'slug', // you want to get the terms by its slug (could also use id)
'terms' => 'your-term', // this is the taxonomy term slug the post has set
),
),
);
$loop = new WP_Query( $args ); // get post objects
// The Loop
if ( $loop ->have_posts() ) { // check if you received post objects
echo "<ul>"; // open unordered list
while ( $loop ->have_posts() ) { // loop through post objects
$loop ->the_post();
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>'; // list items
}
echo "</ul>"; // close unordered list
/* Restore original Post Data */
wp_reset_postdata(); // reset to avoid conflicts
} else {
// no posts found
}
希望这可以帮助!
编辑:如果您不知道如何使用 WP_Query
此代码将使您的 wordpress 帖子按标题和 output 标题和内容排序。 将其放入主题的模板文件中(了解有关模板文件的一些信息: https://developer.wordpress.org/themes/basics/template-hierarchy/ )。
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1, // limit the number of posts if you like to
'orderby' => 'title',
'order' => 'ASC'
);
$custom_query = new WP_Query($args);
if ($custom_query->have_posts()) : while($custom_query->have_posts()) : $custom_query->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content();?>
<?php endwhile; else : ?>
<p>No posts</p>
<?php endif; wp_reset_postdata(); ?>
你说你想使用自定义帖子类型并进行分类查询。 因此,您可以通过更改$args
中的 arguments 来调整它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.