Retriever
Retriever

Reputation: 250

How can I query custom field in wp_posts with WP_Query

I have a question about WP_Query.

I added custom field and named 'custom_cat' in 'wp_posts' table.

But I can't get posts with my custom field.

I tested like,

$wp_query->query('post_type=post&custom_cat=1');

This statement not worked.

How Can I get posts for my purpose.

Thank you.

Upvotes: 1

Views: 394

Answers (1)

wbdlc
wbdlc

Reputation: 1089

You will need to read the docs on WP_Query, you will need to specifically read about using a meta_key in your $args. Ref: https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

$args = array(
'post_type'  => 'post',
'meta_key'   => 'custom_cat',
'orderby'    => 'meta_value_num',
'order'      => 'ASC',
'meta_query' => array(
    array(
        'key'     => 'custom_cat',
        'value'   => array( 1 ),
        'compare' => 'IN',
    ),
),
);
$query = new WP_Query( $args );

Upvotes: 1

Related Questions