简体   繁体   中英

404 error when passing certain filter with WP_Query, but not others

I have a page where I am using new WP_Query to display posts from a certain category, where the user can filter posts by year they were published. Here's my code for the query:

if (isset($_GET['action'])){
    $orderby = $_GET['orderby'];
    $order = $_GET['order'];
    $year = $_GET['year'];
}
$args = array(
    'category_name' => 'films',
    'orderby' => $orderby,
    'order' => $order,
    'year' => $year
);
$my_query = new WP_Query( $args );

I have a form where users can choose to filter posts by year:

<form class='post-filters'>
    <select name="orderby">
        <option value='date'>Order By Date</option>
        <option value='title'>Order By Title</option>
    </select>
    <select name="order">
        <option value='DESC'>Descending</option>
        <option value='ASC'>Ascending</option>
    </select>
    <select name="year">
        <option value=''>All</option>
        <option value='2016'>2016</option>
        <option value='2015'>2015</option>
    </select>
    <input type='submit' value='Filter!'>
</form>

Everything works fine, except when I try to select 2016 as a filter, where I get a 404 error. There are posts for that year, and if I hard-code the value 2016 in the WP_Query, it works.

Any ideas what could be going wrong?

Some variable names are "reserved" in WordPress. $year is one that will not work - same with $month , $day , etc. Change your select name to something like year_filter and then:

if (isset($_GET['action'])){
  $orderby = $_GET['orderby'];
  $order = $_GET['order'];
  $year_filter = $_GET['year_filter'];
}
$args = array(
  'category_name' => 'films',
  'orderby' => $orderby,
  'order' => $order,
  'year' => $year_filter
);
$my_query = new WP_Query( $args );

I pounded my head against the desk many a times until I figured this out a while back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM