I realize this is an old question, but I wanted to achieve the same thing and I managed to do this by creating a simple plugin and thought I'd share the solution.
Create a new plugin file in your WordPress plugins folder, e.g., wp-content/plugins/auto-category-select/auto-category-select.php.
Add the following PHP code to the new plugin file:
<?php
/**
* Plugin Name: Auto Category Select
* Description: Automatically select a category in the new post page based on a URL parameter.
*/
function auto_category_select_enqueue($hook) {
if ('post-new.php' != $hook) {
// Only applies to post creation page
return;
}
wp_enqueue_script('auto_category_select_script', plugins_url('auto-category-select.js', __FILE__));
}
add_action('admin_enqueue_scripts', 'auto_category_select_enqueue');
This code creates a new WordPress plugin that enqueues a JavaScript file named auto-category-select.js when the new post page is loaded.
Create a new JavaScript file named auto-category-select.js in the same folder as the plugin file.
Add the following JavaScript code to the new JavaScript file:
function checkCategoryCheckbox() {
const urlParams = new URLSearchParams(window.location.search);
const category = urlParams.get('category');
console.log('Category from URL: ' + category);
if (category) {
const labels = document.querySelectorAll('.editor-post-taxonomies__hierarchical-terms-choice');
if (labels.length > 0) {
labels.forEach(function(label) {
console.log('Label text: ' + label.textContent.trim());
if (label.textContent.trim() === category) {
const checkbox = label.querySelector('input');
// Create a new click event
var clickEvent = new MouseEvent('click', {
'bubbles': true,
'cancelable': true,
});
// Dispatch the click event on the checkbox
checkbox.dispatchEvent(clickEvent);
console.log('Checkbox should be checked now');
}
});
// If we've found the labels, we can stop checking
clearInterval(checkInterval);
}
}
}
// Start checking for the checkboxes every 500 milliseconds
var checkInterval = setInterval(checkCategoryCheckbox, 500);
You can then add this snippet of code to your functions.php file or by using something like the Code Snippets plugin:
function add_custom_links_to_admin_sidebar() {
add_menu_page(
'Add Blog', // Page title
'Add Blog', // Menu title
'publish_posts', // Capability
'post-new.php?category=Blog', // Menu slug
'', // Function
'dashicons-welcome-write-blog', // Icon URL
6 // Position
);
add_menu_page(
'Add News',
'Add News',
'publish_posts',
'post-new.php?category=News',
'',
'dashicons-welcome-write-blog',
7
);
}
add_action('admin_menu', 'add_custom_links_to_admin_sidebar');
Hope that helps someone out!