簡體   English   中英

自定義帖子類型顯示帖子所屬類別

[英]Custom Post Type displays post belong on the category

我有一個自定義帖子類型advice和分類法adcat 我想顯示屬於該類別的所有帖子。

可以說我有4個類別,即“游戲”,“旅游”,“菜餚”,“酒店”,這4個類別也是菜單。 例如,如果我單擊類別之一:所有顯示酒店的帖子都應顯示。

順便說一下,我曾經用這段代碼來顯示wordpress默認類別:

<?php $catname = wp_title('', false); ?>
<?php $posts = get_posts("category_name=$catname&numberposts=8&offset=0");
foreach ($posts as $post) : start_wp(); ?>

//html output
<h1><?php the_title(); ?></h1>

<?php endforeach; ?>

這不適用於自定義帖子“分類法”,任何建議都會有所幫助,謝謝

嘗試這樣的事情,這是按類別ID獲取帖子的示例

$args = array( 'cat' => $cat_id, 'post_type' => 'advice', 'posts_per_page' => -1 );
    $loop = new WP_Query( $args );      
    while ( $loop->have_posts() ) : $loop->the_post();
         the_title();
    endwhile; 
wp_reset_postdata();

您也可以使用類別名稱。

$args = array('category_name' => 'catname', 'post_type' => 'advice', 'posts_per_page' => -1 );

您可以根據需要使用post_per_page,我為所有帖子添加了-1

我不太了解您的用語。 在談論adcat ,它是自定義分類法還是內置分類法category的術語。 如果adcat是自定義分類法,則應在tax_query中使用WP_Query ,而不是類別參數。

請記住,類別和自定義分類法都是分類法,其直接子級稱為術語,而其直接子級稱為子術語

您也不應使用wp_title()獲取查詢對象。 您應該使用get_query_var()來獲取查詢的對象。 對於類別將是cat ,分類將taxonomy和術語term 看看get_categoriesget_taxonomiesget_terms的返回值

$category = get_query_var( `cat` );
$cat_slug = $category->slug;

現在,您可以將$cat_slug作為category_name返回到自定義查詢

編輯

我很快重新考慮了整個過程,並檢查了您的評論。 為什么不直接復制index.php並將其重命名為taxonomy.php。 此處完全不需要自定義查詢。 taxonomy.php中的默認循環應該做到這一點

編輯2

要進一步閱讀,請查看以下文章

不確定我是否正確閱讀了您的答案,但是我假設您是要按照正確的分類學術語搜索帖子? 因此,在adcat分類中,您將“游戲”,“旅游”,“菜”,“酒店”作為您的術語或類別。 最好的選擇是在查詢參數中使用tax_query 這是使用WP_Query()對象執行此操作的方法。

<?php 

$args = array( 
    'post_type' => 'advice',
    'posts_per_page' => 8,
    'tax_query' => array(
    'taxonomy' => 'adcat',
    'terms' => array('games', 'tours', 'dishes', 'hotels'),
    'field' => 'slug'
    )
);

$query = new WP_Query($args); 

if($query->have_posts()) : while($query->have_posts()) : $query->the_post(); ?>

    <h1><?php the_title(); ?></h1>

<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>

重要說明:使用WP_Query時,您將覆蓋默認的帖子數據。 因此,為了取回該數據,您只需使用wp_reset_postdata()如循環結束后在上例中所見。

試試這個也許行得通...我寫了一條便條,這樣您就可以看到發生了什么..希望對您有所幫助

<?php
    // Get the term/category of the post
    $terms = get_the_terms( $post->ID , 'advice-cat' );
     foreach ( $terms as $term ) {
     $term_link = get_term_link( $term, 'advice cat' );
    }
    //WordPress loop for custom post type
    $terms = get_the_terms( $post->ID , 'advice-cat' );
     $my_query = new WP_Query('post_type=advice&advice-cat=' . $term->name . '&posts_per_page=-1');
          while ($my_query->have_posts()) : $my_query->the_post(); ?>

     // output content

     <?php the_title(); ?>           


    <?php endwhile;  wp_reset_query(); ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM