0

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!

0

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>';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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