最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Date and Category query with filter

programmeradmin2浏览0评论

I am a little confused by this. I have a query that finds posts within a category and date.

I can filter the categories, but I have no idea how to filter by date.

The query works. I see all of the posts I have queried, but I don't know how to filter the date. It would help if I knew what was meant to appear in the url

The search for categories returns /blog/?category=promotions

What should a date filter result look like?

<?php $categorys = get_terms( 'category', array( 'hide_empty' => true, 'fields' => 'all' ) ); ?>
    <form class="staff-filter" method="GET" action=""><div class="col-sm-12 text-center">
    <span>Filter Posts by:</span>
      <ul class="list-inline">
       <li>
          <label>
            <select name="category">
              <option value="" disabled selected> Category </option>
                    <?php foreach( $categorys as $category ) : ?>
              <option value="<?php echo $category->slug; ?>">
                    <?php echo $category->name; ?>
              </option>
                    <?php endforeach; ?>
            </select>
          </label>
       </li>      

      <?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");

              $months = $wpdb->get_col("SELECT DISTINCT MONTHNAME(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");?>

            <li>
          <select name="date_start">
            <option value="" disabled selected> Date </option>
                    <?php foreach($months as $month) : ?>
            <option> <?php echo '<ul><li class"list-unstyled"><a href="'. site_url() .'/'.$year .'/'.date('m', strtotime($month)).'"/> ' . $month .'</a></li></ul>';?></option>
            <?php endforeach; ?>

            <?php foreach($years as $year) : ?>
            <option><?php echo '<ul><li class"list-unstyled"><a href="'. site_url() .''.$year.'"/> ' . $year .'</a></li></ul>';?></option>
            <?php endforeach; ?>   
           </select>
        </li>
      </ul>
  <!-- SUBMIT BUTTON -->      
  <button class="btn"><span class="glyphicon glyphicon-search" aria-hidden="true">      </span> Search</button>
  <!-- END SUBMIT BUTTON -->
 </div>
 </form>

 <?php

    $cat_query = array(array('relation' => 'AND'));

    if( isset( $_GET['category'] ) && $_GET['category'] ){

            $cat_area_query = array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => $_GET['category'],'operator' => 'IN', );
            $cat_query[] = $cat_area_query;
    }

    if( $cat_query && $cat_query ){
            $cat_query['relation'] = 'AND'
            ;
    }

    $args = array(
                    'post_type'      => array('post'),
                    'post_status'    => 'publish',
                    'tax_query'      => $cat_query,
                    'orderby'        => 'date',
                    'order'          => 'desc',
                    'date_query' => array(
                    'relation' => 'OR',
            array(
                    'year'  => $getdate['year'],
                    'month' => array(9, 8,7, 6, 5),
                    'compare'   => '=',
            ),
            ),
    );?>
    $posts_query = new WP_Query( $args );?>


 <?php if( $posts_query->have_posts() ) : ?>

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

<div class="ms-item col-lg-6 col-md-6 col-sm-6 col-xs-12">

    <?php if (has_post_thumbnail()) : ?>

        <figure class="article-preview-image">

            <a href="<?php the_permalink(); ?>" class="post-title-link"><?php the_post_thumbnail(); ?></a>

        </figure>

    <?php else : ?>

    <?php endif; ?>
     <a href="<?php the_permalink(); ?>">  
    <div class="post-content white">
    <?php $category = get_the_category(); ?>
            <span class="post-category"><?php echo $category[0]->cat_name;?></span>
        <span class="post-date"><i class="fa fa-clock-o"></i> <?php the_time('F j, Y') ?></span>
        <h2 class="post-title"><?php the_title(); ?></h2>

    <?php the_excerpt(); ?>
    </div>
    </a>

 <?php endwhile;?>

Link to pastebin

I am a little confused by this. I have a query that finds posts within a category and date.

I can filter the categories, but I have no idea how to filter by date.

The query works. I see all of the posts I have queried, but I don't know how to filter the date. It would help if I knew what was meant to appear in the url

The search for categories returns /blog/?category=promotions

What should a date filter result look like?

<?php $categorys = get_terms( 'category', array( 'hide_empty' => true, 'fields' => 'all' ) ); ?>
    <form class="staff-filter" method="GET" action=""><div class="col-sm-12 text-center">
    <span>Filter Posts by:</span>
      <ul class="list-inline">
       <li>
          <label>
            <select name="category">
              <option value="" disabled selected> Category </option>
                    <?php foreach( $categorys as $category ) : ?>
              <option value="<?php echo $category->slug; ?>">
                    <?php echo $category->name; ?>
              </option>
                    <?php endforeach; ?>
            </select>
          </label>
       </li>      

      <?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");

              $months = $wpdb->get_col("SELECT DISTINCT MONTHNAME(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");?>

            <li>
          <select name="date_start">
            <option value="" disabled selected> Date </option>
                    <?php foreach($months as $month) : ?>
            <option> <?php echo '<ul><li class"list-unstyled"><a href="'. site_url() .'/'.$year .'/'.date('m', strtotime($month)).'"/> ' . $month .'</a></li></ul>';?></option>
            <?php endforeach; ?>

            <?php foreach($years as $year) : ?>
            <option><?php echo '<ul><li class"list-unstyled"><a href="'. site_url() .''.$year.'"/> ' . $year .'</a></li></ul>';?></option>
            <?php endforeach; ?>   
           </select>
        </li>
      </ul>
  <!-- SUBMIT BUTTON -->      
  <button class="btn"><span class="glyphicon glyphicon-search" aria-hidden="true">      </span> Search</button>
  <!-- END SUBMIT BUTTON -->
 </div>
 </form>

 <?php

    $cat_query = array(array('relation' => 'AND'));

    if( isset( $_GET['category'] ) && $_GET['category'] ){

            $cat_area_query = array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => $_GET['category'],'operator' => 'IN', );
            $cat_query[] = $cat_area_query;
    }

    if( $cat_query && $cat_query ){
            $cat_query['relation'] = 'AND'
            ;
    }

    $args = array(
                    'post_type'      => array('post'),
                    'post_status'    => 'publish',
                    'tax_query'      => $cat_query,
                    'orderby'        => 'date',
                    'order'          => 'desc',
                    'date_query' => array(
                    'relation' => 'OR',
            array(
                    'year'  => $getdate['year'],
                    'month' => array(9, 8,7, 6, 5),
                    'compare'   => '=',
            ),
            ),
    );?>
    $posts_query = new WP_Query( $args );?>


 <?php if( $posts_query->have_posts() ) : ?>

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

<div class="ms-item col-lg-6 col-md-6 col-sm-6 col-xs-12">

    <?php if (has_post_thumbnail()) : ?>

        <figure class="article-preview-image">

            <a href="<?php the_permalink(); ?>" class="post-title-link"><?php the_post_thumbnail(); ?></a>

        </figure>

    <?php else : ?>

    <?php endif; ?>
     <a href="<?php the_permalink(); ?>">  
    <div class="post-content white">
    <?php $category = get_the_category(); ?>
            <span class="post-category"><?php echo $category[0]->cat_name;?></span>
        <span class="post-date"><i class="fa fa-clock-o"></i> <?php the_time('F j, Y') ?></span>
        <h2 class="post-title"><?php the_title(); ?></h2>

    <?php the_excerpt(); ?>
    </div>
    </a>

 <?php endwhile;?>

Link to pastebin

Share Improve this question edited Sep 18, 2015 at 13:22 MrFox asked Sep 18, 2015 at 13:05 MrFoxMrFox 3042 gold badges7 silver badges19 bronze badges 1
  • Please add your code in your question – Pieter Goosen Commented Sep 18, 2015 at 13:08
Add a comment  | 

2 Answers 2

Reset to default 1

I was going about this the wrong way around. I needed to allow the user to select the date first and then the category.

I also needed to make the dropdown boxes auto select, so that the date search is performed first taking the user to the date archive and then the user can select the category they require.

<form class="my-filter" method="GET" action=""><div class="col-sm-12 text-center">
        <span>Filter Posts by:</span>
      <ul class="list-inline">
     <?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");
      $months = $wpdb->get_col("SELECT DISTINCT MONTHNAME(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");?>
        <li>
          <select onChange="window.location.href=this.value">
                <option value="" disabled selected> Date </option>
                    <?php foreach($months as $month) : ?>
                <option value="<?php echo site_url() .'/'.date('Y') .'/'.date('m', strtotime($month))?>"> <?php echo '<ul><li class"list-unstyled">' . $month .'</li></ul>';?></option>
                    <?php endforeach; ?>

                    <?php foreach($years as $year) : ?>
                <option value="<?php echo  site_url() .'/'.$year ?>"><?php echo '<ul><li class"list-unstyled">' . $year .'</li></ul>';?></option>
                    <?php endforeach; ?>    
            </select>
        </li>
        <li>
          <label>
            <select onChange="window.location.href=this.value">
                <option value="category" disabled selected> Category </option>
                    <?php foreach( $categorys as $category ) : ?>
                <option value="?category=<?php echo $category->slug; ?>">
                    <?php echo $category->name; ?>
                </option>
                <?php endforeach; ?>
            </select>
            </label>
        </li>       
      </ul>   
      </div>
    </form>

Now the final url reads

http://mywebsite.com/2015/09/?category=special-events

To make sure that the query finds the category only for that month the $args must include a dynamic date_query like this:

$m = get_the_time('m');
$y = get_the_time('Y');

$args = array(
            'post_type'      => array('post'),
            'post_status'    => 'publish',
            'tax_query'      => $cat_query,
            'orderby'        => 'date',
            'order'          => 'desc',
            'date_query' => array(
    array(
        'year'  => $y,
        'month' => $m,
    ),
),  

);

For anyone else looking to filter by date WITHOUT the URL component, this is what I ended up using this for the form:

<!-- Filter Form -->
<form method="GET" action="/research-submissions/" id="submissionsFilterForm">
    <div class="filter-form--content">
        <div class="filter-items">

            <!-- Years -->
            <div class="filter-item year">
                <?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC"); ?>
                <select name="years[]">
                    <option disabled selected><?php _e('Year', 'twentytwentyone'); ?></option>
                    <?php foreach($years as $year) : ?>
                        <option 
                            value="<?= $year; ?>"
                            <?php echo selected(
                                (isset($_GET['years']) && in_array($year, $_GET['years']))
                            ) ?>
                        ><?= $year; ?></option>
                        <?php endforeach; ?>
                </select>
            </div>
            
        </div>  
        <div class="category-filters--submit">
            <button type="submit" name=""><?php _e('Search', 'twentytwentyone'); ?></button>
        </div>
    </div>
</form> 

And this for the wp_query with args:

<!-- Results -->
<div class="submissions-content">
            
    <?php 
    
    // Years
    if($_GET['years'] && !empty($_GET['years'])) {
      $yearsF = $_GET['years'];
      foreach  ($yearsF as $yearF) {
          $year_filter = $yearF;
      }
    }
    
    global $post;

    $date_query = array('relation' => 'AND');
    if( isset($_GET['years']) ) {
        $date_query[] =  array(
            'year'     => $year_filter,
        );
    }
            
    $args = array(
        'post_type'         => array('post'),
        'posts_per_page'    => -1,
        'date_query'        => $date_query,
    );
            
    $query = new WP_Query($args);
        if ( $query->have_posts() ) : 
            while($query -> have_posts()) : $query -> the_post();

                $title = get_the_title($post->ID); 
                $date = get_the_date( 'F j, Y' ); ?>

                <div class="single-post submission">
                  <h3><?= $title; ?></h3>
                  <time><?= $date; ?></time>
                </div>
            
            <?php endwhile;
            
            else : ?>

                <div class="single-post error">
                    <?php _e('Oops! Nothing matches your search', 'twentytwentyone'); ?>. <span><?php _e('Try again', 'twentytwentyone'); ?></span>.
                </div>

        <?php endif;
            
        wp_reset_query(); ?>
            
</div>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论