Skip to content

How to dynamically insert an orderby statement in a query array

An answer to this question on Stack Overflow.

Question

I'm trying to dynamically assign the sort order (stored in $current_sort below) for a query that lists menu items.

If I hard code the sort order it works fine, however, when I try to dynamically assign the sort parameters to a string, it fails. What am I missing?

$current_sort = ", 'orderby' => 'title', 'order' => 'asc'";
$myposts = get_posts(
	array(
		'cat' => "$cat,-$catHidden",
		'numberposts' => $my_current_count . $current_sort
		));
//If I hard code the value of $current_sort it works fine
$myposts = get_posts(
	array(
		'cat' => "$cat,-$catHidden",
		'numberposts' => $my_current_count,
		'orderby' => 'title',
		'order' => 'asc'));

Answer

The string concatenation on the line

'numberposts' => $my_current_count . $current_sort

is not equivalent to creating multiple array elements as in

'numberposts' => $my_current_count,
'orderby' => 'title',
'order' => 'asc'));

In the first instance, numberposts becomes a string containing information about the sort. In the second instance, numberposts only contains the current count.

A better option may be:

$orderoption="<TITLE HERE>";
$order_dir="<SORT OPTION HERE>";
$myposts = get_posts(
array(
    'cat' => "$cat,-$catHidden",
    'numberposts' => $my_current_count,
    'orderby' => $orderoption,
    'order' => $order_dir));