I'm looking for a solution to conditionally load scripts and styles on specific Wordpress pages. I've searched for solutions, but have hit a dead end. I haven't been able to use php selectors, such as is_page(), in the functions.php file to do this. Here is an example of my past attempt:
function blog_style() {
if ( is_page('blog') ) {
wp_enqueue_style( 'blog' );
}
}
add_action( 'wp_print_styles', 'blog_style' );
I have a feeling this is because the functions.php file is loaded before the page has been identified. Any advice is helpful. I have a basic understanding of php and Wordpress codex. Thanks!
I understand your confusion in this matter and must confess that WordPress sometimes has strange ways to handle things.
First of all; you should enqueue scripts and styles in the wp_enqueue_scripts hook:
add_action('wp_enqueue_scripts', 'themeslug_styles');
function themeslug_styles() {
wp_enqueue_style(...);
}
Or in shorthand-/anonymous-function-format, if you prefer:
add_action('wp_enqueue_scripts', function () {
wp_enqueue_style(...);
});
The basic idea of your is_page('blog') in an if-statement is correct. But also check out this detailed info about conditional tags - maybe there are better ways to target the blog-page of your website (see "The Blog Page" on the linked resource).
You must use the if-statement inside your function, because it is only at the point of wp_enqueue_scripts, where the function is run, that WordPress has information about the actual content ready.
add_action('wp_enqueue_scripts', function () {
if (is_home()) {
wp_enqueue_style('themeslug-stylename', URL-to-your-style);
wp_enqueue_script('themeslug-scriptname', URL-to-your-script);
}
});
Addition: You are right, the functions.php file is mainly used to set everything up and connect functions as actions to WordPress hooks. Therefore, the code is executed quite early in the WordPress execution flow to give you access to as many hooks as possible. The downside is, as you experienced, that many things are not directly accessable at this point.
I think you are using the wrong hook here. Try
add_action( 'wp_enqueue_scripts', 'blog_style' );
You can check this function. I had used this function to dynamically load scripts on different post types and pages. I used the screen_id to specify the current page.
Related
I want to remove most css and scripts added to my Wordpress by plugins and maybe core Wordpress. How can I trace which function adds which line in my page header?
Tried to run search for the lines I want to remove but unsuccessfully. I know already that the code is done through wp_header hook but it does not help finding exact function.
If you know which plugins add the code you can go through plugin files in wp-content/plugins/plugin-name and find following functions.
wp_enqueue_script()
wp_enqueue_style()
Usually it will be together and wrapped in another function which will be called by action:
add_action( 'wp_enqueue_scripts', 'name_of_function' );
For not loading the scripts just uncomment add_action line.
But please be aware, that those scripts are usually vital for correct function of plugin so you will have to serve them from somewhere else.
Also when disabling wp_enqueue be sure you are not disabling admin scripts which would be loaded by action
add_action( 'admin_enqueue_scripts', 'name_of_function' );
To be sure always check parametres of wp_enqueue function where script name should match the script you had previously seen in head section of your site.
Every update of plugin will override the files and therefore enable scripts again
Hope this helps.
In pure theory my question is whether it is possible to make one php function run twice taking a different variable each time and returning it as a result.
In practice, I'm tinkering with a child theme for WordPress (and learning some PHP basics). The original theme, twentysixteen, has a function to construct a link to Google fonts using several parameters and output the final URL, which is then taken by some other function and inserted in to the head template with added HTML markup - link, href, rel, type.
In my child theme I had to replace one of the default fonts completely, so instead of reconstructing the function, I simply minimized it to just contain and output the final font URL like so:
if ( ! function_exists( 'twentysixteen_fonts_url' ) ) :
function twentysixteen_fonts_url() {
$fonts_url = 'https://fonts.googleapis.com/css?family=Merriweather:400,700,900,400italic,700italic,900italic|Inconsolata&subset=latin,latin-ext,cyrillic,greek';
return $fonts_url;
}
endif;
What I'm trying to do now is get another URL (https://code.cdn.mozilla.net/fonts/fira.css) into this function to load a third font from Mozilla's CDN alongside the Google ones.
Can't put it into a separate function with a different name, because its output does not get picked up by the head template. Using an array puts both urls into one link href.
Can somebody please point me in the right direction?
Thank you.
Twentysixtee juste use one font, and the URL is generated with twentysixteen_fonts_url ()
If you look into Twentysixtee's function.php, twentysixteen_fonts_url () is use only 2 times. It's use to include font url in editor (line 144) and in front end (line 233).
Add an other font
If you want to add an other font you need to add it in your child theme.
You could do it by adding the following code in your function.php
function my_child_theme_font_url()
{
$fonts_url = 'https://code.cdn.mozilla.net/fonts/fira.css';
return $fonts_url;
}
function my_child_theme_enqueue_scripts()
{
wp_enqueue_style( 'my_child_font', my_child_theme_font_url(), array(), null );
}
add_action( 'wp_enqueue_scripts', 'my_child_theme_enqueue_scripts' );
As suggested by #MonkeyZeus the simplest way to achieve having another webfont enqueued in such cases is leaving the first function as it is and adding a different one right after it to enqueue the needed file like so:
add_action( 'wp_enqueue_scripts', 'register_custom_plugin_styles' );
function register_custom_plugin_styles() {
wp_register_style( 'fira', 'https://code.cdn.mozilla.net/fonts/fira.css' );
wp_enqueue_style( 'fira' );
}
As for the theoretical part of my question, I understand that somehow forcing a function to run a second time and produce a different output would not force the other function using this output to run a second time as well, producing a different result. For this to work, the calling function has to be modified, not the emitting one.
Thank you #MonkeyZeus and #Jordane-CURE for your help.
With Wordpress you have good/bad plugins, some being much more economical than others. By economical I mean that they only call the CSS and JavaScript required for the function when the page is loaded where that function is enabled. Others don't discriminate and call the code on all pages. This can have a negative effect on page load speed/performance.
I have some plugins that are heavy in CSS and are laden with reems of jQuery/Javascript files - I only want them to be enabled on particular pages (not home). In hand I have the page ID and alias. Looking in the plugin folder I also see the main php file that includes all the JS / CSS. Within that file I tried something like is_page() but it seems to have no impact as if is_page has not yet been set.
<?php if ( is_page( '3486' ) ) { exit; } ?>
exit on a line by itself kills the page indicating that the script is being called.
The question, "How and where do you place an if statement that will prevent the plugin CSS/JavaScript from being called on all pages but a particular one (or perhaps an array of pages)?
I could name the plugin but the question is really more generic to any plugin.
You can use wp_deregister_script, this will remove unwanted JS,CSS from specific pages.
add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );
function my_deregister_javascript()
{
if ( is_page('YOUR PAGE NAME') )
{
wp_deregister_script( 'WORDPRESS JS file NAME' );
}
}
Refer : https://codex.wordpress.org/Function_Reference/wp_deregister_script
Massive hat tip to the community, here, you folks are my go-to most days!
I think my topic says it all, really, with relation to jQuery in WordPress - I've been thinking a lot lately that placing jQuery commands in functions.php would make the effects happen sooner rather than in placing them in footer.php which would be a good thing, I think. Can anyone see any flaws with this approach?
-Jc
This question is primarily opinion based. However, the proper way to include JavaScript files in WordPress is to properly "enqueue" them using the wp_enqueue_script() function, from the 'wp_enqueue_scripts' action hook.
To speed up page load, many people prefer to enqueue scripts in the footer, using the 4th and final parameter of wp_enqueue_script().
Doing the following will ensure that your script is properly enqueued, that it's dependencies have been satisfied, and that it's in the footer (added via wp_footer()):
/**
* Proper way to enqueue a script with a jQuery dependency, in the footer
*/
function theme_name_scripts() {
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
For more reasons about why you should use this function instead of hard-coding them into the footer of your theme, check out this post on WPSE.
wp_enqueue_script() as I read about so far and went through the source code instantiates new wp_scripts object 'representing' the script.
My question is how does wordpress know when to load the the script source when needed ?
For example, on index I need bootstrap and jquery, I enqueue bootstrap with jquery dependency in functions.php. How does wordpress know to automatically load the bootstrap on the first page ? What I want to understand is the logic behind it.
I have to create a new plugin and I need some scripts for a slideshow, what I want is to create a quality plugin, optimized using wp_enqueue_scripts, but I don't really understand the concept in-depth so I can use it properly (to load the scripts only when the plugin is activated)
You can treat wp_enqueue_scripts as a kind of action_hook. I.e. when it is time to create pages, it will include the file. You can also make it dependant on another file being loaded, so if jQuery is needed, you can stipulate this in the function and it will load after jQuery. This maintains seperation of your code.
If you want to optimize the code, you can make the function dependant on the page you are loading.
Forexample:
function prepare_scripts() {
if(is_front_page() )
wp_enqueue_scripts('myscript', 'path to script', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'prepare_scripts' );
As #knoblik suggests, you can set the priority for the add_action() if needed. This will probably enqueue the script in the order of the priority.