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

问题描述 投票:1回答:2

我正在functions.php WordPress中创建一个shortcode,以便我可以将JavaScript文件添加为shortcode以便在我的网站页面上对其进行调用。

javascript php wordpress shortcode wordpress-shortcode
2个回答
2
投票

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

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/


1
投票

我不建议这样添加。简码实际上是在页面其余部分呈现之后不久添加的。相反,我会通过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');
© www.soinside.com 2019 - 2024. All rights reserved.