0

I would like to query information in my sidebar text widget. I added the function. The php query working. (see the code below)

I have single posts with wine tastings. I would like to show in right sidebar which cellar producted it. I added the same custom field key cellar_slug and value somloi-apatsagi-cellar each post. Code below can show the cellar.

But how can I using on all posts? Every post have different meta value. Is there any solution using current post meta value instead of a fix value?

    <?php 

$cellars = new WP_Query(array(
     'post_type' => 'post', 
     'numberposts' => -1, 
    'posts_per_page' => '1',
 'meta_query' => array(
          array(
           'key' => 'cellar_slug',
           'value' => 'somloi-apatsagi-cellar',
          )),
     'orderby' => 'menu_order', 
     'order' => 'ASC'
));


if ($cellars->have_posts()) : ?>

<u1>
     <?php 
     while ($cellars->have_posts()) : 
     $cellars->the_post(); ?>
          <li><h3><a href="<?php the_permalink(); ?>">
               <?php the_title(); ?></a></h3><?php the_post_thumbnail('widget-text-post-thumbnail'); ?><?php the_excerpt(); ?>
        </li>  
     <?php endwhile; ?>
</u1>
<?php endif; ?>
0

Your question is a bit hard to read, but if I understand you on a single post page this should work:

$obj = get_queried_object();

if ('WP_Post' === get_class($obj)) {
  $cellar = get_post_meta($obj->ID,'cellar_slug',true);
  if (!empty($cellar)) {
    $cellars = new WP_Query(
      array(
        'post_type' => 'post', 
        'numberposts' => -1, 
        'posts_per_page' => '1',
        'meta_query' => array(
        array(
          'key' => 'cellar_slug',
          'value' => $cellar,
        )
      ),
      'orderby' => 'menu_order', 
      'order' => 'ASC'
      )
    );
  }
}

You are:

  1. Using get_queried_object() to grab the main post data
  2. Using get_post_meta() to retrieve the cellar associated with the post
  3. And running the query only if you have a cellar
| improve this answer | |
  • I tried find a way, but dont know why not works: $id = get_post_custom_values('cellar_slug'); $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1, 'cat' => '25', 'meta_query' => array( array( 'value' => $id, 'compare' => '=' ) ) ); – jagger Feb 22 '14 at 19:01
  • What you did is, in significant ways, not like the code I posted. You don't specify a key, for one, you don't pass an ID to get_post_custom_values(), and if you need an array you need the IN comparison not the = one. Try to follow my code more closely. – s_ha_dum Feb 22 '14 at 19:13
  • I'm using your code. I appreciate your help. Regards. – jagger Feb 22 '14 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.