1

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...

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Wow that's actually worked! only problem is its pulling the results through more than once, as though its looping for some...
you can add GROUP BY post_id and see the result, did you mean something like that...
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.