How to preset listing category based on Vendor category

Hello,

This is recurring problem encountered a couple of times on this forum, that I would like to solve.

I tried to sync both categories, but without success.

Please help.

Solved, at last !
A nice-to-have feature to preset the listing category based on vendor category, quite an improvement, UX-wise !

What I mean by “preset” is set a default value which is different from “-” , which would not validate (unless you use this code) and forces you to manually set it, over and over.

Without further ado, here’s how to do it :
(you’ll probably have to tweak the code slightly to your needs, at least to reflect your own categories IDs and matches)

//(PHP code)
function add_inline_jquery_script() {
	if ($_SERVER['REQUEST_URI'] ==='/submit-listing/details/'){
		//retrieve current vendor from user_id 
		$vendor = \HivePress\Models\Vendor::query()->filter(
		[
			'status__in' => [ 'auto-draft', 'draft', 'publish' ],
			'user'       => get_current_user_id(),
		]
		)->get_first();
		
		//retrieve current vendor category id 
		$current_vendor_cat_id = intval(implode(',',$vendor->get_categories__id())); 

		//match current_vendor_cat_id to preset_listing_cat_id
		switch($current_vendor_cat_id){
			case 172:
				$preset_listing_cat_id = 58; //Category A 
				break;
			case 174:
				$preset_listing_cat_id = 76; //Category B
				break;
            //add as many cases as needed... 
			default :
				$preset_listing_cat_id = 0;  //just in case
		}
		if($preset_listing_cat_id != 0){
		?>
		<script type="text/javascript">
		jQuery(document).ready(function ($) {
			$("select[name='categories']").val(<?php echo $preset_listing_cat_id;?>).trigger('change');
		});
		</script>
		<?php
		}
	} 
	
}// /add_inline_jquery_script 
add_action('wp_footer', 'add_inline_jquery_script');

Result (preset based on vendor’s category) :

image

Instead of :

Note that other solutions may exist, but this one allows end-user to change the preset if need be. So it remains flexible.
If you judge letting vendor change category is not advisable or unnecessary, you can simply hide it, with this extra snippet (that you can add in the code above):

jQuery("select[name='categories']").parent().hide();

If you know of a more concise solution, feel free to mention it.
I hope this is helpful to you. If so, please give me some :heart: !

1 Like