WordPress AJAX函数中的回显简码返回

时间:2018-07-12 08:27:27

标签: php ajax wordpress

我在这里和网络上进行了搜索,但似乎无法正常工作-希望大家都能提供帮助。

我正在尝试在类别页面上设置WooCommerce的产品过滤器(例如根据颜色等过滤产品)

我正在使用ajax,但是我想为每个产品显示一个简码,但是这不起作用-关于如何显示它的任何想法?

以下代码:

PHP

function ajax_filter_posts_scripts() {
  // Enqueue script
wp_register_script('afp_script', plugins_url() . '/plugin-name/js/product-filter-ajax.js', false, null, false);
  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);

JS

    jQuery(document).ready(function($) {

        $(".loading").hide();

var taxonomy = [];
var terms = [];

         $('.filter-option input').click( function(event) {

                 var taxonomy_idx = $.inArray($(this).closest(".filter-title-wrapper").attr('data-attribute'), taxonomy);
                 if (taxonomy_idx == -1) {
             taxonomy.push($(this).closest(".filter-title-wrapper").attr('data-attribute'));
             } else {
         taxonomy.splice(taxonomy_idx, 1);
            }

            var terms_idx = $.inArray($(this).val(), terms);
            if (terms_idx == -1) {
            terms.push($(this).val());
        } else {
        terms.splice(terms_idx, 1);
     }



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

            // Get tag slug from title attirbute
                    var selecetd_taxonomy = taxonomy.toString();;


                    var selected_term = terms.toString();
                    var selected_term_speach = '\'' + selected_term.split(',').join('\',\'') + '\'';
                    console.log(selecetd_taxonomy);
                    console.log(selected_term_speach);

            // After user click on tag, fade out list of posts
            $('.products').fadeOut();
                    $(".loading").fadeIn();

            data = {
                action: 'filter_posts', // function to execute
                afp_nonce: afp_vars.afp_nonce, // wp_nonce
                taxonomy: selecetd_taxonomy, // selected tag
                            term: selected_term_speach,
                };

            $.post( afp_vars.afp_ajax_url, data, function(response) {
                        $(".loading").fadeOut();
                if( response ) {
                    // Display posts on page
                    $('.products').html( response );
                    // Restore div visibility
                    $('.products').fadeIn();

                };
            });
        });
    });

PHP获取帖子

// Script for getting posts
function ajax_filter_get_posts( $taxonomy, $term ) {
ob_start();
global  $woocommerce, $product;

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

  $taxonomy = $_POST['taxonomy'];
  $term = $_POST['term'];

  $term = str_replace("\\", '', $term);

  // WP Query
  $args = array(
    'post_type' => 'product',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
      );

  if ($term == "''") {
}
  else {
    $args = array(
      'tax_query' => array(
      array(
          'taxonomy' => $taxonomy,
          'terms' => array($term),
          'field' => 'slug',
          'operator' => 'IN'
      ),
  )
      );
  }

?>
<h1> <?php echo $term ?> </h1>
<?php
  $query = new WP_Query( $args );

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

<li <?php wc_product_class(); ?>>
<?php echo do_shortcode('[product_shortcode]'); ?>
</li>


<?php

 ?>

  <?php endwhile; ?>
  <?php else: ?>
    <h2>No posts found</h2>
  <?php endif;

  die();
  return ob_get_clean();
}

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

不好意思,代码混乱,只是想让它正常工作,然后再开始整理它。有关如何更好地解决此问题的任何建议,请告诉我。

感谢并感谢您的帮助!

UPDATE -----

试图添加简码回调,但这不起作用或我输入的代码错误

add_action( 'init', function() {
  ps_register_shortcode_ajax( 'ajax_filter_get_posts', 'ajax_filter_get_posts' ); 
} );

function ps_register_shortcode_ajax( $callable, $action ) {

  if ( empty( $_POST['action'] ) || $_POST['action'] != $action )
    return;

  call_user_func( $callable );
}

1 个答案:

答案 0 :(得分:0)

WordPress Ajax调用无法访问整个WordPress环境,这就是为什么您的短代码无法正常工作的原因。与其直接调用短代码,不如调用其回调。有关更多详细信息,请参见https://wordpress.stackexchange.com/questions/53309/why-might-a-plugins-do-shortcode-not-work-in-an-ajax-request