短代码和 javascript 包含

Shortcodes and javascript inclusion

我遇到了一个问题,短代码只被回显而不被执行,即这是我在我的网页上实际看到的:

[ajax_filter_posts per_page="10"]

这是我的 function.php 文件 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);

这是我在个人类别中调用简码的方式-template.php http://termbin.com/8r3x

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

据我所知,我做错了什么,可能是在入队和/或本地化方面,但我不明白哪里出了问题。此外,javascript 正确加载,因为浏览器不会抱怨找不到文件。

同样在我的模板 category.php 文件中,我直接调用函数,例如:

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

它确实工作正常......

我从这里 fork 了 2016 Wordpress 内置主题和 hack,我在某处有冲突吗?

我已经尽可能多地搜索了,但无法整理出来。

您没有 post 定义简码的代码。

它看起来像 add_shortcode('ajax_filter_post', ...)。您没有说明您是在提供简码还是在您不负责的某个插件中。

您可以看到定义了哪些短代码:

global $shortcode_tags;
print_r($shortcode_tags);

这将(应该)给你一个包含所有定义的简码的数组。如果 ajax_filter_post 没有出现在该列表中,则您的短代码未定义。

根据此内容所在的位置,您可能对过滤器的顺序有疑问。也就是说,任何扩展此简码的内容都可能在 wp_enqueue_scripts 之后 运行 已经 运行。如果发生这种情况,您的 JS 代码将永远无法进入浏览器。解决方法是在每个页面上将 JS 排入队列,并且仅在短代码出现时才使用它。例如,简码可以输出这个 HTML:

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

和 jQuery 是这样的:

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

您的简码似乎在过滤某些东西,因此您可以用决定显示什么和不显示什么的东西替换那里的 DOM 操作。