Add Snippet To Project
Using stylesheets can significantly improve the layout and aesthetic of your webpages. However, loading unnecessary stylesheets can affect your website’s speed and performance. In WordPress, it’s possible to load a stylesheet only when a particular component, such as a gallery, is being used. This article will take you through a step-by-step process on how you can optimize your WordPress website by loading a stylesheet only when a gallery is in use.
function wpturbo_enqueue_gallery_stylesheet() {
global $post;
if ( has_shortcode( $post->post_content, 'gallery' ) ) {
wp_enqueue_style( 'wpturbo-gallery-styles', get_template_directory_uri() . '/css/gallery-styles.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpturbo_enqueue_gallery_stylesheet' );
The code snippet starts off by defining a function named wpturbo_enqueue_gallery_stylesheet()
. The purpose of this function is to load a specific CSS stylesheet when a gallery shortcode is used within a post.
The use of the global $post
line is to give us access to the $post object, which houses data for the currently queried post or page in WordPress.
global $post;
The if
statement uses the WordPress function has_shortcode()
to check if the gallery shortcode is present within the current post’s content. The function needs two parameters, the post content for which to check and the shortcode to look for. These are $post->post_content
and 'gallery'
, respectively.
if ( has_shortcode( $post->post_content, 'gallery' ) ) {
Only if the gallery shortcode is present will the function wp_enqueue_style()
be executed. This function is used to include a CSS file in WordPress. Here it is enqueuing a CSS file located in ‘yourtheme/css/gallery-styles.css’. Remember to replace ‘yourtheme’ with the actual directory name of your theme.
wp_enqueue_style( 'wpturbo-gallery-styles', get_template_directory_uri() . '/css/gallery-styles.css' );
The add_action
function is used to hook our new function wpturbo_enqueue_gallery_stylesheet()
into WordPress at the wp_enqueue_scripts
action hook. This tells WordPress that we want our function to be called when scripts and styles are being enqueued. This action hook is the proper place to enqueue styles and scripts to ensure correct order and avoid conflicts.
add_action( 'wp_enqueue_scripts', 'wpturbo_enqueue_gallery_stylesheet' );
What this function does as a whole is to conditionally load a particular stylesheet only when a gallery is included in a WordPress post or page. This has a performance advantage because the gallery-specific stylesheet will be loaded only on the pages required, not across the whole site.