Ahsan aslam
Ahsan aslam

Reputation: 1199

Get WP_Query Object with mysql custom query in wordpress

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?

Upvotes: 1

Views: 1100

Answers (1)

Pieter Goosen
Pieter Goosen

Reputation: 9941

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

Upvotes: 1

Related Questions