I am testing the new (experimental ) Query Sort, Filter & Live Search on the default posts
If possible I would like to use “post_date” to filter.
I would then like to display “post_date” as year (2022) in a button style so user can click the year button and this will show all posts from that year
I just can’t figure it out, i cant find how to select the meta key “post_date”
is there anyone who has tested this successfully or maybe someone who knows how to do this
I am also trying to use a select filter that should filter my posts based on the year. I haven’t found any input or any way to insert the {post_year} in Bricks select filter.
Any ideas anyone? I hope the answer is not to “just use WP Grid Builder”.
Update: After searching and researching I realized that there is no native way to do this so I decided to create a taxonomy with the years. This is one more click but it does the job.
// Register the Custom Taxonomy Year
function register_year_taxonomy() {
register_taxonomy(
‘year’, // Taxonomy slug
‘post’, // Post type it applies to
array(
‘label’ => __(‘Year’),
‘rewrite’ => array(‘slug’ => ‘year’),
‘hierarchical’ => false, // Set to true if you want it to behave like categories
)
);
}
add_action(‘init’, ‘register_year_taxonomy’);
//Assign the Year to Posts Automatically
function assign_year_taxonomy_term($post_id) {
if (get_post_type($post_id) !== ‘post’) {
return;
}
$year = get_the_date('Y', $post_id); // Get the year of the post
wp_set_post_terms($post_id, $year, 'year', true); // Assign the year to the 'year' taxonomy
// This will loops through all posts, gets their published year, and assigns the year to the year custom taxonomy.
function update_all_posts_with_year_taxonomy() {
// Get all posts
$args = array(
‘post_type’ => ‘post’,
‘posts_per_page’ => -1, // Retrieve all posts
‘post_status’ => ‘publish’, // Only published posts
);
$all_posts = get_posts($args);
foreach ($all_posts as $post) {
// Get the year of the post
$year = get_the_date('Y', $post->ID);
// Assign the year as a term in the 'year' taxonomy
wp_set_post_terms($post->ID, $year, 'year', true);
}
echo 'All posts have been updated with the Year taxonomy.';
}
// Hook it to a WordPress action or run it manually
update_all_posts_with_year_taxonomy();