How to create filter's for custom taxonomy page

what i want to do it's create filters for my custom taxonomy page.

For example.

I allready have a custom taxonomy created with thumbnails and pagination ready, but i want to add filter's for the girls.

Filter's for select the color of the hair to see the girls for examle : I want to see blonde girls, or for country and etc and also i want filters of most videos, most visited and etc..

Hair and etc example : https://prnt.sc/tjkc3d

Most visited example : https://prnt.sc/tjkbei

How i will be able to do can you help me please ? thanks.

Topic request-filter custom-taxonomy Wordpress

Category Web


You can use the filter pre_get_posts to manipulate the global WP_Query Object to apply your filters.

If your filters add a URL parameter, you can manipulate the query and adjust it to your liking.

Here is an example. You still have to adjust the taxonomy and post type to make it work for you.

<?php // functions.php

/**
 * Modifies the query in a Post Type Archive and defines the taxonomy for hair color.
 * 
 * @param WP_Query $query The global WP_Query Object.
 *
 * @return WP_Query
 */
function my_custom_query( $query ) {

  /**
   * Here we tell WordPress that we want to adjust the query when we
   * are not in the admin area and only on the post type archive for girls.
   */
  if ( ! is_admin() && is_post_type_archive( 'girl' ) ) {

    /**
     * Here we check whether a query parameter hair_color is available and then
     * apply it. To do this, we change the taxonomy of the current query.
     */
    if ( isset( $_GET['hair_color'] ) && '' !== $_GET['hair_color'] ) {
      $hair_color = sanitize_text_field( wp_unslash( $_GET['hair_color'] ) );

      /**
       * Here we define the term hair_color for the taxonomy hair_colors.
       */
      $hair_taxonomy = [
        [
          'taxonomy' => 'hair_colors',
          'field'    => 'slug',
          'terms'    => $hair_color,
        ],
      ];

      $query->set( 'tax_query', $hair_taxonomy );
    }
  }

  /**
   * Here we return the manipulated query.
   */
  return $query;
}

/**
 * Here our manipulated query is transferred to WordPress.
 */
add_filter( 'pre_get_posts', 'my_custom_query' );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.