How to see if a post exists based on a meta value

Is there any way to see if a post exists by a meta value?

For instance, lets say I want to see if another post has a unique meta value of “pictureID”, and if so do something else.

Read More

Is there a way I could write that clause in php?

Thank you

Related posts

Leave a Reply

3 comments

  1. if you dont know the post id then

    you can use custom wordpress query to check post meta according to key like

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

    And then you can get all results with post id and then get that post data.

    Hope this helps 😉

  2. You can use a standard WP_Query to return posts by meta_key using the meta_query argument and EXISTS compare type.

    // 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();
    

    If you want to quickly grab a random post_id that has this meta_key set you can go to the database directly (bypassing caching, etc).

    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 );