Liam
Liam

Reputation: 9855

Query posts based on custom field in wordpress

Im trying to write a query that will find and display all of my posts that have the same custom field values as my input.

In wordpress I have the following...

enter image description here

My query is...

$pageposts = $wpdb->get_results("SELECT wposts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_value = 'petrol' OR wpostmeta.meta_value = 'local' ORDER BY wpostmeta.meta_value DESC", OBJECT); 

If I remove 'OR wpostmeta.meta_value = 'local' This works correctly and pulls the correct post with the custom field value as 'petrol'

Can anybody give me an idea on where im going wrong? At the moment its display all of my posts even those that are drafts and have been deleted and its also looping and displaying them numerous times...

Upvotes: 1

Views: 1735

Answers (2)

Liam
Liam

Reputation: 9855

Figured it out...

<?php
$customkey = 'Network'; // set to your custom key
$customvalue = 'Local'; // set to custom value

global $wpdb;
$my_posts = $wpdb->get_results("SELECT * FROM $wpdb->posts, $wpdb->postmeta WHERE ID = $wpdb->postmeta.post_id AND meta_key = '$customkey' AND meta_value = '$customvalue' ORDER BY post_date DESC");

foreach ($my_posts as $post) :
setup_postdata($post);

echo '<div><a href="';
the_permalink();
echo '"></div>';
the_title();

endforeach;
?>

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Try:


SELECT wposts.* 
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta 
WHERE wposts.ID = wpostmeta.post_id 
AND (wpostmeta.meta_value = 'petrol' OR wpostmeta.meta_value = 'local') 
ORDER BY wpostmeta.meta_value DESC"

Upvotes: 1

Related Questions