1

I've been trying to create AJAX categories filters but I can't get the code working. I've followed these instructions : http://juha.blog/dev/wordpress/ajax-filters-for-wordpress-categories/

Edit : So I fixed the script by replacing $(this) by jquery(this) but now as I click on the filters, all the articles disappear, and show up againt when I click (all articles".

So in my template :

<!-- Filters -->
<ul class="xiong-filters">
    <?php 
        $args= array(  
            'show_option_all'   =>   'All posts', //Text for button All
            'title_li'          => __('')
        );
    wp_list_categories( $args );
    ?>
</ul>

<!-- Loop -->
<?php if ( have_posts() ) :?>
<div id="main-content" class="row">
    <div id="inside">
        <div class="container">

            <?php while ( have_posts() ) : the_post(); ?>
                <article>
                    <a class="xiong-articlebox" href="<?php the_permalink();?>">
                        <header>
                            <h3><?php the_title( );?></h3>
                            <p><em><?php the_date( 'j.n.Y'); ?> </em></p>
                        </header>
                        <p><?php the_excerpt();?></p>
                    </a>
                </article>
            <?php endwhile; endif; ?>

        </div><!-- container-->  
    </div><!--inside -->                   
</div>  <!--row -->

In my function.php

//ENQUEUE SCRIPTS HERE
function xiong_theme_scripts() {
    //Ajax filter scripts     
    wp_register_script( 'ajax', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'ajax' );
    }
add_action( 'wp_enqueue_scripts', 'xiong_theme_scripts' );

In my ajax.js

//AJAX Filters

jQuery(function(){
    var mainContent = jQuery('#main-content'),
        cat_links = jQuery('ul.xiong-filters li a');

        cat_links.on('click', function(e){

            e.preventDefault();
            el = jquery(this);
            var value = el.attr("href");
            mainContent.animate({opacity:"0.5"});
            mainContent.load(value + " #inside", function(){
                mainContent.animate({opacity:"1"});
            });
            jQuery( "li" ).removeClass( "current-cat" );
            jQuery(this).closest('li').addClass("current-cat");
        });
});

I don't know how to fix it as I don't know much js at all so thanks in advance so much !

  • In your JavaScript file (ajax.js) change $ to jQuery – user141080 Oct 2 '18 at 16:06
  • I tired replacing $(this) by jquery(this) but I still get the same error. I alsa replaced it in $el.attr but that didn't help. – Caroline Oct 3 '18 at 7:08
  • The error i now get it : $el is not defined – Caroline Oct 3 '18 at 7:19

Your Answer

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

Browse other questions tagged or ask your own question.