lucemia
lucemia

Reputation: 6627

WordPress Query with meta_key not work as expect

For some reason, I cannot filter post via custom fields

For example, the post is insert in this way.

function insert_post($story)
{
    $post = [
        // "post_content" => $story["extra"]["content"],
        // "post_content_filtered" => wp_json_encode($story["extra"]["story_data"]),
        "post_status" => "draft",
        "meta_input" => [
            "glia_story_id" => $story["id"]
        ]
    ];

    debug($story["id"] . "->" . wp_insert_post($post));
}

if I query this way, query results are always empty.

// FIXME: not work
$args = [
    'meta_value' => $story_id,
    'post_type' => 'any',
];

$the_query = new WP_Query($args);

debug($story_id . "posts" . $the_query->have_posts());

On the other hand, if I use meta_query, query will always return all

// FIXME: not work
$args = [
    'meta_query' => [["glia_story_id"=>$story_id]]
];

$the_query = new WP_Query($args);

debug($story_id . "posts" . $the_query->have_posts());

Solution

The issue is due to WP_Query will ignore draft posts by default. So the query need to override to accept draft posts

$args = [
    'meta_value' => $story_id,
    'post_status' => "any"
];

$the_query = new WP_Query($args)

Upvotes: 0

Views: 90

Answers (1)

mikerojas
mikerojas

Reputation: 2338

I think you just need to add some keys to your meta query (your second example) like below:

$args = [
    'meta_query' => [
        [
            "key" => "glia_story_id",
            "value" => $story_id
        ]
    ]
];

$the_query = new WP_Query($args);

debug($story_id . "posts" . $the_query->have_posts());

Upvotes: 1

Related Questions