Saving category to a post, before publishing the post

I have created a link from the dashboard, which goes to add new post, but with a category already selected for the post – but the post will not belong to this category before publishing – this is a problem, because I have some custom fields, which I have assigned to the category, and they will not be visible before the post is published.

Is there a way to asign a category to a post, before it is published, which will make what I am trying to achieve possible?

Related posts

Leave a Reply

1 comment

  1. You can use the function wp_set_post_terms to set a category before the post is published. You need to get the post_id by call the global variable $post and get the id by $post->ID.

    Here is a simple example. Change the id (2) to the id of your wanted category.

    function wpse_78701_add_category_before_post() {
        global $post;
        if( $post->ID ) {
            wp_set_post_terms( $post->ID, 2, 'category' );
        }
    }
    add_action('admin_head', 'wpse_78701_add_category_before_post');
    

    Update

    If you want to change the category that will be saved when the user clicks on the link you have to add something like ?cat=2 on the dashboard-links like this:

    echo '<a href="post-new.php?cat=1">'. __('Add new post in category X', 'theme') .'</a>';
    

    Then you can get the category bu use $_GET['cat']; like this:

    function wpse_78701_add_category_before_post() {
        global $post;
    
        // Get category-ID from the link in dashboard (cat=X)
        $category = ( isset( $_GET['cat'] ) ? $_GET['cat'] : '' );
    
        if( isset( $post ) && $post->ID ) {
            wp_set_post_terms( $post->ID, $category, 'category' );
        }
    }
    add_action('admin_head', 'wpse_78701_add_category_before_post');