is_page() function in WordPress

If you’re working with WordPress themes or plugins, you’ve likely encountered is_page(). This powerful conditional tag lets you target specific pages with precision—whether for displaying custom content or managing SEO tweaks.

In this tutorial, we break down what is_page() is, how it works, and provide practical examples to help you integrate it smoothly into your project. Let’s dive right in.

What is is_page()?

is_page() is a WordPress conditional tag that checks if the current page being displayed is a WordPress Page (and not a post, archive, or any other type of content). It returns true if the query is for a page, and false otherwise.

The basic syntax looks like this:

if ( is_page() ) {
  // Your code here
}

How Does It Work?

This conditional function works for any page in your WordPress site. It can accept various parameters to match by page ID, slug, or title, giving you flexibility when targeting specific pages.

Practical Examples

Basic Check for Any Page

if ( is_page() ) {
  echo '<p>This is a page.</p>';
}

This snippet simply outputs a message if the current view is a page.

Check by Page ID

if ( is_page( 42 ) ) {
  // Code executes only for the page with ID 42
}

Check by Page Slug

if ( is_page( 'about-us' ) ) {
  // Code executes only for the page with slug "about-us"
}

Check by Page Title

if ( is_page( 'Contact' ) ) {
  // Code executes only for the page titled "Contact"
}

Using page titles can be less reliable if the title ever changes. It’s often better to use the ID or slug for consistency.

Multiple Page Targets

if ( is_page( array( 42, 'about-us', 'Contact' ) ) ) {
  // This will match if any of the IDs, slugs, or titles in the array match
}

Key Considerations

  • is_page() targets WordPress Pages only. It does not detect posts or other custom post types.
  • When developing, ensure you’re within the context of the main query to avoid unexpected behaviors.

SEO Use Case Example

Suppose you want to apply custom meta tags on your ‘About Us’ page to boost your SEO:

if ( is_page( 'about-us' ) ) {
  echo '<meta name="description" content="Learn more about our company and values." />';
}

This snippet adds a custom meta description only on the specified page.

Developer Tip

For optimal performance, use these conditionals within hooks like wp to ensure the query is fully set up:

add_action( 'wp', function() {
  if ( is_page() ) {
    // Place your code here
  }
});

Reference

For additional details, check out the official documentation on is_page():
is_page() – WordPress Developer Resources

Final Thoughts

is_page() is an essential tool for WordPress developers. Whether you’re customizing templates, managing content display, or refining your SEO strategy, mastering this conditional tag is a must.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *