Forums

[resolved] How to run a WP_Query on both wp_posts and wp_postmeta simultaneously? (8 posts)

  1. Johnny T
    Member
    Posted 4 months ago #

    Hi,

    Does anyone know how I can run a query that interrogates both the wp_posts table and the wp_postmeta table.

    Currently I have:

    $params = "post_status=publish,pending&numberposts=8&author=0";
    $query = new WP_Query;
    $results = $query->query($params);

    What I want to do is something like this:

    $params = "post_status=publish,pending&numberposts=8&author=0 AND WHERE wp_postmeta dataX is equal to Y";
    $query = new WP_Query;
    $results = $query->query($params);

    Anyone any ideas on this?

    Even a "it can't be done" would be better than me tearing my hair out!

    Many thanks for any help you can give me

    John ;-)

  2. t31os_
    Member
    Posted 4 months ago #

    The code here is relevant..
    http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

    Namingly this part...

    <?php
    	$querystr = "
    	SELECT wposts.*
    	FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    	WHERE wposts.ID = wpostmeta.post_id
    	AND wpostmeta.meta_key = 'tag'
    	AND wpostmeta.meta_value = 'email'
    	AND wposts.post_status = 'publish'
    	AND wposts.post_type = 'post'
    	AND wposts.post_date < NOW()
    	ORDER BY wposts.post_date DESC
    	";
    	$pageposts = $wpdb->get_results($querystr, OBJECT);
    ?>

    You can use that as a reference to create a joined query, just modify as required..

  3. MichaelH
    moderator
    Posted 4 months ago #

    Didn't test this but I believe this would also work:

    $params=array(
    'showposts'=>3,
    'post_type' => 'post',
    'post_status' => 'publish,pending',
    'meta_key'=>'dataX',
    'meta_value'=>'Y'
    );
    $query = new WP_Query;
    $results = $query->query($params);
  4. Otto42
    Moderator
    Posted 4 months ago #

    Yes, the built in query system can select based on meta values. Just provide it the meta_key and meta_value in the parameters and it should work.

  5. t31os_
    Member
    Posted 4 months ago #

    Cool.... :) ...

  6. Johnny T
    Member
    Posted 4 months ago #

    Brilliant stuff!

    Thanks a million for all your replies.

    They are very very very much appreciated!

    Nice one ;-)

  7. Johnny T
    Member
    Posted 4 months ago #

    MichaelH

    I've tested your method and it works an absolute treat so that will be what I'm using from now on.

    Thank you once again for your help.

    ;-)

  8. beytar
    Member
    Posted 3 months ago #

    Thanks a lot MichaelH, it's very useful.

Reply

You must log in to post.

About this Topic