有没有方法通过元值查看帖子是否存在?如何根据元值查看帖子是否存在
例如,假设我想查看另一个帖子是否具有唯一的“pictureID”元值,如果有,请执行其他操作。
有没有一种方法可以在PHP中编写该子句?
谢谢
有没有方法通过元值查看帖子是否存在?如何根据元值查看帖子是否存在
例如,假设我想查看另一个帖子是否具有唯一的“pictureID”元值,如果有,请执行其他操作。
有没有一种方法可以在PHP中编写该子句?
谢谢
如果你不知道的帖子ID,然后
可以使用自定义的WordPress查询根据检查后的元键像
global $wpdb;
$wpdb->get_results("select * from $wpdb->postmeta where meta_key = 'pictureID' ");
然后你可以得到al l以帖子ID结果,然后获取该帖子数据。
希望这有助于;)
第一次尝试获取meta值的岗位get_post_meta()
$postMetaValue=get_post_meta($postId,"meta_key",true);
if($postMetaValue=='pictureID')
{
//do as you want
}
您可以通过meta_key
使用meta_query
参数使用标准WP_Query
做回帖子和EXISTS
比较类型。
// query for all posts with the pictureID meta key set
$args = array(
'post_type' => 'post', // or your_custom_post_type
'meta_query' => array(
array(
'key' => 'pictureID',
'compare' => 'EXISTS',
),
),
}
// create a custom query
$my_query = new WP_Query($args);
// loop over your query, creating a custom The Loop
if ($my_query->have_posts()): while ($my_query->have_posts()): $my_query->the_post();
// $post is now posts that have a pictureId meta value
endwhile; endif;
// reset $post
wp_reset_postdata();
如果你想迅速抢占具有此meta_key集,你可以去到数据库中直接(绕过缓存等)随机POST_ID。
global $wpdb;
// SQL statement to fetch the post_id using a meta_key and a published post
$sql = <<<SQL
SELECT post_id
FROM {$wpdb->postmeta} pm
JOIN {$wpdb->posts} p
ON p.ID = pm.post_id
AND post_status = 'publish'
AND post_type = 'post'
WHERE meta_key = 'pictureID'
AND meta_value != ''
AND post_id != %d
ORDER BY RAND()
LIMIT 1
SQL;
// exclude the current post by replacing %d with the current ID
$sql = $wpdb->prepare($sql, $post->ID);
// use get_var() to return the post_id
$post_id = $wpdb->get_var($sql);