我正在使用Codestar框架为设置API创建一个页面,并使用其filterable configure - question is not related to Codestar. 在其中一个下拉字段中,我需要加载30天内添加的自定义帖子类型中的所有帖子。为了使这些东西美观整洁,我创建了一个自定义函数:
<?php
/**
* Get posts of last 30 days only.
*
* @return array Array of posts.
* --------------------------------------------------------------------------
*/
function pre_get_active_posts_of_30_days() {
//admin-only function
if( !is_admin() )
return;
global $project_prefix; //set a project prefix (i.e. pre_)
$latest_posts = new WP_Query(
array(
\'post_type\' => \'cpt\',
\'post_status\' => \'publish\',
\'posts_per_page\' => -1,
\'date_query\' => array(
array(
\'after\' => \'30 days ago\',
\'inclusive\' => true,
),
)
)
);
$posts_this_month = array();
if( $latest_posts->have_posts() ) : while( $latest_posts->have_posts() ) : $latest_posts->the_post();
$validity_type = get_post_meta( get_the_ID(), "{$project_prefix}validity_type", true );
if( $validity_type && \'validity date\' === $validity_type ) {
$validity = get_post_meta( get_the_ID(), "{$project_prefix}validity", true );
$tag = days_until( $validity ) .\' days left\'; //custom function
} else if( $validity_type && \'validity stock\' === $validity_type ) {
$tag = \'Stock\';
} else {
$tag = \'...\';
}
$posts_this_month[get_the_ID()] = get_the_title() .\' [\'. $tag .\']\';
endwhile; endif; wp_reset_postdata();
return $posts_this_month;
}
问题与函数不一致。
我想进行查询only on that particular top_level_custom-settings-api page. 该函数正在加载admin的每个页面。我试过使用get_current_screen()
但是这个函数给了我一个未找到的致命错误。
编辑,不,邦格,我记得。我以这种方式尝试了您的代码:
add_action(\'current_screen\', \'current_screen_callback\');
function current_screen_callback($screen) {
if( is_object($screen) && $screen->id == \'top_level_custom-settings-api\' ) {
add_action( \'admin_init\', \'pre_get_active_posts_of_30_days\' );
}
}
代码确实工作得很好,但它不能控制我的函数仅在该特定页面上加载。我检查了其他页面上的查询,查询也在那里。我试着把条件改错了,比如
$screen->id == \'top_level_-api\'
, 它仍然是这样工作的(
恐怕,我知道我在幕后行动和过滤方面严重不足。我也很想好好读一读。
SO网友:Adam
值得指出的是,使用admin_init
在current_screen
筛选太迟,因为admin_init
已启动。
相反,请执行以下操作:
add_action(\'current_screen\', \'current_screen_callback\');
function current_screen_callback($screen) {
if( is_object($screen) && $screen->id === \'top_level_custom-settings-api\' ) {
add_filter(\'top_level_screen\', \'__return_true\');
}
}
在您的
top_level_page_callback
负责执行查询的回调:
function top_level_page_callback() {
$active_posts = null;
if ( ($is_top_level = apply_filters(\'top_level_screen\', false)) ) {
$active_posts = pre_get_active_posts_of_30_days();
}
//etc...
}
这是一种方法。。。
或者你可以用,add_action(\'load-top_level_custom-settings-api\', \'callback\');
除了current_screen
胡克,你还想打电话给哪里pre_get_active_posts_of_30_days()
从…起因为您必须在某种全局范围内调用它,它才能在所有页面上运行,而不仅仅是在目标页面上运行。