• I have a custom post type of “products”. In the archive template I want to sort the posts by a meta_key. The problem I am having is that when I try and sort by this meta_key it only returns post that have that meta_key. How would I sort posts by a meta_key first, followed by any posts that don’t have this meta_key? Here is the code I have so far.

    /**
     * Show more posts for products post type and sort by ranging meta value.
     */
    function products_per_page( $query ) {
    	if( !is_admin() && $query->is_main_query() && is_post_type_archive( 'products' ) ) {
    		$query->set( 'meta_key', 'product_rank' );
    		$query->set( 'orderby', 'meta_value_num' );
    		$query->set( 'order', 'ASC' );
    	}
    }
    add_action( 'pre_get_posts', 'products_per_page' );
  • The topic ‘Order by meta_key, but not limited that meta_key’ is closed to new replies.