• Hello! I want to sort search results by the value of custom field (‘name-official’) for all posts (is this field filled or not).
    But when I add filter in function.php like

    function searchExcludePages($query) {
    	if ($query->is_search) {
    		$query->set('orderby','meta_value');
    		$query->set('meta_key','name-official');
    		$query->set('order','ASC');
    	}
    	return $query;
    }
    add_filter('pre_get_posts','searchExcludePages');

    i’ve received results with filled ‘name-official’ only. What should i do to get results with non-filled field too?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hello @varro,

    Try to add the compare key as per WP_Query and Custom Field Parameters instructions.

    The EXISTS value can solve your issue.

    $query->set('compare', 'EXISTS');

    compare is not a parameter. If you used meta_compare, which is a parameter along with ‘EXISTS’, you would get what you already have. That would basically be the default that you are already dealing with. So that will NOT solve the issue. It won’t change anything. at all.

    Unfortunately. It looks like there are three possible solutions to this, but they are not just a simple setting to your base query.

    1. Make sure every post has that meta_key with at least an empty value.
    2. Multiple queries, one where you get the posts in which the meta_value is 'something', and one where the meta_value is NOT 'something'.
    3. Use a custom Left Join and Order By query. Something like this. Though I have not tried this specific solution, I have done something like it a while back.

    Link: http://wordpress.stackexchange.com/a/141367/11966

    • This reply was modified 8 years ago by Jupitercow. Reason: code marks
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Order queries by meta_value even if meta_key is not filled’ is closed to new replies.