Forums

How to pull meta field value using the default query (1 post)

  1. safin
    Member
    Posted 2 years ago #

    Hello,
    On my wordpress install i have a custom meta named "thumbnail" that i want to pull with each instance of the loop. The meta value contains the url to a thumbnail for each post that i want to show both at category pages and at home page.
    Now right now i use the default WP_query like this

    <?php $getposts = new WP_query(); $getposts->query('showposts=17&cat=56,92,93'); ?>
    		<?php global $wp_query; $wp_query->in_the_loop = true; ?>
    		<?php while ($getposts->have_posts()) : $getposts->the_post(); ?>

    And to get the meta, i have to use the get_post_meta function for each postid in the loop.
    $custom_field = get_post_meta($post->ID, 'thumbnail', true);
    Now this is extremely wasteful when showing a lot of posts on front page and category pages as its adding as may database queries.
    I use wordpress in a CMS like manner.

    Basically i want to know if there is a way to modify the base query to get the meta value for the key by default for each loop and not call the get_post_meta inside the loop for each post?

    I did this via a function but that is a core hack.

    $querystr ="
          SELECT $wpdb->posts.ID, $wpdb->posts.post_title,$wpdb->postmeta.meta_value as thumbnail  FROM $wpdb->posts
          LEFT JOIN $wpdb->postmeta ON (($wpdb->posts.ID = $wpdb->postmeta.post_id) AND ($wpdb->postmeta.meta_key = 'thumbnail'))
          LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
          LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
          WHERE $wpdb->term_taxonomy.term_id = $catlist
          AND $wpdb->term_taxonomy.taxonomy = 'category'
          AND $wpdb->posts.post_status = 'publish'
          ORDER BY  $wpdb->posts.post_date DESC
          LIMIT 0,3
      ";
    
     $myposts = $wpdb->get_results($querystr, OBJECT);

    I was wondering if there is a WP_query(); equivalent that doesn't get hands dirty so as to say? :=)

Topic Closed

This topic has been closed to new replies.

About this Topic