• How can you join posts by Meta Value?

    So far I have this:
    query_posts('category_name=CATNAME&meta_key=METANAME&orderby=meta_value');

Viewing 6 replies - 1 through 6 (of 6 total)
  • I don’t understand exactly what you are trying to achieve. Can you explain more and give examples?

    Thread Starter SpidermanPuddin

    (@spidermanpuddin)

    Sorry, I meant GROUP BY no JOIN. Here’s an example.

    These are all meta values I have for a group of posts:

    meta_value_name = name_A
    meta_value_name = name_A
    meta_value_name = name_B
    meta_value_name = name_B
    meta_value_name = name_B
    meta_value_name = name_C
    meta_value_name = name_C

    I want to be able to query it so it only shows the unique meta-values.

    It’d query this:

    • name_A
    • name_B
    • name_C

    Even though the meta_values may be unique, there may be different posts for each one. Do you just want to show the first post for each meta_value?

    Thread Starter SpidermanPuddin

    (@spidermanpuddin)

    Yes that would work too.

    You need to add a filter to the query to include the meta_value.

    The code below should be close to what you want.

    function mam_posts_fields ($fields) {
          global $mam_global_fields;
          // Make sure there is a leading comma
          if ($mam_global_fields) $fields .= (preg_match('/^(\s+)?,/',$mam_global_fields)) ? $mam_global_fields : ", $mam_global_fields";
          return $fields;
       }
    
    add_filter('posts_fields','mam_posts_fields');
    $mam_global_fields = 'meta_value';
    query_posts('category_name=CATNAME&meta_key=METANAME&orderby=meta_value');
    $mam_global_fields = '';  //Turn off filter
    if (have_posts()) {
       $seen = array();
       while (have_posts()) {
          if (in_array($post->meta_value,$seen)) continue;
          $seen[] = $post->meta_value;
          // Rest of code to display a post
       }
    } else {
       // Code for no posts found
    }
    Thread Starter SpidermanPuddin

    (@spidermanpuddin)

    Thank you, vtxyzzy, I’m going to try that. I’ll let you know how it works.

Viewing 6 replies - 1 through 6 (of 6 total)

The topic ‘How-to Join wordpress Query’ is closed to new replies.