Support » How-To and Troubleshooting » List pages & order by custom field value

List pages & order by custom field value

  • I have a request that I’ve seen multiple times but I didn’t really seem to get the answer I was looking for. A lot of it may be because I’m new with php and its difficult to grasp. BUT… I am trying to understand better which is why I’m asking this question myself and hoping for a somewhat simple solution. I hope that, if I can find a solution to change the code that I currently have, that I will better understand why and how the change in code works.

    I have a page template that I created that shows a list of child and grandchild pages based on the code I found in the support forums.

    I added my code to coincide with my CSS to display the way I want it to:

    $postid = $post->ID;
    $args = array(
    'post_type' => 'page',
    'post_status' => 'publish',
    'orderby' => 'rand',
    'posts_per_page' => -1,
    'post_parent' => $postid
    $child_level = get_posts($args);
    if($child_level) :
    foreach($child_level as $child_page) :
    $args = array(
    'post_type' => 'page',
    'post_status' => 'publish',
    'orderby' => 'rand',
    'posts_per_page' => -1,
    'post_parent' => $child_page->ID
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <div id="individual-product-wrapper">
    <div id="product-title">
    <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
    <div id="product-thumb">
    $img = get_post_meta($post->ID, 'image_url', true);
    if ($img == '')
    { ?>
    <a href="<?php the_permalink() ?>"><img src="No-Image-Available.gif" width="200px" height="200px" style="border:1px solid black;"></a>
    <?php } else { ?>
    <a href="<?php the_permalink() ?>"><img src="<?php echo get_post_meta($post->ID, 'image_url', true); ?>" width="200px" height="200px" style="border:1px solid black;"></a>
    <?php } ?>
    <div id="product-status">
    Status: <?php echo get_post_meta($post->ID, 'product_status', true); ?>
    <?php endwhile;

    Now I completely understand that 'orderby' => 'rand', means that it will display the list in random order. I would like to know if there is a simple solution for me to order by a custom field. The last snipet of code displays the custom field “product_status” I would like to add a number value like “status_number” and have it display that in descending order.

    I guess something like this:

    'orderby' => 'status_number',
    'order' => 'desc',

    What do I need to do to have 'orderby' recognize my custom field 'status_number'then say, take all status_number equaling 3 and display them first, then 2 then 1?

  • The topic ‘List pages & order by custom field value’ is closed to new replies.