Miller
Miller

Reputation: 105

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?

Upvotes: 0

Views: 14336

Answers (3)

Keusta
Keusta

Reputation: 11

$my_query = new WP_Query( array(
  'post_type' => 'your_post_type_here',
  'p' => '$id'));// need to set the simple quote '$id'

if( $my_query->have_posts() ){
    // start the loop
}else{
    // no result message
}

dont forget to add simple quote to '$id' because i tried without and it was not working in my case. hope it helps someone in the future !

Upvotes: 0

Pieter Goosen
Pieter Goosen

Reputation: 9941

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

Upvotes: 2

Miller
Miller

Reputation: 105

I found the solution.

create this variable $id= get_the_ID();

and add 'p'=>$id to $args.

Upvotes: 5

Related Questions