0

I have a custom post type - on a single page it displays all kinds of information for the post type. There are 10 posts altogether. Below the info I have a slideshow as part of a loop that displays the other posts. However this is always in alphabetical order.

I would like to be able to recognise the current single page and display it as the first entry in the loop. The loop uses a WP_Query so I need to figure out a way to have it sort this way.

How would I be able to do this? Does it involve a meta query?

EG: If current post is Post7, order by Post7, Post1, Post2, Post3 etc.

4
  • Simply orderby by date which is default in WP_Query Dec 3, 2015 at 11:16
  • I don't mean the "latest" post, I mean the post that is being displayed in the browser - so for example if it shows "post7" in browser, the order for query is "post7, post1, post2, post3 etc." Dec 3, 2015 at 11:20
  • That is info that should be inside your question Dec 3, 2015 at 11:25
  • OK, it's there now Dec 3, 2015 at 11:29

1 Answer 1

1

You can most probably reuse the loop and run it twice. The first time to display the queried post and the second time to display the rest

// Get the current post id being viewed
$current_post_id = get_queried_object_id();

// Define your query and query arguments
$args = [
    // All your arguments
];
$q = new WP_Query( $args );

if ( $q->have_posts() ) {
    // Run the loop for the first time to display the post equal to the queried one
    while ( $q->have_posts() ) {
    $q->the_post();

        if ( get_the_ID() == $current_post_id ) {
            // Display the post equal to the queried one
        }

    } // endwhile

    // Rewind the loop so that we can run it again
    $q->rewind_posts();

    // Run the loop for the second time to display all the other posts
    while ( $q->have_posts() ) {
    $q->the_post();

        if ( get_the_ID() != $current_post_id ) {
            // Display all the other posts skipping the queried one
        }

    } // endwhile

    // Clean after ourselves, good housekeeping
    wp_reset_postdata();
} // endif
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.