我正在functions.php
WordPress中创建一个短functions.php
,以便我可以在短代码中添加我的javaScript文件以在我的网站页面上调用它。
You can add short code and output the content of the short parameter like this
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' );
You can then use it like this in your posts where you want to show the output path:
[jsshortcode path="https://example.com/complete-path.js"]
This can work on both page and post content as explained here: https://nabtron.com/how-to-add-javascript-file-in-wordpress-shortcode/
I wouldn't recommend adding it this way first you have to register the script using 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');
After that you have call it in your shortcode using 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');
This is the right way to that
I wouldn't advise adding it this way. The shortcode is actually added shortly after the rest of the page is rendered. Instead I would add the javascript via wp_enqueue_scripts on the specific page you want to add it to. Add this to your function:
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.