我已经以WordPress主题注册了CPT。我可以按post_type获取循环中的帖子,但是当我尝试按category_name获取帖子时。它没有给我结果。
add_action( 'init', 'achivement', 0 );
function achivement() {
register_post_type( 'achivement', array(
'label' => __( 'Achivement', 'achivement-free' ),
'description' => __( 'Achivement custom post type.', 'achivement-free' ),
'public' => false,
'has_archive' => false,
'publicaly_queryable' => false,
'query_var' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-networking',
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'hierarchical' => true,
'menu_position' => 20,
'supports' => array(
'title',
'editor',
),
'capability_type' => 'post',
'labels' => array(
'name' => __( 'Achivements', 'achivement-free' ),
'singular_name' => __( 'Achivement', 'achivement-free' ),
'menu_name' => __( 'Achivement', 'achivement-free' ),
'all_items' => __( 'Achivements', 'achivement-free' ),
'add_new' => __( 'Add Achivement', 'achivement-free' ),
'add_new_item' => __( 'Add Achivement', 'achivement-free' ),
'edit' => __( 'Edit', 'achivement-free' ),
'edit_item' => __( 'Edit Achivement', 'achivement-free' ),
'new_item' => __( 'New Achivement', 'achivement-free' ),
'search_items' => __( 'Search Achivements', 'achivement-free' ),
'not_found' => __( 'No Achivements found', 'achivement-free' ),
'not_found_in_trash' => __( 'No Achivements found in Trash', 'achivement-free' ),
'parent' => __( 'Parent Achivements', 'achivement-free' ),
)
) );
register_taxonomy(
'achivement-category',
'achivement',
array(
'label' => __( 'Category' ),
'rewrite' => array( 'slug' => 'achivement-category' ),
'hierarchical' => true,
)
);
}
这是我编写的循环,用于在WordPress中按category_name获取帖子。
$posts = get_posts(array(
'post_status' => 'publish',
'posts_per_page' => -1,
'post_type' => 'achivement',
'order' => 'ASC',
));
if( $posts ):
foreach( $posts as $post ):
setup_postdata( $post );
var_dump(get_the_category());
endforeach;
wp_reset_postdata();
endif;
我知道也许会有一个愚蠢的小错误,但我无法理解。如果您能找到该错误,请告诉我。我会非常感激。
谢谢
从下面的答案中得到了一个有效的查询。我要在这里粘贴给其他人。
$args = array(
'post_type' => 'achivement',
'posts_per_page' => 500,
'tax_query' => array(
array(
'taxonomy' => 'strike',
'field' => 'slug',
'terms' => array( 'strike-1' ),
),
),
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo get_the_title().'<br />';
endwhile;
wp_reset_postdata();
else :
_e( 'Sorry, no posts matched your criteria.' );
endif;
答案 0 :(得分:1)
首先,不要使用'posts_per_page' => -1,
,这会严重影响查询速度。
第二,只需使用WP_Query
并指定分类参数,如此处所述:https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters
类似的事情应该起作用
$args = array(
'post_type' => 'achivement',
'posts_per_page' => 500,
'tax_query' => array(
array(
'taxonomy' => 'achivement-category',
'field' => 'name',
),
),
);
$query = new WP_Query( $args );