WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have these requirements:

  • If the child page has featured_product and the value equals to 1 then it's featured. This works.

  • If the child page has featured_product and the value does not equal to 1, or if it doesn't even have the field featured_product then it's not featured product. This doesn't work at the moment.

For featured products (it works):

<?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 normal product (it doesn't work):

<?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
        )
    );
?>
share|improve this question
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.