m (Link and typo fixes.) |
m (→is_tax) |
||
(14 intermediate revisions by 13 users not shown) | |||
Line 3: | Line 3: | ||
{{fr|Marqueurs_conditionnels}} |
{{fr|Marqueurs_conditionnels}} |
||
{{it|Tag condizionali}} |
{{it|Tag condizionali}} |
||
− | {{ja| |
+ | {{ja|Conditional_Tags}} |
{{tr|Kosul Etiketleri}} |
{{tr|Kosul Etiketleri}} |
||
{{pt-br|Tags condicionais}} |
{{pt-br|Tags condicionais}} |
||
Line 15: | Line 15: | ||
'''Warning: You can only use conditional query tags after the ''posts_selection'' [[Plugin API/Action Reference#Actions Run During a Typical Request|action hook]] in WordPress (the ''wp'' action hook is the first one through which you can use these conditionals). For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function.''' |
'''Warning: You can only use conditional query tags after the ''posts_selection'' [[Plugin API/Action Reference#Actions Run During a Typical Request|action hook]] in WordPress (the ''wp'' action hook is the first one through which you can use these conditionals). For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function.''' |
||
+ | |||
+ | '''However: if you have a reference to the <tt>query</tt> object (for example, from within the <tt>parse_query</tt> or <tt>pre_get_posts</tt> hooks), you can use the WP_Query conditional methods (eg: <code>$query->is_search()</code>)''' |
||
== The Conditions For ... == |
== The Conditions For ... == |
||
Line 45: | Line 47: | ||
// blog page |
// blog page |
||
} else { |
} else { |
||
− | // |
+ | //everything else |
}</pre> |
}</pre> |
||
Line 51: | Line 53: | ||
; <tt>[[Function_Reference/is_admin|is_admin()]]</tt>: When the Dashboard or the administration panels are being displayed. |
; <tt>[[Function_Reference/is_admin|is_admin()]]</tt>: When the Dashboard or the administration panels are being displayed. |
||
+ | ; <tt>[[Function_Reference/is_network_admin|is_network_admin()]]</tt>: When the Network Dashboard or the Network administration panels for multisite are being displayed. |
||
'''Attention''': The '''wp-login.php''' page is not an admin page. To check if this page is displayed, use <tt>[[Global_Variables#Admin_Globals|the admin global variable]]</tt> '''$pagenow'''. |
'''Attention''': The '''wp-login.php''' page is not an admin page. To check if this page is displayed, use <tt>[[Global_Variables#Admin_Globals|the admin global variable]]</tt> '''$pagenow'''. |
||
Line 61: | Line 64: | ||
=== A Single Post Page === |
=== A Single Post Page === |
||
− | ; <tt>[[Function_Reference/is_single|is_single()]]</tt> : When |
+ | ; <tt>[[Function_Reference/is_single|is_single()]]</tt> : When a single post of any post type (except attachment and page post types) is being displayed. |
; <tt>is_single( '17' )</tt> : When Post 17 is being displayed as a single Post. |
; <tt>is_single( '17' )</tt> : When Post 17 is being displayed as a single Post. |
||
; <tt>is_single( 'Irish Stew' )</tt> : When the Post with Title "Irish Stew" is being displayed as a single Post. |
; <tt>is_single( 'Irish Stew' )</tt> : When the Post with Title "Irish Stew" is being displayed as a single Post. |
||
Line 96: | Line 99: | ||
=== A PAGE Page === |
=== A PAGE Page === |
||
− | This section refers to WordPress [[Pages]], not any generic |
+ | This section refers to WordPress [[Pages]], not any generic web page from your blog, or in other words to the built in ''post_type'' 'page'. |
; <tt>[[Function_Reference/is_page|is_page()]]</tt> : When any [[Pages|Page]] is being displayed. |
; <tt>[[Function_Reference/is_page|is_page()]]</tt> : When any [[Pages|Page]] is being displayed. |
||
Line 105: | Line 108: | ||
; <tt>is_page( array( 42, 54, 6 ) )</tt> : Returns true when the [[Pages|Pages]] displayed is either ''post ID'' = 42, or ''post ID'' = 54, or ''post ID'' = 6. |
; <tt>is_page( array( 42, 54, 6 ) )</tt> : Returns true when the [[Pages|Pages]] displayed is either ''post ID'' = 42, or ''post ID'' = 54, or ''post ID'' = 6. |
||
− | See also [[Function_Reference/is_page|is_page()]] for more snippets. |
+ | See also [[Function_Reference/is_page|is_page()]] for more snippets, such as <tt>is_subpage</tt>, <tt>is_tree</tt>. |
''Note'': There is no function to check if a page is a sub-page. We can get around the problem: |
''Note'': There is no function to check if a page is a sub-page. We can get around the problem: |
||
Line 128: | Line 131: | ||
; <tt>is_category( 'blue-cheese' )</tt> : When the archive page for the Category with Category Slug "blue-cheese" is being displayed. |
; <tt>is_category( 'blue-cheese' )</tt> : When the archive page for the Category with Category Slug "blue-cheese" is being displayed. |
||
; <tt>is_category( array( 9, 'blue-cheese', 'Stinky Cheeses' ) )</tt> : Returns true when the category of posts being displayed is either term_ID 9, or ''slug'' "blue-cheese", or ''name'' "Stinky Cheeses". |
; <tt>is_category( array( 9, 'blue-cheese', 'Stinky Cheeses' ) )</tt> : Returns true when the category of posts being displayed is either term_ID 9, or ''slug'' "blue-cheese", or ''name'' "Stinky Cheeses". |
||
+ | ; <tt>is_category( 5 ) || cat_is_ancestor_of( 5, get_query_var( 'cat' ) )</tt> : Returns true when the category of posts being displayed is either term_id 5, or an ancestor of term_id 5 (subcategory, sub-subcategory...). |
||
; <tt>in_category( '5' )</tt> : Returns true if the current post is '''in''' the specified category id ([[Template_Tags/in_category|read more]]). |
; <tt>in_category( '5' )</tt> : Returns true if the current post is '''in''' the specified category id ([[Template_Tags/in_category|read more]]). |
||
; <tt>in_category( array( 1,2,3 ) )</tt> : Returns true if the current post is '''in''' either category 1, 2, or 3. |
; <tt>in_category( array( 1,2,3 ) )</tt> : Returns true if the current post is '''in''' either category 1, 2, or 3. |
||
Line 149: | Line 153: | ||
==== is_tax ==== |
==== is_tax ==== |
||
− | ; <tt>[[Function_Reference/is_tax|is_tax()]]</tt> : |
+ | ; <tt>[[Function_Reference/is_tax|is_tax()]]</tt> : True for custom taxonomy archive pages, false for built-in taxonomies (category and tag archives). |
; <tt>is_tax( 'flavor' )</tt> : When a Taxonomy archive page for the flavor taxonomy is being displayed. |
; <tt>is_tax( 'flavor' )</tt> : When a Taxonomy archive page for the flavor taxonomy is being displayed. |
||
; <tt>is_tax( 'flavor', 'mild')</tt> : When the archive page for the flavor taxonomy with the slug of 'mild' is being displayed. |
; <tt>is_tax( 'flavor', 'mild')</tt> : When the archive page for the flavor taxonomy with the slug of 'mild' is being displayed. |
||
Line 163: | Line 167: | ||
==== is_taxonomy_hierarchical ==== |
==== is_taxonomy_hierarchical ==== |
||
− | ; <tt>[[Function_Reference/is_taxonomy_hierarchical|is_taxonomy_hierarchical( $taxonomy )]]</tt> : Returns <tt>true</tt> |
+ | ; <tt>[[Function_Reference/is_taxonomy_hierarchical|is_taxonomy_hierarchical( $taxonomy )]]</tt> : Returns <tt>true</tt> if the taxonomy <tt>$taxonomy</tt> is hierarchical. To declare a taxonomy hierarchical, use <tt>'hierarchical' => true</tt> when using [[Function_Reference/register_taxonomy|register_taxonomy()]]. |
==== taxonomy_exists ==== |
==== taxonomy_exists ==== |
||
Line 363: | Line 367: | ||
</pre> |
</pre> |
||
This would check if the script named 'fluidVids.js' is enqueued. If it is not enqueued, the files are then registered and enqueued. |
This would check if the script named 'fluidVids.js' is enqueued. If it is not enqueued, the files are then registered and enqueued. |
||
+ | |||
+ | === Is Previewed in the Customizer === |
||
+ | ; <tt>[[Function_Reference/is_customize_preview|is_customize_preview()]]</tt> : Returns <tt>true</tt> if the site is being previewed in the [[Theme_Customization_API|Customizer]], <tt>false</tt> otherwise. |
||
==Working Examples== |
==Working Examples== |
||
Line 384: | Line 391: | ||
add_action( 'loop_start', 'add_to_single_posts' ); |
add_action( 'loop_start', 'add_to_single_posts' ); |
||
function add_to_single_posts() { |
function add_to_single_posts() { |
||
− | if ( |
+ | if ( is_single('post') ) { |
+ | echo'<div class="your-class">Your Text or HTML</div>'; |
||
+ | } |
||
+ | } |
||
+ | </pre> |
||
+ | |||
+ | You could also use: |
||
+ | |||
+ | <pre> |
||
+ | add_action( 'loop_start', 'wpsites_add_to_single_posts' ); |
||
+ | function wpsites_add_to_single_posts() { |
||
+ | if ( is_single() ) { |
||
echo'<div class="your-class">Your Text or HTML</div>'; |
echo'<div class="your-class">Your Text or HTML</div>'; |
||
} |
} |
||
Line 417: | Line 435: | ||
===Check for Multiple Conditionals=== |
===Check for Multiple Conditionals=== |
||
− | You can use [http://www.w3schools.com/php/php_operators.asp |
+ | You can use [http://www.w3schools.com/php/php_operators.asp PHP operators] to evaluate multiple conditionals in a single if statement. |
This is handy if you need to check whether combinations of conditionals evaluate to true or false. |
This is handy if you need to check whether combinations of conditionals evaluate to true or false. |
||
Line 581: | Line 599: | ||
* [[#A_Child_Theme|is_child_theme]] |
* [[#A_Child_Theme|is_child_theme]] |
||
* [[#A_Comments_Popup|is_comments_popup]] |
* [[#A_Comments_Popup|is_comments_popup]] |
||
+ | * [[#Is_Previewed_in_the_Customizer|is_customize_preview]] |
||
* [[#A_Date_Page|is_date]] |
* [[#A_Date_Page|is_date]] |
||
* [[#A_Date_Page|is_day]] |
* [[#A_Date_Page|is_day]] |
Languages: English • Français • Italiano • 日本語 Türkçe • Português do Brasil • 中文(简体) • (Add your language)
The Conditional Tags can be used in your Template files to change what content is displayed and how that content is displayed on a particular page depending on what conditions that page matches. For example, you might want to display a snippet of text above the series of posts, but only on the main page of your blog. With the is_home() Conditional Tag, that task is made easy.
Note the close relation these tags have to WordPress Template Hierarchy.
Warning: You can only use conditional query tags after the posts_selection action hook in WordPress (the wp action hook is the first one through which you can use these conditionals). For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function.
However: if you have a reference to the query object (for example, from within the parse_query or pre_get_posts hooks), you can use the WP_Query conditional methods (eg: $query->is_search()
)
All of the Conditional Tags test to see whether a certain condition is met, and then returns either TRUE or FALSE. The conditions under which various tags output TRUE is listed below. Those tags which can accept parameters are so noted.
There is no conditional tag for the blog page. You have to use both is_home() and is_front_page() to detect this page, but those functions can be misused. In fact, a user can define a static page for the homepage, and another page to display the blog. This one will return true with is_home() function, even if it's not the homepage. Here is what a user can define :
When you use is_home() and is_front_page(), you have to use them in the right order to avoid bugs and to test every user configuration:
if ( is_front_page() && is_home() ) { // Default homepage } elseif ( is_front_page() ) { // static homepage } elseif ( is_home() ) { // blog page } else { //everything else }
Attention: The wp-login.php page is not an admin page. To check if this page is displayed, use the admin global variable $pagenow.
Note : To display or not this bar, use show_admin_bar(), this function should be called immediately upon plugins_loaded or placed in the theme's functions.php file.
Note: This function does not distinguish between the post ID, post title, or post name. A post named "17" would be displayed if a post ID of 17 was requested. Presumably the same holds for a post with the slug "17".
To turn on post type archives, use 'has_archive' => true, when registering the post type.
This section refers to WordPress Pages, not any generic web page from your blog, or in other words to the built in post_type 'page'.
See also is_page() for more snippets, such as is_subpage, is_tree.
Note: There is no function to check if a page is a sub-page. We can get around the problem:
if ( is_page() && $post->post_parent > 0 ) { echo "This is a child page"; }
Allows you to determine whether or not you are in a page template or if a specific page template is being used.
Note: if the file is in a subdirectory you must include this as well. Meaning that this should be the filepath in relation to your theme as well as the filename, for example page-templates/about.php.
Note: Be sure to check your spelling when testing: "is" and "in" are significantly different.
See also is_archive() and Category Templates.
See also is_archive() and Tag Templates.
See also is_archive().
See also is_archive() and Author Templates.
See also is_archive().
See also Using Image and File Attachments.
See also the Custom Post Types book.
Example with the filter hook the_content
add_action( 'the_content', 'baw_add_social_buttons' ); function baw_add_social_buttons( $content ) { if ( ! is_admin() && is_main_query() ) { return $content . function_from_a_social_plugin(); } return $content; }
If, when WordPress tries to display the content of each post in the Loop or in a single post page, we are in the main query, and not admin side, we add some social buttons (for example).
Example with the action hook pre_get_posts
add_action( 'pre_get_posts', 'baw_modify_query_exclude_category' ); function baw_modify_query_exclude_category( $query ) { if ( ! is_admin() && $query->is_main_query() && ! $query->get( 'cat' ) ) { $query->set( 'cat', '-5' ); } }
With pre_get_posts, this is not possible to call directly is_main_query, we should use $query given as a parameter.
See also register_nav_menu().
Note: To display a sidebar's content, use dynamic_sidebar( $sidebar ).
Note : To be effective this function has to run after widgets have initialized, at action 'init' or later, see Action Reference.
Note: The cache will be checked first. If you have a cache plugin, which saves the cache values, then this will work. If you use the default WordPress cache, and the database goes away, then you might have problems.
Example
if ( is_rtl() ) { wp_enqueue_style( 'style-rtl', plugins_url( '/css/style-rtl.css', __FILE__ ) ); wp_enqueue_script( 'script-rtl', plugins_url( '/js/script-rtl.js', __FILE__ ) ); }
Example
$handle = 'fluidVids.js'; $list = 'enqueued'; if ( wp_script_is( $handle, $list ) ) { return; } else { wp_register_script( 'fluidVids.js', plugin_dir_url(__FILE__).'js/fluidvids.min.js'); wp_enqueue_script( 'fluidVids.js' ); }
This would check if the script named 'fluidVids.js' is enqueued. If it is not enqueued, the files are then registered and enqueued.
Here are working samples to demonstrate how to use these conditional tags.
This example shows how to use is_single() to display something specific only when viewing a single post page:
if ( is_single() ) { echo 'This post\'s title is ' . get_the_title(); }
Add this custom function to your child themes functions.php file and modify the conditional tag to suit your needs.
add_action( 'loop_start', 'add_to_single_posts' ); function add_to_single_posts() { if ( is_single('post') ) { echo'<div class="your-class">Your Text or HTML</div>'; } }
You could also use:
add_action( 'loop_start', 'wpsites_add_to_single_posts' ); function wpsites_add_to_single_posts() { if ( is_single() ) { echo'<div class="your-class">Your Text or HTML</div>'; } }
Another example of how to use Conditional Tags in the Loop. Choose to display content or excerpt in index.php when this is a display single post or the home page.
if ( is_home() || is_single() ) { the_content(); } else { the_excerpt(); }
When you need display a code or element, in a place that is NOT the home page.
<?php if ( ! is_home() ) {?> Insert your markup ... <?php } ?>
You can use PHP operators to evaluate multiple conditionals in a single if statement.
This is handy if you need to check whether combinations of conditionals evaluate to true or false.
// Check to see if 2 conditionals are met if ( is_single() || is_page() ) ) { // If it's a single post or a single page, do something special } if ( is_archive() && ! is_category( 'nachos' ) ) { // If it's an archive page for any category EXCEPT nachos, do something special }
// Check to see if 3 conditionals are met if ( $query->is_main_query() && is_post_type_archive( 'products' ) && ! is_admin() ) { // If it's the main query on a custom post type archive for Products // And if we're not in the WordPress admin, then do something special } if ( is_post_type_archive( 'movies' ) || is_tax( 'genre' ) || is_tax( 'actor' ) ) { // If it's a custom post type archive for Movies // Or it's a taxonomy archive for Genre // Or it's a taxonomy archive for Actor, do something special }
If someone browses our site by date, let's distinguish posts in different years by using different colors:
<?php // this starts The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <h2 id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <?php the_title(); ?></a></h2> <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small> <?php // are we showing a date-based archive? if ( is_date() ) { if ( date( 'Y' ) != get_the_date( 'Y' ) ) { // this post was written in a previous year // so let's style the content using the "oldentry" class echo '<div class="oldentry">'; } else { echo '<div class="entry">'; } } else { echo '<div class="entry">'; } the_content( 'Read the rest of this entry »' ); ?> </div>
This example will display different content in your sidebar based on what page the reader is currently viewing.
<!-- begin sidebar --> <div id="sidebar"> <?php // let's generate info appropriate to the page being displayed if ( is_home() ) { // we're on the home page, so let's show a list of all top-level categories echo "<ul>"; wp_list_categories( 'optionall=0&sort_column=name&list=1&children=0' ); echo "</ul>"; } elseif ( is_category() ) { // we're looking at a single category view, so let's show _all_ the categories echo "<ul>"; wp_list_categories( 'optionall=1&sort_column=name&list=1&children=1&hierarchical=1' ); echo "</ul>"; } elseif ( is_single() ) { // we're looking at a single page, so let's not show anything in the sidebar } elseif ( is_page() ) { // we're looking at a static page. Which one? if ( is_page( 'About' ) ) { // our about page. echo "<p>This is my about page!</p>"; } elseif ( is_page( 'Colophon' ) ) { echo "<p>This is my colophon page, running on WordPress, " . bloginfo( 'name' ) . "</p>"; } else { // catch-all for other pages echo "<p>Vote for Pedro!</p>"; } } else { // catch-all for everything else (archives, searches, 404s, etc) echo "<p>That's all.</p>"; } // That's all, folks! ?> <form id="searchform" method="get" action="<?php echo esc_url( $_SERVER['PHP_SELF'] ); ?>"> <div> <input type="text" name="s" id="s" size="15" /> <input type="submit" value="<?php _e( 'Search' ); ?>" /> </div> </form> </div> <!-- end sidebar -->
The Creating an Error 404 Page article has an example of using the PHP conditional function
isset()
in the Writing Friendly Messages section.
The Dynamic Menu Highlighting article discusses how to use the conditional tags to enable highlighting of the current page in a menu.
At times queries performed in other templates such as sidebar.php may corrupt certain conditional tags. For instance, in header.php a conditional tag works properly but doesn't work in a theme's footer.php. The trick is to put wp_reset_query before the conditional test in the footer. For example:
<?php wp_reset_query(); if ( is_page( '2' ) ) { echo 'This is page 2!'; } ?>