在主页上手动显示特定帖子

时间:2016-01-30 14:21:47

标签: php wordpress

循环显示我们使用的所有WordPress帖子:

<?php 
    if( have_posts() ) :
         while( have_posts() ) : the_post(); ?>
    <p><?php the_content(); ?></p>
<?php 
   endwhile;
   endif;
?>

仅显示我们使用的第一篇帖子:

<?php 
    if( have_posts() ) :
         if( have_posts() ) : the_post(); ?>
    <p><?php the_content(); ?></p>
<?php 
   endif;
   endif;
?>

我的问题是,我可以手动选择要在我的主页上显示哪些帖子而不进行循环播放吗?例如,让我说我只想在我的主页上显示post1,post3和post6,我可以这样做吗?

3 个答案:

答案 0 :(得分:1)

不使用while循环,因为帖子只包含一个帖子。

<?php /*
Template Name: Query Single Post
*/
get_header(); ?>
    <?php query_posts('p=>40'); ?>
    <?php if (have_posts()) : the_post(); ?>
        <h4><?php the_title(); ?></h4>
        <?php the_content(); ?>
    <?php endif;?>
<?php get_footer(); ?>

答案 1 :(得分:0)

试试此代码

<?php /*
Template Name: Query Single Post
*/
get_header(); ?>
    <?php query_posts('p=40'); ?>
    <?php while (have_posts()) : the_post(); ?>
        <h4><?php the_title(); ?></h4>
        <?php the_content(); ?>
    <?php endwhile;?>
<?php get_footer(); ?>

我挑选的那个ID为40.所以,我设p = 40。在我选择使用此页面的页面上,我选择了“查询单个帖子”帖子模板。点击保存并刷新我的页面。

答案 2 :(得分:0)

您需要使用pre_get_posts过滤器。

代码:

<?php
add_action('pre_get_posts', function($query){
    if ( !$query->is_home() or !$query->is_main_query() )
        return false;

    # And here you can use any parameters from [WP_Query Class](https://codex.wordpress.org/Class_Reference/WP_Query)
    # For example
    $query->set('post__in', [10, 15, 16]);
});
相关问题