Custom Wordpress Ajax Taxonomy

I currently have wordpress with a custom post type and custom taxonomy attached to this. (jobs_category).

I have an assembly that lists the categories from this taxonomy:

<?php
  $taxonomy = 'jobs_category';
  $tax_terms = get_terms($taxonomy);
?>
<ul>
  <?php
  foreach ($tax_terms as $tax_term) {?>
    <li id="cat-<?php echo $tax_term->term_id; ?>">
     <a href="#<?php //echo esc_attr(get_term_link($tax_term, $taxonomy)); ?>" class="<?php echo $tax_term->slug; ?> ajax" onclick="cat_ajax_get('<?php echo $tax_term->term_id; ?>');" title="<?php echo $tax_term->name;?>"><?php echo $tax_term->name; ?></a>
    </li>
  <? } ?>
</ul>

In my function file, I used the following:

    add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
    $cat_id = $_POST[ 'cat' ];
         $args = array (
        'cat' => $cat_id,
        'posts_per_page' => 10,
        'order' => 'DESC'

    );

    $posts = get_posts( $args );

    ob_start ();

    foreach ( $posts as $p ) { ?>

    <div id="post-<?php echo $post->ID; ?>">
        <h1 class="posttitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>

        <div id="post-content">
        <?php the_excerpt(); ?>

        </div>
   </div> 


   <?php } wp_reset_postdata();

   $response = ob_get_contents();
   ob_end_clean();

   echo $response;
   die(1);
}

To execute AJAX with the following JS:

    <script>
function cat_ajax_get(catID) {
    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-2").show();
    var ajaxurl = '/wp-admin/admin-ajax.php';
    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {"action": "load-filter", cat: catID },
        success: function(response) {
            jQuery("#category-post-content").html(response);
            jQuery("#loading-animation").hide();
            return false;
        }
    });
}
</script>

My question is how to get it to use custom taxonomy categories? Im not 100% sure because i have never done this before.

Any help would be great.

thank

+4
source share
1 answer

tax_query cat. category Wordpress, .

$args :

$args = array (
    'tax_query' => array(
         array(
            'taxonomy' => 'jobs_category',
            'field' => 'term_id',
            'terms' => array( $cat_id )
         )
    ),
    'post_type' => 'jobs', // <== this was missing
    'posts_per_page' => 10,
    'order' => 'DESC'
);
+7

Source: https://habr.com/ru/post/1542637/


All Articles