How can I make a snippet run on only a certain page?

Avatar

By Shea Bunge

updated 2 months ago

If you want to run a Code Snippet only on specific parts on your site, you can use conditional tags in a Function Snippet to only run the snippet based on certain conditions.

Here's an example for how you would ensure that CSS code is only run on pages with the ID 123, the URL slug some-page-slug, or the name Some Page Title:

add_action( 'wp_head', function () {

	if ( ! is_page( [ 123, 'some-page-slug', 'Some Page Title' ] ) ) {
		return;
	}

	?>
	<style>
		
	/* css code here */
		
	</style>
	<?php
} );

Of course, you should change out the condition in the if statement for whatever is relevant to your requirements.

You can find a list of conditional tags on the WordPress Theme Handbook.

If you are using a third-party plugin like WooCommerce, check that plugin's documentation for information on any additional conditional tags it might provide.

Did this answer your question?