2014-10-30 64 views
2

有沒有方法通過元值查看帖子是否存在?如何根據元值查看帖子是否存在

例如,假設我想查看另一個帖子是否具有唯一的「pictureID」元值,如果有,請執行其他操作。

有沒有一種方法可以在PHP中編寫該子句?

謝謝

回答

4

如果你不知道的帖子ID,然後

可以使用自定義的WordPress查詢根據檢查後的元鍵像

global $wpdb; 
$wpdb->get_results("select * from $wpdb->postmeta where meta_key = 'pictureID' "); 

然後你可以得到al l以帖子ID結果,然後獲取該帖子數據。

希望這有助於;)

1

第一次嘗試獲取meta值的崗位get_post_meta()

$postMetaValue=get_post_meta($postId,"meta_key",true); 
if($postMetaValue=='pictureID') 
    { 
    //do as you want 
    } 
2

您可以通過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); 
相關問題