Support » Themes and Templates » Custom query, select category

  • Resolved martin.aleksander



    I have the following code, which will print out articles that are posted in a special category called “Produkttest”. (I am using Magic Fields).

    Now, I also want to include regular categories in this query, but is currently a little unsure how.

    	$querystr = "
    		SELECT wposts.*
    		FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    		WHERE wposts.ID = wpostmeta.post_id
    		AND wpostmeta.meta_key = 'article_type'
    		AND wpostmeta.meta_value = 'Produkttest'
    		AND wposts.post_status = 'publish'
    		AND wposts.post_type = 'post'
    		ORDER BY post_date DESC
    	$pageposts = $wpdb->get_results($querystr, OBJECT); 
    	if ($pageposts):
    		foreach ($pageposts as $post):
    			setup_postdata($post); ?>
    			<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    		<?php  endforeach;

    In the default WP-query I would have used this;
    <?php query_posts(‘category_name=wordpress’); ?>

    So, how can I do this inside my custom query?

Viewing 2 replies - 1 through 2 (of 2 total)
  • You don’t need a custom query

    $cat_id = get_cat_ID('wordpress');  //category id is 7 on my system
      'category__in' => array($cat_id),
      'meta_value'=> 'Produkttest',
      '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>
    wp_reset_query();  // Restore global post data stomped by the_post().

    Here’s the SQL that WordPress used for that:

    SELECT   wp_posts.* FROM wp_posts
    INNER JOIN wp_term_relationships
    ON (wp_posts.ID = wp_term_relationships.object_id)
    INNER JOIN wp_term_taxonomy
    ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
    JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
    WHERE 1=1  AND wp_term_taxonomy.taxonomy = 'category'
    AND wp_term_taxonomy.term_id IN ('7')
    AND wp_posts.post_type = 'post'
    AND (wp_posts.post_status = 'publish')
    AND wp_postmeta.meta_key = 'article_type'
    AND wp_postmeta.meta_value = 'Produkttest'
    GROUP BY wp_posts.ID
    ORDER BY wp_posts.post_date DESC

    Worked like a charm!

    Thank you very much, Michael!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Custom query, select category’ is closed to new replies.