I’m making a page for settings API using Codestar Framework, and loading fields using their filterable configure – question is not related to Codestar. In one of such dropdown field, I need to load all the posts from a custom post type that are added within 30 days. To make the things nice and clean I made a custom function:
<?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;
}
Question is not even with the function.
I want to do the query only on that particular top_level_custom-settings-api page. The function is loading on every page load of admin. I tried using get_current_screen()
but this function’s giving me not found fatal error.
Edit
No @bonger, I remembered that. I tried your code in this way:
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' );
}
}
The code does work well, but it doesn’t control my function loading only on that particular page. I checked the query on other pages, the query is there too. And I tried changing the conditional to something wrong, like $screen->id == 'top_level_-api'
, it still works that way. 🙁
I’m afraid, I know I have a serious lack in behind-the-scene action and filter things. Would love to have a good read for that too.