3

I found this post that describes how to filter category posts with Ajax and it works great, but I also want to filter my custom taxonomies the same way and I can't get it to work. It shows me all posts instead of just the posts from my taxonomy.

I know the menu needs to be changed to get_the_terms instead of get_the_categories but I specifically need help with what to change in the jQuery function and the php function at the bottom. I tried adding a tax_query calling my taxonomy but it's still not showing the correct posts. Can anyone help point me in the right direction?

8
  • I get a fatal undefined function error when I try to use get_the_categories() Are you sure you don't mean get_the_category?
    – s_ha_dum
    Apr 20 '13 at 20:00
  • @s_ha_dum That's what the original developer used, but you may be correct. That code is a few years old so maybe the function changed? I'm not even using that to call my category list since I want to be able to list them in a specific order. My category links look like this: <li id="cat-8"><a class="category ajax" onclick="cat_ajax_get('8');" href="#">Category</a></li>
    – Emily
    Apr 20 '13 at 20:46
  • 1
    It sounds like you are doing something different from that post you referenced. Please edit your question to include your code.
    – s_ha_dum
    Apr 20 '13 at 21:32
  • 1
    @s_ha_dum Ok, I just did that. It won't let me accept the answer for 23 hours, but I'll come back and do that tomorrow.
    – Emily
    Apr 21 '13 at 20:21
  • 1
    I can upvote you though. Self-solving warms my heart. :)
    – s_ha_dum
    Apr 21 '13 at 20:33
8

I figured it out! Here is the code I used:

Add to functions.php:

add_action( 'wp_ajax_nopriv_load-filter2', 'prefix_load_term_posts' );
add_action( 'wp_ajax_load-filter2', 'prefix_load_term_posts' );
function prefix_load_term_posts () {
        $term_id = $_POST[ 'term' ];
            $args = array (
            'term' => $term_id,
            'posts_per_page' => -1,
            'order' => 'DESC',
                 'tax_query' => array(
                  array(
                      'taxonomy' => 'yourtaxonomyhere',
                      'field'    => 'id',
                      'terms'    => $term_id,
                      'operator' => 'IN'
                      )
                  )
             );

        global $post;
        $myposts = get_posts( $args );
        ob_start (); ?>

        <ul class="list">
        <?php foreach( $myposts as $post ) : setup_postdata($post); ?>
            <li><a href="<?php the_permalink(); ?>" id="post-<?php the_ID(); ?>"><?php echo get_post_meta($post->ID, 'image', $single = true); ?></a><br />
             <?php the_title(); ?></li>
       <?php endforeach; ?>
        </ul>

       <?php wp_reset_postdata(); 
       $response = ob_get_contents();
       ob_end_clean();
       echo $response;
       die(1);
}

jQuery script:

<script>
function term_ajax_get(termID) {
    jQuery("a.ajax").removeClass("current");
    jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
    jQuery("#loading-animation").show();
    var ajaxurl = 'http://yourdomain.com/wp-admin/admin-ajax.php';
    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {"action": "load-filter2", term: termID },
        success: function(response) {
            jQuery("#category-post-content").html(response);
            jQuery("#loading-animation").hide();
            return false;
        }
    });
}
</script>

I'm not using a function to list the categories, I'm just listing each of them separately. Replace the number with the ID of your term:

<ul class="nav">
     <li id="term-166"><a class="yourtermname ajax" onclick="term_ajax_get('166');" href="#">Your Term Name</a></li>
     <li id="term-354"><a class="yourtermname ajax" onclick="term_ajax_get('354');" href="#">Your Term Name</a></li>
</ul>

Also, if you want to filter tags instead of terms, replace:

  • 'term' with 'tag__in',
  • $term_id with $tag_id
  • and change 'taxonomy' => 'yourtaxonomyhere' to 'taxonomy' => 'post_tag'.
0

I suggest that you use a shortcode to display taxonomy of your choice : create a class to declare the shortcode and call this function

  public function shortcode($atts)
{
 extract(shortcode_atts( array(
    'data' => 'taxonomy',
    'taxonomy' => 'category',
    //get_terms arguments
    'parent' => 0, //only get top level terms by default
    'exclude'=>'',
    'type'=>'radio' // checkbox,radio
    ), $atts,'astSearchInput' ));

$arrStr =array();
$arrStr[]= "<div class='astSearchInput " . $taxonomy. "' taxonomy='" .$taxonomy. "'>"  ;
if ($type=="checkbox" || $type=="radio")
{
    if ($data=="taxonomy")
        {
        //echo $datatata;
        $arrValues=get_terms($taxonomy, array("parent"=>$parent, "exclude"=>$exclude)); 
        }


     if ($type=="checkbox")$arrStr[]= $this->inputCheckBox($arrValues,$atts);
     if ($type=="radio")$arrStr[]= $this->inputRadio($arrValues,$atts);
}
$arrStr[]= "</div>";
$str=join("\n",$arrStr);
return $str  ;
}




    function inputCheckBox($arrValues,$attr)
{
    $arrStr =array();
    $arrStr[]='<div class="formcb">';
    foreach($arrValues as $k=>$term)
        {
            $title=$term->name; //$term->description 
            //  print_r($term);
            $id="cb" . $term->term_id;
            $arrStr[]='<div class="cb"><input class="astInpuntTerm astcheckBox" type="checkbox" id="' . $id  .'" value="' . $term->term_id . '" ><label for="' . $id . '">' . $title. '</label></div>';
        }
    $arrStr[]='</div>'; 
    $str=join("\n",$arrStr);    
        return $str;
}

http://www.webmasterbulletin.net/wordpress-ajax-taxonomy-search-shortcode

0

I had a similar problem.

The code is good, but it needs to small modify to work.

            $args = array (
        'term' => $term_id,
        'posts_per_page' => -1,
        'order' => 'DESC',
             'tax_query' => array(
              array(
                  'taxonomy' => 'yourtaxonomyhere',
                  'field'    => 'id',
                  'terms'    => $term_id,
                  'operator' => 'IN'
                  )
              ),
               'post_type' => 'yourcustomposttype', // <== this was missing
'posts_per_page' => 10,
'order' => 'DESC'
         );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.