0

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
        )
    );
?>
3

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' );

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.