1

How can i create a direct link to "New post" (/post-new.php), which will create a new post automatically added in specific category?

In other words, i click on the link "new post in category one", then browser opens WP editor, where category "one" is already selected.

Maybe i can somehow do it with information from the URL? Something like this: "/post-new.php?postcategory=one". Don't know is it possible to do.

Thank you!

1 Answer 1

1

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>';
}
3
  • 1
    Can you please post same sample link url? I can not get it preselect categories. Commented Apr 4, 2020 at 18:25
  • 1
    @LeeGee I didn't find any deprecated notice in the source. Where did you find that it's been deprecated?
    – obiPlabon
    Commented Oct 3, 2020 at 8:37
  • @obiPlabon - My bad: it is called by wp_terms_checklist despite the note in the Codex saying it is deprecated. Must be another reason this code was ineffective for me. Commented Oct 5, 2020 at 8:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.