我创建了自定义帖子和分类法。现在我想在以下格式的类别下显示帖子。
-
分类名称1
- 发布1
- 发布2
- 发布3
- 全部发布
-
分类名称2
- 发布1
- 发布2
- 发布3
- 全部发布
-
分类名称4
- 发布1
- 发布2
- 发布3
- 全部发布
并继续那样。我找到了一个代码, 但是没有用。
代码
<?php
$taxonomy = 'category';
$param_type = 'category__in';
$term_args=array(
'orderby' => 'name', 'order' => 'ASC');
$terms = get_terms($taxonomy, $term_args);
if ($terms) {
foreach( $terms as $term ) {
$args=array(
"$param_type" => array($term->term_id), 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1, 'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<div class="category section">
<h3><?php echo 'Category '.$term->name;?></h3>
<ul><?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark"
title="Permanent Link to <?php the_title_attribute(); ?>">
<?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
</div>
<?php}
}}
wp_reset_query(); // Restore global post data stomped by the_post().?>
所以请帮助我。如何解决。谢谢
#1
我假设你正在尝试从”分类标准”类别中获取任何帖子。
<?php
$cat_terms = get_terms(
array('category'), array(
'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 6 //specify yours
)
);
if( $cat_terms ) :
foreach( $cat_terms as $term ) :
//var_dump( $term );
echo '<h3>'. $term->name .'</h3>';
$args = array(
'post_type' => 'post', 'posts_per_page' => 10 //specify yours
'post_status' => 'publish', 'tax_query' => array(
array(
'taxonomy' => 'category', 'field' => 'slug', 'terms' => $term->slug, ), ), 'ignore_sticky_posts' => true //caller_get_posts is deprecated since 3.1
);
$_posts = new WP_Query( $args );
if( $_posts->have_posts() ) :
while( $_posts->have_posts() ) : $_posts->the_post();
echo '<h3>'. get_the_title() .'</h3>';
endwhile;
endif;
wp_reset_postdata(); //important
endforeach;
endif;
请注意, 从3.1开始不推荐使用caller_get_posts参数。请始终向Codex查询最新的代码说明, 并且不要使用不建议使用的代码。
WP_Query()-WordPress Codex
#2
你可以尝试这样做, 你可能希望将其移入模板而不是将其移入函数中, 确保$ tax是正确的分类法, 如果不使用本机wordpress, 请更改post_type。
function get_taxonomy_and_post() {
$tax = 'category'; // Your Taxonomy, change it if you not using wordpress native category
$terms = get_terms( $tax , array( // get all taxonomy terms
'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => 0, ));
//Loop throug each taxonomy terms, foreach ( $terms as $term ) {
//Query argument for post
$args = array(
'post_type' => 'post', // Or Custom Post Type, 'order' => 'DESC', 'orderby' => 'date', 'taxonomy' => $tax, 'term' => $term->slug, // Query posts for each term based on term slug
);
$query = new WP_Query( $args );
$posts = $query->get_posts();
echo '<div class="category section"><h3>Category '.$term->name.'</h3><ul>';
if ( $posts ) {
foreach ( $posts as $post ) {
echo '<li><a href="'.$post->guid /**use get_permalink( $post->ID ) if you want the custom permalink**/.'">'.$post->post_title.'</a><li>';
}
}
echo '</ul></div>';
}
}
add_action('wp_head', 'get_taxonomy_and_post');
评论前必须登录!
注册