How to Pre-Select a Category for a New Post
Lets say you have a category called “X”, and you want to create a link which when clicked will take the user to the “Add New Post” screen with the “X” category already selected. This could be used to simplify posting for non-technical users, or even as a way to implement “poor-man’s custom post types” of sorts, with categories instead of true CPTs.
To make this possible, you’ll need a way to set the post category via the URL. The following snippet lets you do just that. Simply append a category_id=123 parameter to the post editor URL, and it will automatically select the specified category in the “Categories” widget.
Place this code in your functions.php or a functionality plugin:
function ws_preselect_post_category() {
if ( isset($_GET['category_id']) && is_numeric($_GET['category_id']) ) {
$catId = intval($_GET['category_id']);
?>
<script type="text/javascript">
jQuery(function() {
var catId = <?php echo json_encode($catId); ?>;
jQuery('#in-category-' + catId).click();
});
</script>
<?php
}
}
add_action('admin_footer-post-new.php', 'ws_preselect_post_category');
Now you can pass in the category ID like this: /wp-admin/post-new.php?category_id=123.
For example, suppose you have a web development blog that has a “JavaScript” category with the ID = 15. You could use this snippet to add a Posts -> Add New JS Article link to the admin menu. When you click it, the “JavaScript” category will be selected automatically:
function ws_add_new_post_link() {
add_posts_page(
'Add New JS Article',
'Add New JS Article',
'edit_posts',
'post-new.php?category_id=15'
);
}
add_action('admin_menu', 'ws_add_new_post_link');
Related posts :

