How to add Java-Script properly in wordpress?

2019-09-19 08:48发布

问题:

I have created a theme from the static website in wordpress. I want to know the right way to add javascript & style-sheet into the wordpress theme`s file. I have header.php, footer.php and index.php files and other css & javascript files that are linked in header.php.

Thank you in Advance.

回答1:

Write following code into your theme's function.php file

/**
 * Proper way to enqueue scripts and styles
 */
function theme_name_scripts() {
    wp_enqueue_style( 'style-name', get_stylesheet_uri() );
    wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
}

add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );


回答2:

if you want to add js and css in theme/front end than you cac add js and css in your header.php like this.

<script src="<?php echo get_template_directory_uri(); ?>/js/your-js-file.js" type="text/javascript"></script>

For css

<link rel="stylesheet" type = "text/css" href="<?php echo get_stylesheet_directory_uri(); ?>/your-style-sheet.css"/>


回答3:

Loading the scripts correctly in WordPress is incredibly easy. Below is surely an example code which you would paste inside your plugins file or inside your theme’s functions.php file to properly Load scripts in WordPress.

function wpb_adding_scripts() {
   wp_register_script('my_js', plugins_url('jsscript.js', __FILE__),  array('jquery'),'1.1', true);
   wp_enqueue_script('my_js');
}
add_action('wp_enqueue_scripts', 'wpb_adding_scripts');  

for stylesheets

function wpb_adding_styles() {
   wp_register_script('my_stylesheet', plugins_url('mystyle.css', __FILE__));
   wp_enqueue_script('my_stylesheet');
}

add_action('wp_enqueue_scripts', 'wpb_adding_styles');