is_post_type_archive()判断当前的文章是否为某个类型

目录

描述

Checks if the query is for an archive page of a given post type(s).

is_post_type_archive() 描述

用法

<?php is_post_type_archive$post_types ); ?>

is_post_type_archive() 用法

参数

$post_types

(array/string) (可选) Post type or array of posts types to check against.

默认值: None

is_post_type_archive() 参数

返回值

(boolean

Whether the query is for an archive page of a given post type(s).

is_post_type_archive() 返回值

示例

Determine if the current page is an archive made by a custom post type and display the custom post type title:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php
if ( is_post_type_archive() ) {
    ?>
    <h1><?php post_type_archive_title(); ?></h1>
    <?php
}
?>

is_post_type_archive() 示例

注意

This returns false for a page like /category/uncategorized/?post_type=custom. It only returns true for a page like /?post_type=custom. In other words, it's not checking for the existence of the post_type query parameter, it's testing if this is the archive of all posts of a given type. You might instead be looking for get_query_var('post_type').

Depending on when this function is run it may or may not be run by nav_menu_item. Take the following code example:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php
function some_func( $query ){
    if ( is_post_type_archive('my_custom_post_type') ) {
         // Do stuff
    }
}
add_action('pre_get_posts','some_func');
?>

"Do stuff" may or may not be run in the menu, depending on if the theme is using nav menus or not. The correct usage would be:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php
function some_func( $query ){
    if ( is_post_type_archive('my_custom_post_type') 
         && ! empty( $query->query['post_type']  == 'my_custom_post_type' ) {
         // Do stuff
    }
}
add_action('pre_get_posts','some_func');
?>

is_post_type_archive() 注意

历史

  • 添加于 版本: 3.1.0

is_post_type_archive() 历史

源文件

is_post_type_archive() 函数的代码位于 wp-includes/query.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Is the query for an existing post type archive page?
 *
 * @since 3.1.0
 *
 * @global WP_Query $wp_query
 *
 * @param string|array $post_types Optional. Post type or array of posts types to check against.
 * @return bool
 */
function is_post_type_archive( $post_types = '' ) {
	global $wp_query;

	if ( ! isset( $wp_query ) ) {
		_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
		return false;
	}

	return $wp_query->is_post_type_archive( $post_types );
}

is_post_type_archive() 源文件

相关