How to sort wordpress posts by selecting a year from a drop down?

I answered my own question. I’m just a beginner, so the code is trash; I know, don’t judge.

What you have to do is create a new query. First, go to your themes category.php file.

People need to select the year from your ul/li menu. For me it is:

<ul class="dropdown-menu">
<li class="nav-item"><a href="?orderbyyear=2021" class="nav-link dropdown-item" type="button" role="tab">2021</a></li></ul>

‘?orderbyyear=2021’ Doesn’t exist; I made it up. It doesn’t do anything in WordPress. We are just checking the URL for ‘2021’. Next, add these below:

<?php
                                $cat_ID = get_query_var('cat'); // Get the current category, if you don't it will display all (your choice)
                                $args = array(
                                    'cat' => $cat_ID, // determine, you add other stuff here. Such as post_per_page, cat_id, etc.
                                    'date_query' => array(
                                        array(
                                            'year'  => 2021,
                                        ),
                                    ),
                                );
                                $myYearQuery = new WP_Query($args); ?>

Next, check your URL for the year you wish (you need to create a new if-else for each year you want). We need to check the URL for ‘2021’ using if-else. I’m sure there is a simpler and smarter way that I don’t know. Maybe it can be created in the functions.php and use get.

                                <?php
                                $url = $_SERVER["REQUEST_URI"];
                                $isityear = strpos($url, '2021');
                                if ($isityear!==false) {
                                if ( $myYearQuery->have_posts() ) : while ( $myYearQuery->have_posts() ) : $myYearQuery->the_post(); ?>

Do your blog’s php/html/css -here- and end it.

<?php endwhile; endif; ?>

Repeat this for all your years. At the very end, you also need to add your normal code. Because if people don’t select a year, you need to display post normally.

<?PHP else if (have_posts()) : while (have_posts()) : the_post(); ?>

Don’t forget to end your normal while/if as well.
Well. That’s how I solved it. Hope it helps someone. I’m sure people who know will do it easily.

You can also add pagination if you need. I’ve did it like this:

<?php the_posts_pagination( array(
    'mid_size' => 1,
    'prev_text' => __( '<', 'textdomain' ),
    'next_text' => __( '>', 'textdomain' ),
) ); ?>

So what we got is

domain/category/ > Normal Posts
domain/category/?orderbyyear=2022 > Posts from 2022
domain/category/?orderbyyear=2021 > Posts from 2021
domain/category/?orderbyyear=2020 > Posts from 2020…

Etc.