Manytime i want to add script inside tag in wordpress.

Lets say i want to show charts.js in author php ,category php file but not in other file like in index.php single.php

What i do now is check the if is author page or category page and check if the current page

But that makes header very messy . Many lines of code just for checking and adding script?

Is there any possibility that i add something to author.php and it will display from wp_head hook?

When i add code like this in author.php it is not working

add_action('wp_enqueue_scripts', function(){
    wp_register_script( 'jquery', 'SITE_URL/charts.js');

yes it may be due to i am not running from functions.php but is there any other way ?


Hardcoding scripts in header.php is a very very bad practice. You should always use proper hooks to enqueue scripts and styles in header. This code will give you some idea on how to do this in proper way.

function wpse206834_enqueue_scripts() {
    if ( is_author() // Checks if Author Archive is Being Displayed
    || is_category() // Checks if Category Archive is being displayed
        wp_register_script( 'charts', 'SITE_URL/charts.js', array('jquery') );
        wp_enqueue_script( 'charts' );
add_action( 'wp_enqueue_scripts', 'wpse206834_enqueue_scripts' );    

Here are some good reads to get started:

  • hai. But where do i add your code in function.php ? Suppose i want to show charts.js in author page,mysscript.js in index page, ajax_user.js in single.php , mycustom.js in category.php ?? So i should do all the checking in functions.php?? – stlawrance Oct 28 '15 at 11:35
  • @stlawrance exactly that. You have to check for conditions if you want to enqueue scripts in specific pages. The code goes in your functions.php, any where in that file. – Abhik Oct 28 '15 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.