CHOOSE ONLY ONE CATEGORY WORDPRESS
If you need to limit the number of categories used by the authors of your site, there is a trick for you.
This piece of PHP code limits the number of categories choosen by the authors who are using WordPress to edit post articles in your web sites.
The code works only in the backoffice side of WordPress, to do this it starts with is_admin()
check, then it hooks at admin_head
action to add some inline javascript.
The script on the browser side (the javascript code is executed by the client browser, not by the server side) uses jQuery framework to count the checkboxes checked in the <div id="#category-all">
tag, and if the count is grater than the predefined max
variable value, it stops with a a simple alert()
message.
// limit categories wordpress ---------------- if (is_admin()) { add_action( 'admin_head', 'admin_inline_js' ); function admin_inline_js(){ echo "<script type='text/javascript'>\n"; echo 'jQuery(document).ready(function($){ $("#category-all input:checkbox").change(function () { var max = 1; var count = $("#category-all input:checked").length; if (count > max) { $(this).prop("checked", ""); alert("You can choose " + max + " categor" + (max==1?"y":"ies") ); } }); });'; echo "\n</script>"; } }
You can place this code at the bottom of your functions.php
file in your WordPress theme.
Limit categories to 1 for SEO purposes
Limit the number of categories choosen by your authors could be useful to better handle and organize your site navigation, but limit the categories to 1 can be very useful also for Search Engine Optimization, especially if you have the category name in your permalink structure.
If you have, for example, two categories for a post and you have the category slug in your permalink structure your WordPress will creates 2 urls for your post (get_the_permalink()
will return 1 url, but your post will be reached with both urls if you navigated throught caategory pages), which is a bad thing:
http://www.your-site.com/category-name-one/title-of-post/
http://www.your-site.com/category-name-two/title-of-post/
This is bad because for Google you’re site is duplicating contents, which is penalized by Google search engine.