简体   繁体   中英

WordPress - Get all categories with filtered Posts

I'm using wp_dropdown_categories to generate a list of categories as the dropdown options, by setting the hide_if_empty to true in parameters, the function will only list out categories with attached posts.

But what I want to achieve is I only want to show categories with active posts , I have custom fields from_date and to_date to determine the validity of the posts so I can filter the active posts with the meta_query below:

array(
  'key'     => 'to_date',
  'value'   => $today_date,
  'compare' => '>='
)

Is there a way I can filter down the categories by meta query, as currently the category will be outputted as long as there are posts attached to it.

Trying to look for something like:

<?php 
  $args = array(
    'show_option_all' => 'All',
    'hide_empty'      => 1,
    'selected'        => $selected,
    'hide_if_empty'   => true,
    'value_field'     => 'slug',
    'meta_query'      => array(
      // Conditions to filter out categories without active posts
    ),
  ); 
?>

<div id="filter-select-wrapper">
  <?php wp_dropdown_categories( $args ); ?> 
</div>

Use below code to show posts which are active from today:

<?php 
  $today = date( 'Y-m-d' );
  $args = array(
    'show_option_all' => 'All',
    'hide_empty'      => 1,
    'selected'        => $selected,
    'hide_if_empty'   => true,
    'value_field'     => 'slug',
    'meta_query' => array(
        array(
            'key' => 'to_date',
            'value' => $today,
            'compare' => '>=',
            'type' => 'DATE'
        )
    )
  ); 
?>

<div id="filter-select-wrapper">
  <?php wp_dropdown_categories( $args ); ?> 
</div>

Use this code,

 <?php $args = array ( 'showposts' => '1', 'category_name' => 'apples', 'paged' => $paged ); $the_query = new WP_Query( $args ); if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 

For More Information, Reference Link

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