WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. realshot
    Member
    Posted 1 year 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">
    <?php
    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; ?>
    </ul>

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

    Any help would be very much appreciated!

  2. vtxyzzy
    Member
    Posted 1 year ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic