Using WordPress ‘pre_months_dropdown_query’ PHP filter

‘pre_months_dropdown_query’ is a WordPress PHP filter that allows you to short-circuit the months dropdown query, which means you can bypass the default query and provide your own custom results.

Usage

function my_pre_months_dropdown_query( $months, $post_type ) {
// your custom code
return $filtered_months; 
} 
add_filter( 'pre_months_dropdown_query', 'my_pre_months_dropdown_query', 10, 2 );

Parameters

  • $months (object[]|false): The months drop-down results. Default is false.
  • $post_type (string): The post type for which the filter is being applied.

Examples

Remove empty months from the dropdown

function remove_empty_months( $months, $post_type ) {
// Filter out months with no posts
$filtered_months = array_filter( $months, function( $month ) {
return $month->post_count > 0;
});
return $filtered_months; 
} 
add_filter( 'pre_months_dropdown_query', 'remove_empty_months', 10, 2 );

This code snippet removes any month from the dropdown that has no posts associated with it. It filters the $months array, keeping only the months with a post count greater than 0.

Show only the last 6 months

function show_last_six_months( $months, $post_type ) {
// Get only the last 6 months
$recent_months = array_slice( $months, 0, 6 );
return $recent_months; 
} 
add_filter( 'pre_months_dropdown_query', 'show_last_six_months', 10, 2 );

This example limits the months dropdown to display only the last 6 months. It uses array_slice to select the first 6 elements of the $months array.

Reverse the order of the months

function reverse_months_order( $months, $post_type ) {
// Reverse the order of the months
$reversed_months = array_reverse( $months );
return $reversed_months; 
} 
add_filter( 'pre_months_dropdown_query', 'reverse_months_order', 10, 2 );

This code snippet reverses the order of the months in the dropdown. It uses array_reverse to reverse the $months array.

Exclude a specific post type

function exclude_specific_post_type( $months, $post_type ) {
// Exclude 'product' post type
if ( $post_type === 'product' ) {
return false;
}
add_filter( 'pre_months_dropdown_query', 'exclude_specific_post_type', 10, 2 );

This example prevents the months dropdown query from being performed for the ‘product’ post type. If $post_type is equal to ‘product’, the filter returns false.

Show only months with a specific number of posts

function show_months_with_specific_post_count( $months, $post_type ) {
// Filter months with a post count of 5
$filtered_months = array_filter( $months, function( $month ) {
return $month->post_count == 5;
});
return $filtered_months; 
} 
add_filter( 'pre_months_dropdown_query', 'show_months_with_specific_post_count', 10, 2 );

This code snippet filters the months dropdown to display only the months with a specific post count, in this case, 5 posts. It filters the $months array, keeping only the months with a post count equal to 5.