1

Does somebody know how to add "All Posts" button to my custom post ("albums") with custom taxonomy ("album_category")? I can see my categories (Mixing, Mastering, Production) and when I click on them it shows me the posts that have been ticked under the certain category (Mixing, Mastering, Production). What I want is to have also a button "All Posts" so the user can go back to displaying all posts, once he has viewed the filtered posts.

I know that I can do that with wp_list_categories(array('show_option_all' => "All Posts")); But I don't know how to implement it into the code.

Here is my full code:

My album-page.php

$args = array(
    'post_type' => 'albums',
    'posts_per_page' => 10,
);

$query = new WP_Query( $args );

$tax = 'album_category';
$terms = get_terms( $tax );
$count = count( $terms );

if ( $count > 0 ): ?>
    <div class="post-tags">
    <?php
    foreach ( $terms as $term ) {
        $term_link = get_term_link( $term, $tax );
        echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> ';
    } ?>
    </div>
<?php endif;
if ( $query->have_posts() ): ?>
<div class="tagged-posts">
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>

    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php the_excerpt(); ?>

    <?php endwhile; ?>
</div>

<?php else: ?>
    <div class="tagged-posts">
        <h2>No posts found</h2>
    </div>
<?php endif;
wp_reset_postdata(); ?>
</article>

My functions.php:

function ajax_filter_posts_scripts() {
    // Enqueue script
    wp_enqueue_script('jquery');
    wp_register_script('afp_script', get_template_directory_uri() . '/assets/src/js/ajax-filter-posts.js', 'jquery', null, true);
    wp_enqueue_script('afp_script');

    wp_localize_script( 'afp_script', 'afp_vars', array(
          'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
          'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
        )
    );
  }
  add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);

  // Script for getting posts
  function ajax_filter_get_posts( $taxonomy ) {

    // Verify nonce
    if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
      die('Permission denied');

    $taxonomy = $_POST['album_category'];

    // WP Query
    $args = array(
      'taxonomy' => $taxonomy,
      'post_type' => 'albums',
      'posts_per_page' => 10,
    );

    // If taxonomy is not set, remove key from array and get all posts
    if( !$taxonomy ) {
      unset( $args['album_category'] );
    }

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

      $output  = '<h2><a href="'.get_permalink().'">'. get_the_title().'</a></h2>';
      $output .= get_the_excerpt();

      $result = 'success';

    endwhile; else:
      $output = '<h2>No posts found</h2>';
      $result = 'fail';
    endif;

    $response = json_encode($output);
    echo $response;

    wp_reset_postdata();

    die();
  }

  add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
  add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');

My ajax.js

jQuery(document).ready(function($) {
    $('.tax-filter').click( function(event) {

        // Prevent defualt action - opening tag page
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false;
        }

        // Get tag slug from title attirbute
        var selecetd_taxonomy = $(this).attr('title');

        $('.tagged-posts').fadeOut();

        data = {
            action: 'filter_posts',
            afp_nonce: afp_vars.afp_nonce,
            taxonomy: selecetd_taxonomy,
        };

        $.ajax({
            type: 'post',
            dataType: 'json',
            url: afp_vars.afp_ajax_url,
            data: data,
            success: function( data, textStatus, XMLHttpRequest ) {
                $('.tagged-posts').html( data );
                $('.tagged-posts').fadeIn();
                console.log( textStatus );
                console.log( XMLHttpRequest );
            },
            error: function( MLHttpRequest, textStatus, errorThrown ) {
                console.log( MLHttpRequest );
                console.log( textStatus );
                console.log( errorThrown );
                $('.tagged-posts').html( 'No posts found' );
                $('.tagged-posts').fadeIn();
            }
        })

    });
});
0

I updated your code there is 2-3 mistake in js file datatype and function file query parameter. Below I paste an updated code, please check and let me know incase of any doubts.

Your album-page.php

<?php
$args = array(
    'post_type' => 'albums',//Custom Post type name
    'posts_per_page' => 10,
);

$query = new WP_Query($args);

$tax = 'album_category';//Custom post type taxonomy name
$terms = get_terms($tax);
$count = count($terms);

if ($count > 0):
    ?>
    <div class="post-tags">
        <?php
        echo '<a href="#" class="tax-filter" title="">All</a> ';
        foreach ($terms as $term) {
            $term_link = get_term_link($term, $tax);
            echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> ';
        }
        ?>
    </div>
<?php
endif;
if ($query->have_posts()):
    ?>
    <div class="tagged-posts">
    <?php while ($query->have_posts()) : $query->the_post(); ?>

            <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <?php the_excerpt(); ?>

    <?php endwhile; ?>
    </div>

<?php else: ?>
    <div class="tagged-posts">
        <h2>No posts found</h2>
    </div>
<?php
endif;
wp_reset_postdata();
?>

Your functions.php

function ajax_filter_posts_scripts() {
    // Enqueue script
    wp_enqueue_script('jquery');
    wp_register_script('afp_script', get_template_directory_uri() . '/assets/src/js/ajax-filter-posts.js', 'jquery', null, true);
    wp_enqueue_script('afp_script');

    wp_localize_script( 'afp_script', 'afp_vars', array(
          'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
          'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
        )
    );
  }
  add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
// Script for getting posts
function ajax_filter_get_posts($taxonomy) {
    // Verify nonce
    if (!isset($_POST['afp_nonce']) || !wp_verify_nonce($_POST['afp_nonce'], 'afp_nonce'))
        die('Permission denied');
    $taxonomy = $_POST['taxonomy'];
    // WP Query
    $args = array(
        'post_type' => 'albums',//Custom Post type name
        'posts_per_page' => -1,
    );
    if (!empty($taxonomy)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'album_category',//Custom post type taxonomy name
                'field' => 'slug',
                'terms' => $taxonomy,
            ),
        );
    }
    $query = new WP_Query($args);
    if ($query->have_posts()) :
    ?>
    <div class="tagged-posts">
        <?php while ($query->have_posts()) : $query->the_post(); ?>

            <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <?php the_excerpt(); ?>

        <?php endwhile; ?>
    </div>
    <?php
    endif;
    wp_reset_postdata();
    die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');

Your ajax.js

jQuery('.tax-filter').click(function (event) {
        // Prevent defualt action - opening tag page
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false;
        }
        // Get tag slug from title attirbute
        var selecetd_taxonomy = $(this).attr('title');
        $('.tagged-posts').fadeOut();
        var data = {
            action: 'filter_posts',
            afp_nonce: afp_vars.afp_nonce,
            taxonomy: selecetd_taxonomy,
        };
        $.ajax({
            type: 'post',
            dataType: 'html',//Return type is html
            url: afp_vars.ajaxurl,
            data: data,
            success: function (data, textStatus, XMLHttpRequest) {
                $('.tagged-posts').html(data);
                $('.tagged-posts').fadeIn();
                console.log(textStatus);
                console.log(XMLHttpRequest);
            },
            error: function (MLHttpRequest, textStatus, errorThrown) {
                console.log(MLHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);
                $('.tagged-posts').html('No posts found');
                $('.tagged-posts').fadeIn();
            }
        })

    });

Thanks.

|improve this answer|||||
  • Thanks, but i still can't see where do you add a category that includes all posts. For example like wp_list_categories() has 'show_option_all'. I want to implement it into my code, and I don't know how. – Sara Teofilova Jan 7 at 11:27
  • I added a link above $terms foreach loop in album-page.php echo '<a href="#" class="tax-filter" title="">All</a> '; – Dip Patel Jan 10 at 7:23
  • this solution works ? – Dip Patel Jan 18 at 4:52
  • 1
    yes, thank you. I made it work – Sara Teofilova Jan 24 at 20:43
  • @SaraTeofilova If my answer give you a solution then please upvote my answer. – Dip Patel Jan 29 at 16:19

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.