Ray
Ray

Reputation: 9674

Manually show specific posts on homepage

To loop and show all WordPress posts we use:

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

And to show only the first recent post we use:

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

My question is, can I manually select what posts I want to show on my homepage without doing a loop? For example let's say I want to only show post1, post3, and post6 on my homepage, can I do that?

Upvotes: 1

Views: 570

Answers (3)

glutaminefree
glutaminefree

Reputation: 382

You need to use pre_get_posts filter.

Code:

<?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]);
});

Upvotes: 0

Domain
Domain

Reputation: 11808

Without using while loop because the post contain only one post.

<?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(); ?>

Upvotes: 1

Jim
Jim

Reputation: 16

Try this code

<?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(); ?>

The one I picked had an ID of 40. So, I set p=40. On the page I chose to use this on, I selected the "Query Single Post" post template. Clicked save and refreshed my page.

Upvotes: 0

Related Questions