Support

Account

Home Forums Front-end Issues Need help with WP_Query orderby custom field

Solved

Need help with WP_Query orderby custom field

    • dalbeck

    • January 15, 2014 at 5:55 am

    Hello,

    First let me apologize because I know this has been asked a million times but I have been wracking my brain around this for countless hours now and can’t get it. I have tried the examples in the documentation as well as answers provided here in the forum. So I have a portfolio page that queries the attachments post type filters them by taxonmy, with a specific term applied to them. I created a custom field the help with sorting the images on the portfolio in a finer method then date, title etc. The field is just a text field nothing fancy.

    Here is my query:

    <?php
    	$sort = the_field('vehicle_sort_order');
    	$args = new WP_Query(array(
    		'post_type' => 'attachment',
    		'posts_per_page' => -1,
    		'post_status' => 'any',
    		'post_parent' => null,
    		//'meta_query' => array(
    		//	array(
    		//		'key' => 'vehicle_sort_order',
    		//		'compare' => 'IN',
    		//		'value' => $sort,
    		//		'type' => 'CHAR'
    		//	)
    		//),
    		'tax_query' => array(
    			array(
    				'taxonomy' => 'post_tag',
    				'field' => 'slug',
    				'terms' => 'vehicle'
    			)
    		),
    		'oderby' => 'meta_value',
    		'order' => 'DESC'
    	));
    
    	while ( $args->have_posts() ) : $args->the_post();
    
    ?>

    If I uncomment the lines that are commented nothing displays. Any help would be greatly appreciated, I feel like I am missing something very simple.

    • dalbeck

    • January 15, 2014 at 7:40 am

    I ended up changing my query to get_posts

    <?php
    	// get posts
    	$posts = get_posts(array(
    		'post_type' => 'attachment',
    		'posts_per_page' => -1,
    		'post_status' => 'any',
    		'post_parent' => null,
    		'tax_query' => array(
    			array(
    				'taxonomy' => 'post_tag',
    				'field' => 'slug',
    				'terms' => 'vehicle'
    			)
    		),
    		'meta_key' => 'vehicle_sort_order',
    		'orderby' => 'meta_value date',
    		'order'	=> 'DESC'
    	));
    ?>

    This works, but still curious as to why the WP_Query I initially had wasn’t working.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.