WordPress.org

Forums

[resolved] Custom Queries (5 posts)

  1. toneburst
    Member
    Posted 5 years ago #

    I'd like to select all post in a particular category (in this case called 'events'), that have a particular custom field value (say, event_type = 'theatre'). I'm guessing I need a custom query, but my mySQL knowledge isn't up to much, sadly....

    I've had a look at
    http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query
    and
    http://codex.wordpress.org/Function_Reference/wpdb_Class
    but still can't work out the syntax for what I want to do.

    Any tips?

    a|x

  2. MichaelH
    Member
    Posted 5 years ago #

    <?php
    $cat_id = get_cat_ID('events');
    $args=array(
      'cat' => $cat_id,
      'meta_value'=> 'theater',
      'meta_key'=>'type_or_whatever_your_key_is_here',
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo 'List of Posts';
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>

    Related:
    Stepping Into Template Tags
    Stepping Into Templates
    Template Hierarchy

  3. toneburst
    Member
    Posted 5 years ago #

    Great, thanks for that MichaelH!

    That method is quite different from the method I ended up using (which was straight from the wpdb Class function ref. page linked above)

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

    Your method looks nicer though. Are there particular reasons for using one or the other of these two different methods?

    a|x

  4. MichaelH
    Member
    Posted 5 years ago #

    While the wpdb class is nice, and necessary at times, using query_posts decreases the chances future database changes will affect your customizations.

  5. toneburst
    Member
    Posted 5 years ago #

    Ah, OK. Thanks for that.
    I'll give it a go.

    a|x

Topic Closed

This topic has been closed to new replies.

About this Topic