[英]How to show post from just two categories on Wordpress Home page?
主頁上只需要顯示兩個類別。 誰能幫忙。
您可以使用WP_Query獲取帖子列表,並在循環中顯示它
范例:
$the_query = new WP_Query( array( 'category_name' => 'staff,news' ) );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
在您的functions.php
文件中粘貼以下代碼:
我假設您要顯示ID為5和9的兩個類別的類別。
function kiran_home_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '5,9');
}
}
add_action( 'pre_get_posts', 'kiran_home_category' );
說明:
kiran_home_category
只是該函數的自定義名稱。 那可以是任何名字。 它的工作方式是將一個函數附加到動作鈎子pre_get_posts
。 因此,在獲取帖子之前,將調用kiran_home_category
函數。 然后在函數中,我將查詢更改為僅加載ID為5和9的類別
在wordpress WP_query中, category__in參數用於選擇帶有帖子的類別。
<?php
$query = new WP_Query( array( 'category__in' => array( 2, 6 ),'post_status'=>'publish','orderby'=>'menu_order','order'=>'Asc' ) );
if($query->have_posts()):
echo '<ul>';
while ( $query->have_posts() ) : the_post();
echo '<li>' . get_the_title() . '</li>';
endwhile;
echo '</ul>';
endif;
?>
有關wordpress查詢的更多信息, 請單擊此處 ,您可以閱讀更多信息。
<?php
$args = array( 'post_type' => 'post', 'posts_per_page' => -1,'category_name' => array('Latest News','News') );
$loop = new WP_Query( $args );
if($loop->have_posts()):
?><ul>
<?php
while ( $loop->have_posts() ) : $loop->the_post();
?>
<li> <span class="date"><?php echo get_the_date( 'd F Y');?></span>
<h3><?php echo get_the_title();?></h3>
<?php echo $description = get_the_content(); ?>
</li>
<?php endwhile;?>
</ul>
<?php endif;?>
<?php wp_reset_postdata(); ?>
通常在page.php或single.php中執行以下操作,或者如果您要為類別創建自定義頁面,則可以執行category-samplecat.php。
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => array('samplecat', 'anothercat'),
'paged' => $paged
);
$arr_posts = new WP_Query($args);
然后執行常規的if,while語句。
if($arr_posts->have_posts() ) :
// Start the loop.
while ( $arr_posts->have_posts() ) :
$arr_posts->the_post();?>
<?php endwhile;
endif;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.