Shortcodes and JavaScript Enablement

I had a problem when the short code was only echoed and not executed, i.e. Here is what I actually see on my webpage:

[ajax_filter_posts per_page = "10"]

Here is my function.php file http://termbin.com/v6v5

//enqueue and localizing the Javascript. function assets() { wp_enqueue_script('ajax_filter_post_mdu', get_template_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], null, true); wp_localize_script( 'ajax_filter_post_mdu', 'bobz', array( 'nonce' => wp_create_nonce( 'bobz' ), 'ajax_url' => admin_url( 'admin-ajax.php' ) )); } add_action('wp_enqueue_scripts', 'assets', 100); 

This is what I call a shortcode in my personal category-template.php http://termbin.com/8r3x

 <?php echo do_shortcode('[ajax_filter_posts per_page="10"]'); ?> 

From what I understand, I am doing something wrong, maybe around the queue and / or localization, but I do not understand where the error is. In addition, javascript loads correctly, as the browser does not complain about a file that was not found.

Also in my template category.php file I call the function directly like this, for example:

 <?php $a = array('post_tag', false, false); $pub_tag = vb_filter_posts_sc( $a ); echo $pub_tag; ?> 

It works correctly ...

Ive forked 2016 Wordpress inline theme and hack here, do I have a conflict somewhere?

I searched as much as I could, but could not make it out.

+5
source share
1 answer

You have not published the code where your short code is indicated.

It would look like add_shortcode('ajax_filter_post', ...) . You did not indicate if you provide a short code or if in some plugin you are responsible.

You can see which shortcodes are defined as follows:

 global $shortcode_tags; print_r($shortcode_tags); 

This will (should) give you an array with all the codes specified. If ajax_filter_post does not appear on this list, your ajax_filter_post is undefined.

Depending on where this content is located, you may have a problem with the order of the filters. That is, no matter how it expands, this short code can work after wp_enqueue_scripts already running. If this happens, your JS code will never hit the browser. A workaround for this would be to put JS on every page and use it only when something appears with your shortcode. For example, a short code might output this HTML:

 <div class="my-shortcode-target"></div> 

And jQuery is something like this:

 jQuery(() => { (($) => { $('.my-shortcode-target').each(() => { var $target = $(this); $.ajax({'url': bobz.ajax_url, 'data': { 'nonce': bobz.nonce } }).done((data) => { // Here where you can do stuff using what was returned from your AJAX call. target.append($('<span>').text(data.answer)); }); }); })(jQuery); }); 

Your short code seems to be filtering something, so you will replace the DOM manipulation where you decide what to show and what not to show.

0
source

Source: https://habr.com/ru/post/1261680/


All Articles