如何在 admin_init 钩子回调中检测自定义帖子类型? [英] How to detect custom post type inside admin_init hook callback?
本文介绍了如何在 admin_init 钩子回调中检测自定义帖子类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
或者我应该使用不同的钩子吗?主要是我试图仅在管理员中执行某些操作,并且仅针对某些自定义帖子.
Or should I use different hook? Mainly I'm trying to perform some actions only when in admin and only for some of custom posts.
推荐答案
这个方法很简单:
/**
* Based on http://wordpress.stackexchange.com/a/59999/12615
*/
add_action( 'admin_head', 'wpse_59652_list_terms_exclusions' );
function wpse_59652_list_terms_exclusions() {
global $current_screen;
if( 'post' != $current_screen->post_type )
return;
// Do your stuff
}
另一个:
/**
* Based on http://wordpress.stackexchange.com/a/54279/12615
*/
add_action( 'admin_notices', 'wpse_54258_display_error_message' );
function wpse_54258_display_error_message() {
global $post;
if( !isset( $post ) || 'page' != $post->post_type )
return;
?>
<div class="error fade">This is a "page" post type</div>
<?php
}
还有一个复杂的:
/***
* Conditional enqueue of scripts according to Admin page
* Based on http://wordpress.stackexchange.com/a/9095/12615
*/
add_action('admin_init', 'wpse_9080_admin_init');
function wpse_9080_admin_init() {
global $pagenow;
global $firephp; // Using FirePHP for debugging - Remove if library not included
if ( 'edit.php' == $pagenow) {
if ( !isset($_GET['post_type']) ) {
$firephp->log('I am the Posts listings page');
}
elseif ( isset($_GET['post_type']) && 'page' == $_GET['post_type'] ) {
// Will occur only in this screen: /wp-admin/edit.php?post_type=page
$firephp->log('I am the Pages listings page');
}
}
if ('post.php' == $pagenow && isset($_GET['post']) ) {
// Will occur only in this kind of screen: /wp-admin/post.php?post=285&action=edit
// and it can be a Post, a Page or a CPT
$post_type = get_post_type($_GET['post']);
$firephp->log($post_type);
if ( 'post' == $post_type ) {
$firephp->log('I am editing a post');
}
elseif ( 'page' == $post_type) {
$firephp->log('I am editing a page');
}
elseif ( 'movie' == $post_type) {
$firephp->log('I am editing a custom post type');
}
}
if ('post-new.php' == $pagenow ) {
// Will occur only in this kind of screen: /wp-admin/post-new.php
// or: /wp-admin/post-new.php?post_type=page
if ( !isset($_GET['post_type']) ) {
$firephp->log('I am creating a new post');
}
elseif ( isset($_GET['post_type']) && 'page' == $_GET['post_type'] ) {
$firephp->log('I am creating a new page');
}
elseif ( isset($_GET['post_type']) && 'movie' == $_GET['post_type'] ) {
$firephp->log('I am creating a new custom post type');
}
}
}
这篇关于如何在 admin_init 钩子回调中检测自定义帖子类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文