Sorting posts by a custom field, if the custom filed exists (2 posts)

  1. realshot
    Posted 3 years ago #

    Hi, I wonder if someone can help with the code below on Sorting posts (that exists in a specific category) by a custom field, but only if the custom filed exists, otherwise just have the posts (within the specific category) display as usual.

    In addition, all posts should wrap in <li>

    Here's the code so far:

    <ul class="products">
    global $post;
    $page_category = 4;
    $args = array('category'=>$page_category,'meta_key'=>'sorter','orderby'=>'meta_value_num','order' =>'ASC');
    $page_content = get_posts( $args );
    foreach( $page_content as $post ) : setup_postdata($post); ?>
    	<li><?php the_title(); the_content(); ?></a></li>
    <?php endforeach; ?>

    The code above will not show posts if the custom filed 'sorter' doesn't exist.

    Any help would be very much appreciated!

  2. vtxyzzy
    Posted 3 years ago #

    You will need to use query filters to do this. Here is a pastebin with sample code that shows how:

Topic Closed

This topic has been closed to new replies.

About this Topic