Limit the number of categories for posts in WordPress

Just one category for each post

Settembre 14, 2015

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 &quot;&lt;script type='text/javascript'&gt;\n&quot;;
		echo 'jQuery(document).ready(function($){
			$(&quot;#category-all input:checkbox&quot;).change(function () {
				var max = 1;
				var count = $(&quot;#category-all input:checked&quot;).length;
				if (count &gt; max) {
					$(this).prop(&quot;checked&quot;, &quot;&quot;);
					alert(&quot;You can choose &quot; + max + &quot; categor&quot; + (max==1?&quot;y&quot;:&quot;ies&quot;) );
				}
			});
		});';
		echo &quot;\n&lt;/script&gt;&quot;;
	}
}

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.

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.