• Resolved bmtm

    (@bmtm)


    Hi, I’m trying to create a recipe list for a food blog. I’ve written a query that returns the titles of posts within a category, or if the post has a custom field called “recipe_name” then it shows the value of that instead–this is because most posts take their name from their recipe, but not all. That much works (code below). The problem is that the list comes out sorted by post title only; posts appearing as the custom value are out of order. Any idea how to sort these by whichever value is being returned? Thanks for any help!

    Example of code so far:

    <ul>
      <h3>Dessert</h3>
      <?php query_posts('category_name=Dessert&showposts=-1&orderby=title&order=ASC');?>
      <?php while (have_posts()) : the_post(); ?>
        <li><a  href="<?php the_permalink() ?>">
          <?php $posts_recipe_name = get_post_meta($post->ID, 'recipe_name', true);?>
          <?php if(!$posts_recipe_name): ?>
            <?php the_title(); ?>
          <?php else: ?>
        <?php echo get_post_meta($post->ID, 'recipe_name', true);?>
      <?php endif;?>
      </a></li>
      <?php endwhile;?>
    </ul>

Viewing 13 replies - 1 through 13 (of 13 total)
  • What do you want to do with posts that don’t have the Custom Field “recipe_name”?

    The query is being returned sorted by title, so whether you wrap a condition round your get_post_meta calls or not will not help resort the order…

    The only way i can see to correctly sort by title, after you’ve checked the meta values would be to store the data from each post on the first loop of the posts into an array…

    When the loop is finished and the data stored, you then resort that array based on a value, this could be the array key for example (which could take it’s value from title/meta appropriately). You’d then do a secondary loop which then just runs through the new array re-sorted with appropriate titles etc…

    Simply put, store the posts in a new array, resort the array, loop over new array…

    I can provide an example if you like….

    Thread Starter bmtm

    (@bmtm)

    MichaelH: I’d like to include those posts, but each of those is listed by its post title not the “recipe_name” value.

    ts31os_: I had a feeling that might be the only solution. I haven’t worked with arrays before (my PHP knowledge has all been gleaned from WP tinkering), so I would REALLY appreciate an example. I’m fairly proud of the code I came up with but I’m happy to scrap the whole thing for an easier approach.

    Thank you both!

    So where would you sort the posts that don’t have that Custom Field? At the front of the list or the end of the list?

    I’m not sure that matters, both title and meta_value will act as title, but that’s not taken into account in the query..

    Imagine the following theoretical posts..

    Title | Meta (none if not exist)

    Apples – none
    Banannas – Yellow
    Cranberries – none

    Initially Banannas is in the second position, once we take the meta value into account, it’s position should actually be third…

    Apples
    Cranberries
    Yellow

    and not…

    Apples
    Yellow
    Cranberries

    —–

    I think that’s the jist of it, if my understanding is correct… :-s

    Thread Starter bmtm

    (@bmtm)

    Your understanding is exactly right, t31os. I’d like posts with or without the custom value to be mixed together, sorted by whichever value is being returned (title for most, “recipe_name” for the rest). Following t31os’s model:

    Apple pie (no meta-tag)
    The best muffin I ever ate (recipe_name = Blueberry muffin)
    Coffee cake (no meta-tag)

    is showing up as

    Apple Pie
    Coffee cake
    Blueberry muffin

    but I’d like it to be

    Apple Pie
    Blueberry muffin
    Coffee cake

    Thanks again for your help with this!

    This totally untested, so please report back any errors..
    https://wordpress.pastebin.ca/1786491

    Thread Starter bmtm

    (@bmtm)

    It works! t31os, you are a genius. And a generous one at that! I can’t believe you even tagged each line for me. I can’t thank you enough!

    You’re welcome.. ?? Admittedly i expected at least 1 error to fix.. , happy to hear it works… ??

    You can use the regular loop stuff in that second loop, so if you decide you want the_content(); etc… you can just add that in…

    Getting errors at wordpress.pastebin.ca so got t31os_’s code from cache. Hope you don’t mind me posting it here:

    <?php
    query_posts( array(
    	'category_name' => 'Dessert',
    	'posts_per_page' => -1,
    	'orderby' => 'title',
    	'order' => 'asc'
    ) );
    // Empty array to fill with post data
    $temp_posts = array();
    // If the query has posts, no harm in checking
    if( have_posts() ) :
    	while( have_posts() ) : the_post();
    		// Check for recipe name
    		$posts_recipe_name = get_post_meta( $post->ID , 'recipe_name' , true );
    		switch( true ) {
    			// There's a meta field and it's not an empty string
    			case( $posts_recipe_name && $posts_recipe_name != ''):
    				$temp_posts[$posts_recipe_name] = $post;
    			break;
    			// No field, or something else that's not wanted, so fallback to regular title
    			case( !$posts_recipe_name ):
    			default:
    				$temp_posts[apply_filters('the_title',$post->post_title)] = $post;
    			break;
    		}
    	endwhile;
    endif;	
    
    if( !empty( $temp_posts ) ) :
    	ksort( $temp_posts );
    	?>
    
    	<h3>Dessert</h3>
    	<ul>
    
    	<?php foreach( $temp_posts as $key => $post ) : setup_postdata( $post ); ?>
    
    		<li>
    			<a href="<?php the_permalink() ?>"><?php echo $key // the key name is the title ?></a>
    		</li>
    
    	<?php endforeach; ?>
    
    	</ul>
    
    	<?php
    endif;
    
    unset( $temp_posts , $posts_recipe_name );
    ?>

    [edit fixed]

    Thread Starter bmtm

    (@bmtm)

    I had to close the final php tag, but after that it worked great for me.

    It’s only code, post away mate… ??

    NICE!!!!!
    Just what I need, works perfect!

Viewing 13 replies - 1 through 13 (of 13 total)
  • The topic ‘Sorting query results by value of custom key’ is closed to new replies.