I’m trying to get WordPress to display future dated posts (in a certain category) as published so I can display upcoming events.
I found the following code through a blog post ([https://onetarek.com/wordpress/publish-a-wordpress-post-with-a-future-date/]) and his code works almost perfectly:
function onetarek_prevent_future_type( $post_data ) {
if ( $post_data[‘post_status’] == ‘future’ && $post_data[‘post_type’] == ‘post’ ) {
$post_data[‘post_status’] = ‘publish’;
}
return $post_data;
}
add_filter(‘wp_insert_post_data’, ‘onetarek_prevent_future_type’);
remove_action(‘future_post’, ‘_future_post_hook’);
But I only want this function to trigger on certain post categories so I’ve modified the code as follows:
function prevent_future_post( $post_data ) {
$id = get_the_ID();
$category_name = get_the_category( $id )[0]->name;
if ( $post_data[‘post_status’] == ‘future’ && $post_data[‘post_type’] == ‘post’ && $category_name == ‘events’ ) {
$post_data[‘post_status’] = ‘publish’;
}
return $post_data;
}
add_filter(‘wp_insert_post_data’, ‘prevent_future_post’);
remove_action(‘future_post’, ‘_future_post_hook’);
But when I save it and publish a future dated post, the default behaviour happens and it is scheduled.
The check I added && $category\_name == ‘events’ is pretty simple so I assume the problem lies in the two lines above the if statement where I am getting the post ID and then getting the category name from that.
EDIT:
I have read a comment on the original blog post, the author doesn’t answer the question fully but maybe points in the right direction – I have tried accessing other arguments of the action but this still doesn’t work:
function onetarek_prevent_future_type( $post_data, $postarr ) {
if ( $post_data[‘post_status’] == ‘future’ && $post_data[‘post_type’] == ‘post’ && $postarr[‘post_category’] == ‘events’ ) {
$post_data[‘post_status’] = ‘publish’;
}
return $post_data;
}
add_filter(‘wp_insert_post_data’, ‘onetarek_prevent_future_type’, 99, 2);
remove_action(‘future_post’, ‘_future_post_hook’);
Can someone tell me what I am doing wrong?
Thanks in advance.
[ad_2]
What can you see in $category_name? Not sure if get_the_category will work with a CPT.