在WordPress中使用AJAX向自定义帖子分类过滤器添加“所有帖子”按钮

时间:2020-01-05 作者:Sara Teofilova

有人知道如何使用自定义分类(“album\\u category”)将“所有帖子”按钮添加到我的自定义帖子(“albums”)中吗?我可以看到我的类别(混合、掌握、制作),当我单击它们时,它会显示在特定类别(混合、掌握、制作)下打勾的帖子。我想要的是还有一个“所有帖子”按钮,这样用户可以在查看过滤后的帖子后返回显示所有帖子。

我知道我可以用wp\\u list\\u类别(array(\'show\\u option\\u all\'=>“all Posts”))做到这一点;但我不知道如何在代码中实现它。

以下是我的完整代码:

我的相册页面。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>

我的职能。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\');

我的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();
            }
        })

    });
});

1 个回复
SO网友:Dip Patel

我更新了你的代码有2-3个错误js file datatypefunction file query parameter.下面我粘贴了一个更新的代码,请检查并让我知道,如果有任何疑问。

你的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();
?>
您的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\');

您的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();
            }
        })

    });
谢谢。