【发布时间】:2017-05-30 09:06:16
【问题描述】:
首页只需要显示两个类别。谁能帮忙。
【问题讨论】:
-
链接?邮政?图片?
标签: php wordpress categories
首页只需要显示两个类别。谁能帮忙。
【问题讨论】:
标签: php wordpress categories
您可以使用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 的类别
【讨论】:
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查询click here的更多信息,您可以阅读更多信息。
【讨论】:
http://localhost/example.com/wp-admin/term.php?taxonomy=category&tag_ID=1&post_type=post&wp_http_referer=%2Fpneumocare.com%2Fwp-admin%2Fedit-tags.php%3Ftaxonomy%3Dcategory 在此示例中。您可以看到 tag_ID=1 即类别 id=1。这是类别号。
<?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;
【讨论】: