我用這段代碼在functions.php中創建了一個自定義帖子型別。
function create_recipes() {
register_post_type('recipe', [
'public' => true,
'show_in_rest' => true,
'labels' => [
'name' => 'Recipes',
'add_new_item' => 'Add New Recipe',
'edit_item' => 'Edit Recipe',
'all_items' => 'All Recipes',
'singular_name' => 'Recipe',
],
'supports' => ['title', 'editor'],
'rewrite' => ['slug' => 'recipes'],
'menu_icon' => 'dashicons-media-archive',
'has_archive' => true,
'taxonomies' => array('category'),
'supports' => array( 'title', 'editor', 'author', 'thumbnail' ),
]);
}
add_action('init', 'create_recipes');
現在我正在嘗試獲取/顯示我在前端創建的所有帖子,這些帖子在此處具有不同的類別
<?php
$recipes = new WP_Query([
'post_type' => 'recipe',
'category' => '01'
]);
while($recipes->have_posts()):
$recipes->the_post();
?>
<div class="sub-column">
<div class="sub-cat">
<?php the_category(); ?>
</div>
<a>
<div class="sub-thumbnail">
<?php echo the_post_thumbnail(); ?>
</div>
</a>
<div class="sub-title">
<h4><?php the_title(); ?></h4>
</div>
</div>
<?php endwhile; ?>
但我無法讓它作業。現在我得到了所有不同的類別,這很好,但是具有相同類別的帖子應該直接列印在上面,而不是上面的相同類別名稱。
幫助appriciated!
uj5u.com熱心網友回復:
您需要使用“get_cat_name( $category_id )”而不是“the_category()”
因此,在函式 get_cat_name() 中,您需要傳遞您在 wp_query 中傳遞的相同類別 ID。
uj5u.com熱心網友回復:
這是您的代碼,如果您希望顯示所有帖子,那么您不需要通過任何類別,您只需要通過 post_per_page
// WP_Query arguments
$args = array(
'post_type' => array( 'recipes' ),
'post_status' => array( 'publish' ),
'posts_per_page' => '-1',
'order' => 'DESC',
'orderby' => 'id',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
echo get_the_title();
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
如果您希望顯示相應類別的特定帖子,則可以使用 slug、term_id 等,并且您需要在引數中注入 tax_query 此處是基于 slug 的示例代碼
// WP_Query arguments
$args = array(
'post_type' => array( 'recipes' ),
'post_status' => array( 'publish' ),
'posts_per_page' => '-1',
'tax_query' => array(
array(
'taxonomy' => 'category', // taxonomy slug
'field' => 'slug', //do not change this if you wisht to fetch from slug
'terms' => 'bob' //slug name
)
)
'order' => 'DESC',
'orderby' => 'id',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
echo get_the_title();
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/397650.html
標籤:php WordPress的 邮政
