Correct PHP Syntax for custom WP loop

2019-03-02 14:55发布

问题:

I am trying to insert a sorting option into my wordpress site. I already have it working, but need help using it with the wordpress loop correctly. Currently, I have:

On a page, there are options to sort alphabetically or chronologically:

<a href="?sort=date">Newest</a>
<a href="?sort=title">Alphabetical</a>

Sorting Code starts here, placed above the loop:

<?php $sort= $_GET['sort']; 
    if($sort == "title") { $order= "'orderby'=>'title','order'=>ASC'"; } 
    elseif($sort == "date") { $order= "'orderby'=>'date'"; } 
    else{ $order= "'orderby'=>'date','order'=>'DESC'"; } 
?>

note: I am pretty sure the problem lies above in the variable $order

Wordpress Loop Using Variable $order as an argument

<?php $loop = new WP_Query( array( $order, 'post_type' => 'films', 'post_parent' => 0, 'posts_per_page' => -1 ) ); ?>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

    Wordpress loop stuff here

<?php endwhile; ?>

The loop displays items correctly, but the sorting links are not working. This code works very well with query_posts but I am trying to get this to work for WP_Query (above). Any ideas here?

UPDATE: This technique works great using query_posts like below (but I still need it working for WP_Query):

<?php $sort= $_GET['sort']; 
    if($sort == "title") { $order= "&orderby=title&order=ASC"; } 
    elseif($sort == "date") { $order= "&orderby=date"; } 
    else{ $order= "&orderby=date&order=DESC"; } 
?>

<?php $posts = query_posts($query_string . $order); ?>
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
       Wordpress Stuff Here
<?php endwhile; ?>
<?php endif; ?>

回答1:

WP_Query expects associative array of parameters (array('param' => 'value')), whereas query_posts accepts only "query strings" ("param=value&param=value"). You are mixing both options, that's why it doesn't work. You need to change $order variable to be array instead of string, for example: $order = array('orderby' => 'title', 'order' => ASC');.

Answer above is not complete and may be misleading. WP_Query docs are here: https://codex.wordpress.org/Class_Reference/WP_Query . This class accepts boths styles, but they must be somewhat different formed. I don't know how exactly to do this, because it is not written in class docs, but you better use arrays, so:

if($sort == "title") { $order = array('orderby' => 'title', 'order' => 'ASC'); } 
elseif($sort == "date") { $order= array('orderby' => 'date'); } 
else{ $order= array('orderby' => 'date', 'order' => 'DESC'); } 

FYI to convert between both types use functions parse_str(): http://php.net/manual/en/function.parse-str.php and http_build_query(): http://www.php.net/manual/en/function.http-build-query.php .