Question

I need to find if a post with a custom field X equal to Y exists in a wordpress installation.

Should I do it with a simple sql query or is there something build in that can help me achieve it?

Was it helpful?

Solution

You can use the WP_Query(); to check that like this:

$my_query = new WP_Query();
$my_query->query(array( 'meta_key' => 'X', 'meta_value' => 'Y'));
if ( $my_query->have_posts() ){

     //it exists

} else {
    //it's not here
}

Hope this helps.

OTHER TIPS

The current way would be something like this:

$posts = get_posts(array(
    'meta_key' => 'color',
    'meta_value' => 'blue',
));

if( !empty($posts) ) { // some posts found }

Just note that in upcoming 3.1 querying for custom fields is considerably improved and arguments change, see Custom Field Parameters in Codex.

If you want to use this externally(per your comments), to keep the operation cheap you could do something like this.

<?php
// You'll need to make sure the path is correct here
include_once 'wp-config.php';
include_once 'wp-includes/wp-db.php';

// Of course update the following line with a more appropriate query
$result = $wpdb->get_results("SELECT * FROM $wpdb->posts"); 

print '<pre>';
print_r( $result ); // Remove and do whatever you need to do
print '</pre>';
?>

Loading wp-config.php and wp-db.php should be enough to call upon the $wpdb methods to query the DB for whatever data you need.

Let me know if you need an example SQL query to fetch posts based on meta.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top