Paste the following code into your functions.php
file. The wp_terms_checklist_args
filter hook will make sure that one or more category is pre-selected and the op_create_selected_cat_post_link()
function will help you to create a new post link with pre-selected category ids. The function takes $cats
parameter and it can be a single category id or multiple categories ids. You can also pass the link text. The function also checks user login status and user capability.
add_filter( 'wp_terms_checklist_args', function( $args ) {
global $pagenow;
if ( is_admin() && 'post-new.php' === $pagenow && isset( $_GET['cat'] ) ) {
$cat = array();
if ( is_array( $_GET['cat'] ) ) {
$cat = array_filter( $_GET['cat'], 'absint' );
} else {
$cat = (array) absint( $_GET['cat'] );
}
$args['selected_cats'] = $cat;
}
return $args;
} );
/**
* Create a new post link with preselected category
*
* @param int|array $cats Preselected category id
* @return void
*/
function op_create_selected_cat_post_link( $cats, $text = 'Create a new post' ) {
if ( ! is_user_logged_in() || ! current_user_can( 'edit_posts' ) ) {
return;
}
$url = admin_url( add_query_arg(
array(
'cat' => $cats,
),
'post-new.php'
) );
echo '<a href="' . esc_url( $url ) . '">' . esc_html( $text ) . '</a>';
}