is_page()无效

Ok, so I've been trying to figure this out for a while. I'm not exactly a PHP developer but can usually figure things out be looking at examples and Wordpress docs. However I'm struggling.

I'm trying to add a "simple" bit of code to a Wordpress template file, but it won't work. Basically I want to show content on certain pages and different content on other page. This is what I have so far:

<?php if(is_page('123')): ?>
    This text
<?php endif; ?>
<?php if(!is_page('123')): ?>
    That text
<?php endif; ?>

Any help would be so greatly appreciated.

you could try this:

global $post;

<?php if( $post->ID == 346) { ?>

      <!-- do your stuff here -->

<?php } ?>

or

<?php
if (is_page( 'Page Title' ) ):
  # Do your stuff
endif;
?>

You should provide more context. What does the provided code echo? Does it always say "That text" although you think that it should say "This text"?

Perhaps too obvious but is '123' the name of the post?

If you want to check for the Post with the ID you should try this:

<?php if(is_page(123)): ?>
    This text
<?php endif; ?>
<?php if(!is_page(123)): ?>
    That text
<?php endif; ?>

Using '123' makes it a string and searches for a post with a title or slug with that string.

Are you using this inside the WP Loop? If yes, note this:

Due to certain global variables being overwritten during The Loop, is_page() will not work. In order to call it after The Loop, you must call wp_reset_query() first.

(from: https://developer.wordpress.org/reference/functions/is_page/)

Also, you shouldn't put the page ID in quotes - it's an integer.

You shouldn't need to Logical "Not" Operator between the two statements. A simple if/else would suffice. That said:

The is_page() function will return false if the current query isn't set up for an existing page on the site.

Possible Conditions:

The global query has been modified/overwritten. If you're using query_posts() before this code - stop! Use WP_Query() along with wp_reset_postdata().

The record with the name '123' isn't actually a page. is_page specifically checks for the page post type. Consider the sister functions is_single() or is_singular().

In that same vein, are you looking for ID: 123? If so, remove the quotes. ID's should be passed as an integer: 123.

You're using this in "The Loop", where it can have unexpected interactions. You'll instead want to use another qualifying statement such as if( get_the_ID() == 123 ) ){ or if( $post->ID == 123 ){.

This code is hooked to an action hook too early such as plugins_loaded where the global query and post objects may not be set up yet.

Check to make sure whether any of those conditions apply, and then you can modify your code to be a bit more succinct:

if( is_page( 123 ) ){
    echo 'This is page ID 123';
} else {
    echo 'This is NOT page ID 123';
}

Or even further with the Ternary Operator

echo is_page( 123 ) ? 'This is Page ID 123' : 'This is Not page ID 123';