duanchuli5647 2018-07-12 08:27
浏览 67

WordPress AJAX函数中的Echo短代码返回

I have searched all over here and the web but cant seem to get this to work - hopefully you all can help.

I am trying to setup product filters for WooCommerce on the category page (like filter products depending on color etc)

I have the ajax working but I have a shortcode that I want to display for each product and this doesnt work - any ideas how to get it to show?

Code below:

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 TO GET POSTS

// 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');

Excuse the messyness of the code, just trying to get it to work before I can start to neaten it up. Any advice on how to approach this in a better way please let me know.

Thanks and appreciate the help!

UPDATE-----

Tried to add the shortcode callback, but this doesnt work or I have the wrong code

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条回答 默认 最新

  • dqh1984 2018-07-12 08:37
    关注

    WordPress Ajax calls don't have the access to whole WordPress environment and that's why your shortcode not working. Instead of calling the shortcode directly, call its callback. Refer https://wordpress.stackexchange.com/questions/53309/why-might-a-plugins-do-shortcode-not-work-in-an-ajax-request for more details.

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line