我创建了自定义帖子和分类。现在我想这样做。
继续那样。 我找到了一个代码,但是没有用。
代码
<?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().?>
所以请帮助我。如何解决它。 感谢
答案 0 :(得分:3)
我假设您正在尝试从分类法Category
中抓取任何帖子。
<?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
答案 1 :(得分:0)
您可以尝试这样做,您可能希望将其移到模板中而不是将其放在函数中,确保$tax
是正确的分类,如果您不使用本机,也请更改post_type
wordpress Post
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');