Wordpress Ajax自定义分类法



我目前有一个wordpress与自定义的帖子类型和自定义的分类法附加到这个。

我从这个分类法中列出了分类,如下所示:

<?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>

然后我在我的函数文件中使用了以下代码:

    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);
}

使用以下JS执行AJAX:

    <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>

我的问题是如何让它使用自定义分类法类别?我不是百分之百确定,因为我以前从来没有做过。

请帮忙就太好了。

谢谢

您必须使用 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'
);

最新更新