1

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?

1 Answer 1

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');
3
  • thank you! How would I link to it, from the dashboard for it to work? My current method does not work with this
    – Cody
    Commented Jan 8, 2013 at 14:50
  • You only need to add this to your functions.php file. Then this will add a category to new posts. (Is there a way to asign a category to a post, before it is published) Commented Jan 8, 2013 at 14:54
  • ah ok, but this will set the same category for all posts I add, right? I am trying to create links from the dashboard for my client to create a post in a certain category without having to select the category. This I have done - but I have different fields assigned to each category, which are not visible untill the post is published (and thereby saved in the category). SO I want to somehow save the post to the category, and thereby making my fields for that category visible, before the user publishes the post.
    – Cody
    Commented Jan 8, 2013 at 21:54

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.