Фильтр товаров по категориям с проблемой AJAX с отображением товаров - PullRequest
0 голосов
/ 28 мая 2019

У меня проблема с отображением продуктов из категории с ajax. Я отобразил все категории и все продукты на странице, а мои категории являются ссылками, и я запретил действие по умолчанию для ссылок, и я хочу добиться этого. Когда вы нажимаете на ссылку категории, которая запускает Ajax и показывает ниже продукты из этой категории, все происходит на той же странице без перезагрузки. Но все, что я получил, это "пост не найден", когда я нажимаю на ссылку категории

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(
      'tag' => $taxonomy,
      'post_type' => 'product',
      'posts_per_page' => 10

    );


    if( !$taxonomy ) {
      unset( $args['tag'] );
    }

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

    die();
  }

  add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
  add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
<article>
<?php
/**
 * Template name: AJAX Post Filter by Taxonomy
 *
 */
get_header();
$args = array(
    'post_type' => 'product',
    'posts_per_page' => 10
);

$query = new WP_Query( $args );

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

if ( $count > 0 ): ?>
    <div class="post-tags">
    <?php
        echo '<div class="container">';
        echo '<div class="row">';
        foreach ( $terms as $term ) {
         $term_link = get_term_link( $term, $tax );

         echo '<div class="col-4">';
        echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> ';
        echo '</div>';

     }
     echo '</div>';
        echo '</div>';
     ?>
    </div>
<?php endif;

if ( $query->have_posts() ): ?>
<div class="tagged-posts">
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>

    <h2><a class="<?php echo $term->name; ?>" 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;  ?>

</article>
<?php
get_footer();
jQuery(document).ready(function( $ ) {
    $('.tax-filter').click( function(event) {


        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false;
        }

        var selecetd_taxonomy = $(this).attr('title');

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

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

        $.ajax({
            type: 'product',
            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 Ответ

0 голосов
/ 28 мая 2019

В ваших аргументах запроса вы фильтруете по tag, тогда как термин таксономии, который вы передаете, на самом деле product_cat.

Попробуйте изменить аргументы запроса в ajax_filter_get_posts на следующее:

$args = array(
  'post_type' => 'product',
  'posts_per_page' => 10
  'tax_query' => array(
    array (
      'taxonomy' => 'product_cat',
      'field' => 'slug',
      'terms' => $taxonomy,
    )
  ),
);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...