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

Avatar

By Shea Bunge

updated 3 days 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.

Did this answer your question?