Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
hi so I used a great tutorial off of http://scribu.net/wordpress/optimal-script-loading.html and I am having trouble loading the scripts when a shortcode called lightbox is used here is my code. I am at the page when it is called wanted to check with someone to see if it is properly written.
add_shortcode('lightbox', 'lightbox_handler');
function lightbox_handler($atts) {
$base = get_stylesheet_directory_uri();
wp_enqueue_script('jquery-mousewheel', $base . '/js/jquery.mousewheel-3.0.6.pack.js', array('jquery'), null, true);
wp_enqueue_script('jquery-fancybox', $base . '/js/jquery.fancybox.pack.js', array('jquery'), '1.0', true);
wp_enqueue_script('jquery-fancybox-buttons', $base . '/js/jquery.fancybox-buttons.js', array('jquery-fancybox'), '1.0', true);
wp_enqueue_script('jquery-fancybox-media', $base . '/js/jquery.fancybox-media.js', array('jquery-fancybox'), '1.0', true);
wp_enqueue_script('jquery-fancybox-thumbs', $base . '/js/jquery.fancybox-thumbs.js', array('jquery-fancybox'), '1.0', true);
wp_enqueue_style('jquery-fancybox', $base . '/css/jquery.fancybox.css', false, '1.0', true);
wp_enqueue_style('jquery-fancybox-buttons', $base . '/css/jquery.fancybox-buttons.css', array('jquery-fancybox'), '1.0', true);
wp_enqueue_style('jquery-fancybox-thumbs', $base . '/css/jquery.fancybox-thumbs.css', array('jquery-fancybox'), '1.0', true);
}
function lightbox( $atts, $content = null ) {
$defaults = apply_filters( 'toggle_shortcode_args',
array(
'title' => '',
'id' => '',
'type' => '',
'rel' => '',
'url' => '',
)
);
extract( shortcode_atts( $defaults, $atts ) );
$html .= '<a class="'.$id.'" rel="'.$rel.'" data-fancybox-group="gallery" href="'.$url.'" title="'.$title.'"><img src="'.$url.'" alt="" />';
$html .= '</a>';
return $html;
}
First point: that tutorial is based on an old version of WordPress; don't follow that one. Now:
The handle you specify in wp_register_script() must be unique. You are reusing the same handle (fancybox) for all scripts; this won't work. Give each one a different handle, e.g. 'jquery-mousewheel', 'jquery-fancybox', 'jquery-fancybox-buttons', etc. Try to stick to established naming habits that WordPress uses, see wp_enqueue_script() default scripts for examples.
If you want your scripts to be output in the footer, just say so in wp_register_script() (which you have); there is no need to use the wp_footer action. Styles should be output in the header anyway, not the footer.
You can tell WordPress to register and enqueue scripts and stylesheets for output with one call each: wp_enqueue_script() and wp_enqueue_style(). There is no need to register, then enqueue, in your simple case.
The best action hook for registering and enqueueing scripts is 'wp_enqueue_scripts'. Try to only use that one except in special circumstances.
Bonus points: where a script name already includes the version number, you can suppress the extra '?ver=nnn' that WordPress tacks on by passing null as the version string.
And finally, get_stylesheet_directory_uri() doesn't take any arguments.
NB: this gets your script working. One thing your linked tutorial does differently is only output your scripts conditionally, but there are better tutorials on that subject linked at the bottom of the wp_enqueue_scripts() manual page. First, get your site working!
class fancy{
static function init() {
add_shortcode('lightbox', array(__CLASS__, 'handle_shortcode'));
add_action('wp_enqueue_scripts', array(__CLASS__, 'wp_enqueue_scripts'));
}
static function handle_shortcode($atts) {
self::$add_script = true;
// actual shortcode handling here
}
static function wp_enqueue_scripts() {
$base = get_stylesheet_directory_uri();
wp_enqueue_script('jquery-mousewheel', $base . '/js/jquery.mousewheel-3.0.6.pack.js', array('jquery'), null, true);
wp_enqueue_script('jquery-fancybox', $base . '/js/jquery.fancybox.pack.js', array('jquery'), '1.0', true);
wp_enqueue_script('jquery-fancybox-buttons', $base . '/js/jquery.fancybox-buttons.js', array('jquery-fancybox'), '1.0', true);
wp_enqueue_script('jquery-fancybox-media', $base . '/js/jquery.fancybox-media.js', array('jquery-fancybox'), '1.0', true);
wp_enqueue_script('jquery-fancybox-thumbs', $base . '/js/jquery.fancybox-thumbs.js', array('jquery-fancybox'), '1.0', true);
wp_enqueue_style('jquery-fancybox', $base . '/css/jquery.fancybox.css', false, '1.0', true);
wp_enqueue_style('jquery-fancybox-buttons', $base . '/css/jquery.fancybox-buttons.css', array('jquery-fancybox'), '1.0', true);
wp_enqueue_style('jquery-fancybox-thumbs', $base . '/css/jquery.fancybox-thumbs.css', array('jquery-fancybox'), '1.0', true);
}
}
fancy::init();
PS: I suspect that jquery.fancybox.pack.js is a packed (i.e. minified) version of jquery.fancybox.js, so use that one as 'jquery-fancybox' if it is; you don't need both.
The first argument to wp_register_script needs to be unique for each script (see the codex), so you might need names like "fancybox.mousewheel", "fancybox", "fancybox.buttons" etc to differentiate. I'd check, but I suspect you only need one of fancybox.js and fancybox.pack.js - I'd think the pack file is a minified version of fancybox.js
But what version of WordPress are you using? The link at the top of the tutorial you mentioned shows a cleaner way to do it in WordPress 3.3+, removing the need for the class.
Related
I need to add sync or defer attribute in Stylesheets CSS file which are included by using wp_enqueue_style.
My Code is below.
function my_scripts() {
wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.css', array(), '4.4.2');
wp_enqueue_style('my-style', get_stylesheet_uri());
wp_enqueue_style('about-page', get_template_directory_uri() . '/css/about-styles.css', array(), '4.4.3');
wp_enqueue_script('bootstrap-min', get_template_directory_uri() . '/js/bootstrap.min.js', array(), '20151112', true);
wp_enqueue_script('jquery-scrollto', get_template_directory_uri() . '/js/jquery-scrollto.js', array(), '20112', true);
wp_enqueue_style('details-pages', get_template_directory_uri() . '/css/details-pages.css', array(), '4.4.3');
wp_enqueue_style('owl-carousel-css', get_template_directory_uri() . '/css/owl/owl.carousel.css', array(), '4.4.2');
wp_enqueue_script('owl-carousel-js', get_template_directory_uri() . '/css/owl/owl.carousel.min.js', array(), '202', true);
wp_enqueue_script('scripts-js', get_template_directory_uri() . '/js/scripts.js', array(), '20151112', true);
}
add_action('wp_enqueue_scripts', 'my_scripts');
Now I want to add sync or defer attribute in different CSS Style sheets. So please help me, how to add sync or defer attribute. I want to add attributes in just CSS files not in JavaScript files.
Any help will be appreciated.
Thanks.
Try this code
function add_custom_attr( $tag, $handle, $src ) {
$scriptArr = array('bootstrap','my-style','about-page','bootstrap-min','jquery-scrollto','details-pages','owl-carousel-css','owl-carousel-js','scripts-js');
if (in_array($handle, $scriptArr)) {
$tag = str_replace( 'src=', 'sync="false" src=', $tag );
}
return $tag;
}
add_filter( 'script_loader_tag', 'add_custom_attr', 10, 3 );
Another solution using a different filter, which can be used to target a specific script handle:
function frontend_scripts(){
wp_enqueue_script( 'my-unique-script-handle', 'path/to/my/script.js' );
}
add_action( 'wp_enqueue_scripts', 'frontend_script' );
function make_script_async( $tag, $handle, $src ){
if ( 'my-unique-script-handle' != $handle ) {
return $tag;
}
return str_replace( '<script', '<script async', $tag );
}
add_filter( 'script_loader_tag', 'make_script_async', 10, 3 );
I hope this will help you to solve your problems.
Thank you
This is the script I use to control style and script attributes:
enqueue script
This allows you to selectively add Defer, Async, and Lazy Load to stylesheets and scripts. A perfect way to make Google PageSpeed happy LOL.
Applying proper minification, caching and lazy loading of images, along with managing the styles and scripts with this script, changed our PageSpeed score from 60 mobile / 88 Desktop to 74 Mobile and 96 desktop.
I added custom javascript to a wordpress theme through the wp_enqueue_script()
function.
I placed my file in theme-folder/js/my-javascript.js
But it would not be found by wordpress! I would see the script tag in the html source inserted by wordpress, but clicking on it would take me to a "not found page". I looked around everywhere to see if this was some caching issue. Turned off caching, still nothing.
Finally, I ended up placing my-javascript.js file in the root of theme-folder, instead of 'js' folder. And now my js file was being found and loading.
But now a new problem I don't understand.. I would edit my file and the changes wouldn't reflect! I would have to change the file name of my js file everytime I made a change, renaming the file in my enqueue script function as well...I just wanted to get this task done.
So why does this happen? The site is hosted on dreamhost, and I suspect they used a one-click installer. Does dreamhost do some sort of caching on its own? and that's why?
Am I dumb? or does wordpress somehow know that I hate it?
Edit:
This is how I'm loading the script and how I left it working, but why won't my script refresh when I make changes and why doesn't it work when I place it in theme's 'js' folder?
/* Add floater script */
function add_floater_div_script(){
/* wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true); */
if ( is_page(1208) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array('jquery'), '', true);
}
}
add_action( 'wp_enqueue_scripts', 'add_floater_div_script' );
Edit: Changed code from "array ( " to "array(" because someone thought this was a problem. I did a quick check myself and PHP is ok with this space so this does not explain the weird wordpress behaviour I'm trying to solve.
Yeah, caching gets really annoying, Though hard reloading should solve the prob but we can't expect client to do it everytime. And WordPress has added a way to take care of that :)
wp_enqueue_script accepts 4th parameter as version number...
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
So just update version after each update...
For development, Just set it as time()... So that it is reloaded every single time and never cached...
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array('jquery'), time(), true);
Your code will look something like this...
/* Add floater script */
function add_floater_div_script(){
/* wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true); */
if ( is_page(1208) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array('jquery'), time(), true);
}
}
add_action( 'wp_enqueue_scripts', 'add_floater_div_script' );
BE SURE TO REMOVE time() FROM PRODUCTION VERSION.
Or your file will never be cached by browser... Just set the version of your theme after dev is complete, so that every new version gets JS updated.
Try by wrapping your enqueue action in a function that you'll call on after_setup_theme hook in your functions.php
<?php
add_action( 'after_setup_theme', 'yourtheme_theme_setup' );
if ( ! function_exists( 'yourtheme_theme_setup' ) ) {
function yourtheme_theme_setup() {
add_action( 'wp_enqueue_scripts', 'yourtheme_scripts' );
}
}
if ( ! function_exists( 'yourtheme_scripts' ) ) {
function yourtheme_scripts() {
if ( is_page( 1208 ) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array( 'jquery' ), '', true );
}
}
}
Also be sure you're on page with id of 1208 to see if the script is actually loaded (because of the conditional).
And do a hard refresh (Ctrl+Shift+R).
The most common issue I see is an error in how you're enqueueing the file. Can you post code in your functions.php file that's enqueuing the JS file? Always be sure to reference the codex and other developer materials as well: https://developer.wordpress.org/themes/basics/including-css-javascript/
For future reference, it should look something like this:
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/my-javascript.js');
Edit: After OP posted their code I saw they have a space after array which is causing an error, here is the correct code:
function add_floater_div_script() {
if ( is_page( 1208 ) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array( 'jquery' ), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'add_floater_div_script' );
add_action('wp_enqueue_scripts', 'load_scripts', 12);
function load_scripts() {
wp_enqueue_script('filename', get_template_directory_uri() . '/js/filename.js', array(), '1.0.0', true );
}
This is the proper way to import js in wordpress..
An really easy way to prevent caching of loaded resource files like Javascript-files is to add an random value after the filename that is to be included like so:
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js' . '?' . rand(), array('jquery'), '', true);
The PHP function
rand()
generates a random number and is appended to the file name after a '?' as query string. This forces reloading of the file every time the webpage is loaded.
Of course dismiss it for the production version.
Sometimes the issue could be simple somewhere a duplicated declaration of the name of the enqueue_script.
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/custom-floater-
8.js', array('jquery'), '', true);
...
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/custom-floater-
8.js', array('jquery'), '', true);
Don't use twice the same name 'custom-script' for example. The second will not be loaded.
I would like to load the most of my javascripts async to speed up the rendering. Sadly defer is breaking a lot of parts of my wordpress website and i need to exclude it from async load. One file of my theme is using the code
wp_register_script( 'tie-masonry', get_template_directory_uri() . '/js/isotope.js', array( 'jquery' ), false, true );
Pagespeed is needing the attribute data-pagespeed-no-defer
Like <script data-pagespeed-no-defer>...</script> to exclude it.
Is it possible to add this attribute to the wp_register_script, or do i need to exclude it from the php file and insert it by hand into the webpage?
Since 4.1.0 there is a filter hook 'script_loader_tag', which is perfect for this task.
add_filter( 'script_loader_tag', 'my_script_loader_tag', 10 ,2 );
function my_script_loader_tag( $tag, $handle ){
if ( $handle == 'tie-masonry' ) {
return str_replace( '<script', '<script data-pagespeed-no-defer', $tag );
}
return $tag;
}
I'm told it's very important to register and enqueue styles and scripts in WordPress even though it's a real pain in the behind. I had no problem with the scripts however when I try the styles, WordPress shows nothing in the code for stylesheets. I'd like to get in the habit of building my themes the correct way so I'd like to learn how this is done, but I can't understand why my css is not getting added to the code when the scripts are added. See code to functions file below:
<?php
function alpha_scripts(){
$script = get_template_directory_uri() . '/assets/scripts/';
wp_register_script('bootstrap-js', $script . 'bootstrap.min.js', array('jquery'),'', false);
//wp_enqueue_script('jquery');
wp_enqueue_script('bootstrap-js');
}
function alpha_styles(){
$style = get_template_directory_uri() . '/assets/styles/';
wp_register_style('bootstrap-css', $style . 'bootstrap.min.css','','', 'screen');
wp_register_style('alpha-css', $style . 'alpha.css','','', 'screen');
wp_enqueue_style('bootstrap-css');
wp_enqueue_style('alpha-css');
}
function alpha_menus() {
register_nav_menus(
array(
'main-menu' => __( 'Primary Menu' ),
'footer-menu' => __( 'Footer Menu' )
)
);
}
add_action('wp_enqueue_scripts', 'alpha_scripts');
add_action('wp_enqueue_styles', 'alpha_styles');
add_action('after_setup_theme', 'alpha_menus');
?>
What am I doing wrong here? I've tried using different references for the url, like get_template_directory_uri() and get_stylesheet_directory_uri() but as I suspected those two made no difference.
It looks like your registering and enqueueing correctly; but I suspect that the function itself is not being called because the action you are attaching it to isn't one defined by WordPress.
add_action('wp_enqueue_styles', 'alpha_styles');
should be:
add_action('wp_enqueue_scripts', 'alpha_styles');
wp_enqueue_scripts is the hook that should be used for both scripts and styles. (See: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts)
If your unsure about a hook in the future, you can check if it exists in the action reference here: https://codex.wordpress.org/Plugin_API/Action_Reference
I want to add 2 js files in my wordpress template function-dir.php.
how to add this js file is there any tag?
is it right function to use
wp_register_script( $handle, $src, $deps, $ver, $in_footer );
Thanks in advance....
You use wp_register_script to register a script with its handle in order to avoid duplicating code (if for instance you enqueue it in several places and need to update the filename). This is usually not needed, I usually use wp_enqueue_script(), which takes the same arguments and outputs it to the page.
I usually do this by creating a setup function with all my style and script enqueues and then hooking that function up to one of the pre-made hooks, like this:
function theme_enqueue() {
/**
* Scripts.
*/
wp_enqueue_script('scripts', get_template_directory_uri() . '/js/lib/scripts.pkgd.min.js', array('jquery'), THEME_VERSION);
wp_enqueue_script('myscript', get_template_directory_uri() . '/js/myscript.js', array('scripts'), THEME_VERSION, TRUE);
wp_enqueue_script('main-menu', get_template_directory_uri() . '/js/menu.js', array('jquery'), THEME_VERSION, TRUE);
}
add_action('wp_enqueue_scripts','theme_enqueue');
You can use following structure as plugin by using wp_enqueue_script;
function add_custom_js() {
wp_enqueue_script( 'script_name', get_template_directory_uri() . '/js/custom.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'add_custom_js' );
If you are developing plugin, you can add this action to your plugin. Or you can put this to functions.php
wp_register_script() function is used to register your script once and call anywhere, anytime. And wp_enqueue_script() is used to call it in your functions.php file
Method: 1
// First Register
function register_my_scripts(){
wp_register_script('handler_1', get_template_directory_uri() . "/js/script_one.js");
wp_register_script('handler_2', get_template_directory_uri() . "/js/script_two.js");
}
add_action('init', 'register_my_scripts');
Now use :
function wp24_load_script() {
// Check if you want to load for
// specific page
wp_enqueue_script('handler_1');
}
add_action("wp_enqueue_scirpts", "wp24_load_script");
Method: 2
Or you can directly load it with wp_enqueue_script() function:
function wp24_load_script() {
// Check if you want to load for
// specific page
wp_enqueue_script('handler_1', get_template_directory_uri() . "/js/script_one.js");
}
add_action("wp_enqueue_scirpts", "wp24_load_script");