最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Access queried post ID in WP_Query

programmeradmin4浏览0评论

I'm trying to find out if it's possible to specify/define the currently queried post in WP_Query arguments, but having little luck. Not in the loop, but while the query itself is running. Specifically I want to use the post id to access other metadata.

An example of usage might be:

meta_key     => '_an_existing_meta_key',
meta_value   => get_post_meta($current_post_id, '_another_meta_key'),
meta_compare => '!='

Where $current_post_id is the actual currently queried post ID within the current query being run. Considering that the above example works fine with a hardcoded/specific post ID, it seems like it should work, but I'm having zero luck.

I'm specifically hoping to be able to use a function to define meta_value.

I'm trying to find out if it's possible to specify/define the currently queried post in WP_Query arguments, but having little luck. Not in the loop, but while the query itself is running. Specifically I want to use the post id to access other metadata.

An example of usage might be:

meta_key     => '_an_existing_meta_key',
meta_value   => get_post_meta($current_post_id, '_another_meta_key'),
meta_compare => '!='

Where $current_post_id is the actual currently queried post ID within the current query being run. Considering that the above example works fine with a hardcoded/specific post ID, it seems like it should work, but I'm having zero luck.

I'm specifically hoping to be able to use a function to define meta_value.

Share Improve this question asked Apr 12, 2020 at 0:00 gcoulsongcoulson 113 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

WordPress has quite a few global variables to choose from which may help. For example, you can use the global $post to get first post in the query.

global $post;
$my_meta_value = get_post_meta( $post->ID, '_another_meta_key', true );

Or you could reach directly into the $wp_query object posts array and grab the first post:

global $wp_query;

if( ! empty( $wp_query->posts ) ) {
    $my_meta_value = get_post_meta( $wp_query->posts[0]->ID, '_another_meta_key', true );
}
发布评论

评论列表(0)

  1. 暂无评论