Search code examples
phphtmlwordpresscodex

query single post with wp_query


I retrieved the latest posts in front page with WP_query loop, coz i figured out that's the best solution. but i want to display the post was clicked in front page.

what's the best method for single post query?

I used wp_query again in single.php(is there any better idea?)

$args =  array('name' => $the_slug,
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 1);
$the_query = new WP_Query( $args );
<?php while ( $the_query->have_posts() ) :?>

    <?php $the_query->the_post(); ?>
<p><?php $content = get_the_content('Read more');
print $content; ?></p>
<?php endwhile; ?><!-- end of the loop -->
<!-- put pagination functions here -->
    <?php wp_reset_postdata(); ?>
<?php else:  ?>

<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>

<?php endif; ?>

the problem is it always retrieved the latest post, even i click on any post id. how can i fix that problem?


Solution

  • Don't run a custom query in place of the main loop. You can simply just do the following, it is faster, more reliable and the correct way

    <?php
                // Start the Loop.
        while ( have_posts() ) : the_post(); 
    
            // YOUR LOOP ELEMENTS
    
        endwhile;
    ?>
    

    EDIT

    The above code is called the loop, the default loop to be exact. This is not a query. What this loop does, it returns only the information retrieved by the main query. The main query runs on every page that loads. The main query is specific for every page

    For more info, read my post on WPSE regarding this matter