PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » WordPress » Custom Loop/Query Based on Custom Fields

Custom Loop/Query Based on Custom Fields

This snippet enables you to make a custom loop that is purely based on custom-fields. Not dependent on any category or tag. This is not (yet) possible with query_posts() or WP_Query(), so we here utilize a direct $wbdb-call:

<?php

 $querydetails = "
   SELECT wposts.*
   FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
   WHERE wposts.ID = wpostmeta.post_id
   AND wpostmeta.meta_key = 'readmoretext'
   AND wpostmeta.meta_value = 'Go check this out'
   AND wposts.post_status = 'publish'
   AND wposts.post_type = 'post'
   ORDER BY wposts.post_date DESC
 ";

 $pageposts = $wpdb->get_results($querydetails, OBJECT)

 ?>

First we select any WordPress Posts that contain "meta data" (custom fields). We then add a few conditions. For example, the key should be "readmoretext", another condition is that the value of the custom field needs to be "Go check this out". Also, it needs to be published post, it needs to be an actual Post (not a Page), and in lastly in descending order.

You can remove, add or duplicate/change any of these AND conditions to get exactly the thing you need. (for example, all Posts that have a custom field called "mood", then get rid of the *. meta_value-line and then you'll get all the posts that have a "mood" set regardless of it's value.

After you've run the query, you can run a loop to output the results:

<?php if ($pageposts):
 foreach ($pageposts as $post):
       setup_postdata($post); ?>

               // Make your loop here. For example :
               <div <?php post_class(); ?>> id="post-<?php the_ID(); ?>">
               <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
               <?php the_content(); ?>
               </div>

 <?php endforeach;
endif; ?>

Subscribe to The Thread

  1. Bjarne says:

    This is great! What if you want to limit the loop to 5 posts/pages?

  2. Bjarne says:

    Okay, that was easy. Just added LIMIT 4 to the query details…

  3. hmm..is it support wordpress 2.9???

  4. wpfan says:

    Great stuff, using it in several places in one of my wp templates.

    In addition to this, is there a way to query mulitiple custom fields and print the “merged” results?

  5. Isn’t this the same result you’d obtain using wp_query?

    Something like this:
    http://wordpress.pastebin.com/uJDdsiCw

    I used this reference:
    http://codex.wordpress.org/Template_Tags/query_posts#Custom_Field_Parameters

    but haven’t tried it yet.

    • It actually can. I just used it that way.
      I couldnt implement the code in the article whether for noobness or didnt understand where to put it.

      I got your code and integrated it with a simpler query;
      $loop = new WP_Query( $args );
      if($loop->have_posts()): while ( $loop->have_posts() ) : $loop->the_post();

  6. nomadone says:

    I’ve been trying to figure out, how to show posts from a specific category, if the page template being viewed has a custom field value with the same name.

    ie. a custom field value is present, and posts in a category with the same name as that custom field value are shown.

  7. carol says:

    I am trying to use this to output child pages of a certain parent page that have a particular custom field. Problem is it spits out more than one of the same child page depending on how many values have been declared for the custom field. That is if the child page has two different costume field VALUES for “soundfile” it will output that childpage twice. How can I limit that. Here is the link to the page I am working on:

    http://www.oliviablock.net/listen/

    Thanks in advance

  8. carol says:

    OK, by some freakin miricle I was able to figure out the solution to the above comment. Instead of OBJECT I used OBJECT_K which results output as an associative array of row objects, using first column’s values as keys so that duplicates where discarded.

    Thanks,
    carol

  9. Toby says:

    Thanks for this Chris!!! You just saved my life with this one! :)

  10. Phillip says:

    Fantastic! This worked like a charm for me, thanks so much!

  11. danflo says:

    Very nice Chris. This gives me the control I was looking for for out putting post content on my home page. Cheers mate.

  12. Fannar says:

    I wanted to thank you for this super useful post. It basically saved my life. I have spent so much time trying to do something similar with the wordpress built in queries and not been able to.

    Thank you !

  13. PG says:

    Really good post Chris, I almost thought it would solve a problem I’m having, which I’ve looked everywhere for info on but couldn’t find a solution. I’m hoping someone here will have some idea of how to do this or if it’s even possible.

    Below is part of the code from this post, my custom field is called ‘views’ and by using the wp-postviews plugin, that custom field is given the number of how many people have viewed that post. Is there any way to get the last line, instead of ordering the posts by date, to order them by the custom field view number values, in descending order? I’ve all but given up on trying, so if anyone knows I’d be very grateful!

    $querydetails = ”
    SELECT wposts.*
    FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    WHERE wposts.ID = wpostmeta.post_id
    AND wpostmeta.meta_key = ‘views’
    AND wposts.post_status = ‘publish’
    AND wposts.post_type = ‘post’
    ORDER BY wposts.post_date DESC

  14. PG says:

    Just to update, someone else was kind enough to update the current code I had (not the one above) to order posts by view count. Just thought I’d share it below incase anybody is looking to do the same thing.

    $posts_per_page,
    ‘paged’ => $paged,
    ‘more’ => $more = 0,
    ‘meta_key’ => ‘views’,
    ‘orderby’ => ‘meta_value_num’,
    ‘order’ => ‘DESC’,
    ); ?>

    <div id=”post-”>

  15. Valentina says:

    This is a great post!
    With this script, based on custom fields, WordPress is more flexible.
    Thank you! You’ve saved my work. :)

  16. Chris says:

    I know this is a year old post, but I have been searching for a solution to my problem and I have yet to find a solution.

    Code wise, I am using exactly what you have posted. However, the query only retrieves one result.

    Any ideas what might cause this?

    Thanks in advance!

  17. kamal says:

    i am unable to change the loop query in the
    code

    how can i modify
    it by custom fields ..

    and query

    $paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
    $loop = new WP_Query();
    $loop->query( array( ‘post_type’ => ‘page’ , ‘meta_key’ => ‘portfolio_image’, ‘showposts’ => 5, ‘orderby’ => date, ‘order’ => ‘DESC’ ,’paged’=> $paged));

    please any one help me ….

  18. kamal says:

    Actually i have ti implement the where and like conditions in the query.

    for the searching by a particular values

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~