1

I have a custom mysql query

$search_query_location="SELECT wp_posts.* FROM wp_postmeta wher post_id IN (112233,445566,77441,145,254)";

I can run above query to get data with "wpdb" function like

$wpdb->get_results($search_query_location, OBJECT);

It return array of post like

Array

(
    [0] => stdClass Object
        (
            [ID] => 11923
            [post_author] => 1
            [post_date] => 2015-06-23 08:05:30
         )
)

but I need

WP_Query Object in return of "new WP_Query" function

WP_Query Object
(
    [query] => Array
        ()
     [posts] =Array ()
)

If I use WP_Query along with the arguments post__in and posts_per_page then result come in WP_Query Object with default sorting order (that is post id) but I need sorting order that I have defined in my custom query that is (112233,445566,77441,145,254) posts ids How can I get WP_Query Object using custom mysql query?

1 Answer 1

1

The orderby parameter accepts the post__in sorting value as a possible way to sort posts returned. With orderby set to post__in, the posts will be returned in the order they are entered into the post__in parameter.

The following code

$args = [
    'post__in' =>[3, 1, 2],
    'orderby' => 'post__in'
];

$q = new WP_Query( $args );

will return posts 1,2, and 3 in the following order

3, 1, 2

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.