Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.
<?php 
    query_posts(
        array(
            'showposts'   => -1, 
            'post_parent' => $post->ID, 
            'post_type'   => 'page', 
            'orderby'     => 'title',
            'order'       => 'ASC', 
            'meta_key'    => 'featured_product', 
            'meta_value'  => 1
        )
    );
?>

For featured products.

<?php 
    query_posts(
        array(
            'showposts'    => -1, 
            'post_parent'  => $post->ID, 
            'post_type'    => 'page', 
            'orderby'      => 'title', 
            'order'        => 'ASC', 
            'meta_key'     => 'featured_product', 
            'meta_compare' => '!=', 
            'meta_value'   => 1
        )
    );
?>

For normal product.

What I want is:

  • If the child page has 'featured_product' and value equals "1" then it's featured. It works!
  • If the child page has 'featured_product' and value not equal "1" OR it doesn't even have the field 'featured_product' then it's not featured product (this doesn't work at the moment).

Anyone? Thanks!

share|improve this question

1 Answer 1

up vote 3 down vote accepted

The best solution i found for querying posts where the meta_key IS NOT or doesn't exists is to use the posts_where filter with a small sub-query, try this:

//paste this function in your theme's functions.php

function metakey_no_featured( $where )
{
    global $wp_query;
    global $wpdb;
    $where .= $wpdb->prepare(" AND $wpdb->posts.ID NOT IN ( SELECT post_id FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = %s AND meta_value = 1) ",'featured_product');

    return $where;
}


//and when you query none featured products use
add_filter('posts_where', 'metakey_no_featured' );
query_posts(
        array(
            'showposts'    => -1, 
            'post_parent'  => $post->ID, 
            'post_type'    => 'page', 
            'orderby'      => 'title', 
            'order'        => 'ASC', 
        )
    );
remove_filter('posts_where', 'metakey_no_featured' );
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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