繁体   English   中英

如何在 WordPress 的短代码中添加两个 javascript 文件?

[英]How to add two javascript files in a shortcode in WordPress?

我正在functions.php WordPress中创建一个functions.php ,以便我可以在短代码中添加我的javaScript文件以在我的网站页面上调用它。

您可以像这样添加短代码并输出短参数的内容

function stackoverflow_60004550( $atts ) {
    $atts = shortcode_atts(
        array(
            'path' => 'default-path.js',
        ), $atts, 'path' );

    return '<script type="text/javascript" src="'.$atts['path'].'"></script>';
}
add_shortcode( 'jsshortcode', 'stackoverflow_60004550' );

然后,您可以在要显示输出路径的帖子中像这样使用它:

[jsshortcode path="https://example.com/complete-path.js"]

这可以适用于页面和帖子内容,如下所述: https : //nabtron.com/how-to-add-javascript-file-in-wordpress-shortcode/

我不建议首先以这种方式添加它,您必须使用 wp_register_script() 注册脚本

function your_shortcode_wp_enqueue_scripts_fun() {

    wp_register_script( 'cus-js1',get_stylesheet_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.0', true );

}
add_action( 'wp_enqueue_scripts', 'your_shortcode_wp_enqueue_scripts_fun');

之后,您使用 wp_enqueue_script() 在短代码中调用它

function get_specific_product_shortcode_function($atts){

    extract( shortcode_atts(
        array(
           'id' => '',
            ), $atts )
    );

    ob_start();


    ...
    wp_enqueue_script('cus-js1');
    ...




return ob_get_clean();
}
add_shortcode('get_specific_product_shortcode', 'get_specific_product_shortcode_function');

这是正确的方法

我不建议以这种方式添加它。 短代码实际上是在页面的其余部分呈现后不久添加的。 相反,我会通过 wp_enqueue_scripts 在您想要将其添加到的特定页面上添加 javascript。 将此添加到您的函数中:

function load_scripts() {

   global $post;

   if( is_page() || is_single() )
   {
       switch($post->post_name) // post_name is the post slug
       {
           case 'some-page-slug-here':
               wp_enqueue_script('about', get_template_directory_uri() . '/js/some-js-file.js', array('jquery'), '', true);
               break;

       }
   } 
}

add_action('wp_enqueue_scripts', 'load_scripts');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM