WordPress.org

Ready to get started?Download WordPress

Forums

WP_Query, meta keys, and posts that do not have a certain meta key (3 posts)

  1. daletaylor
    Member
    Posted 3 years ago #

    Hello,

    I have a 'News' category and I would like to be able to make certain posts in that category 'Featured' or 'Sticky'.

    To make a post 'Featured', I add a Custom Field 'Featured News' with the value 'true'. For normal posts, there is no Custom Field.

    I could not get WP_query to sort the posts properly so what I tried was doing two separate queries, the first to get featured posts and the second to get non featured posts. However, it seems that if the Custom Field is not present at all, the post gets ignored. Here is my code:

    $newsQuery = array(	'category_name' => 'news',
    					'meta_query' => array( 'key' => 'Featured News', 'compare' => '!=', 'value' => 'true' ),
    					'posts_per_page' => 4,
    					'orderby' => 'date',
    					'order' => 'desc' );

    It would seem that in order for this to work I would have to give non-featured posts the Custom Field 'Featured News' with a value 'false'. I was hoping that if the field is not present, a value of 'false' would be assumed. Is there any way to make it work that way?

    Thanks!

  2. esmi
    Forum Moderator
    Posted 3 years ago #

    I think this might be more of a human logic issue rather than a coding one. As far as I can tell, there's no way to use WP_query to pull posts that don't have a specific custom field (meta_key). So your second query will need to pull in all posts and then you'll have to check the each result before you display it it to see if it was in the first query. Perhaps by creating an array of post ids during the first query's Loop and then using a simple in_array() check?

  3. daletaylor
    Member
    Posted 3 years ago #

    Hi,

    Thanks for your response. I will try doing something like that.

Topic Closed

This topic has been closed to new replies.

About this Topic