skip to Main Content

I’m creating an Ajax filter on a category page and am wanting to filter the posts by post_tag AND the current category. The issue I am having is get_queried_object isn’t outputting any value when the filter is submitted. It works perfectly when I manually type in the category ID, but obviously this isn’t going to work as I have multiple categories.

<?php
// Filter blog.
add_action('wp_ajax_filter_cases','filter_function_blog');
add_action('wp_ajax_nopriv_filter_cases','filter_function_blog');

function filter_function_blog() {
  $catID = get_queried_object(); // This should get the current category
  
  $post_args = array(
    'post_type' => 'case-studies',
    'posts_per_page' => 999,
  );
  $post_args['tax_query'] = array( 'relation' => 'AND' );

  $post_args['tax_query'] = array(
    array(
      'taxonomy' => 'category',
      'field' => 'id',
      'terms' => $catID->term_id // This should output the current category ID
    ),
    array(
        'taxonomy' => 'post_tag',
        'field' => 'id',
        'terms' => $_POST['tag-select']
    )
);

2

Answers


  1. Chosen as BEST ANSWER

    Managed to find a fix for this by getting the URL and stripping out everything so I'm left with just the slug.

    $url = wp_get_referer();
    $slug = str_replace(get_site_url(), '', $url);
    $cleanSlug = str_replace('/', '', $slug);
    $catID = get_category_by_slug($cleanSlug);
    

    Then I'm able to use $catID to get the correct value to put into my tax query

     array(
       'taxonomy' => 'category',
       'field' => 'id',
       'terms' => $catID->term_id
     ),
    

  2. I think that you can’t use it. Should pass it through the ajax call or try to do this in your filter_function_blog:

    $url = wp_get_referer();
    $post_id = url_to_postid( $url ); 
    $category = get_the_category($post_id); // returns an array with cat info
    $category_id = $category[0]->term_id;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search