Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.9 kB
7
Indexable
Never
add_action('woocommerce_after_add_to_cart_button', function(){
	global $post;
	$current_user = get_current_user_id();
	$subaccounts_list = explode(',', get_user_meta($current_user, 'b2bking_subaccounts_list', true));
	$subaccounts_list = array_filter($subaccounts_list); // filter blank, null, etc.
	// add current user to subaccounts to form a complete accounts list
	array_push($subaccounts_list, $current_user);

	// if current account is subaccount AND has permission to view all account purchase lists, add parent account+all subaccounts lists
	$account_type = get_user_meta($current_user, 'b2bking_account_type', true);
	if ($account_type === 'subaccount'){
		$permission_view_all_lists = filter_var(get_user_meta($current_user, 'b2bking_account_permission_view_lists', true),FILTER_VALIDATE_BOOLEAN);
		if ($permission_view_all_lists === true){
			// has permission
			$parent_account = get_user_meta($current_user, 'b2bking_account_parent', true);
			$parent_subaccounts_list = explode(',', get_user_meta($parent_account, 'b2bking_subaccounts_list', true));
			$parent_subaccounts_list = array_filter($parent_subaccounts_list); // filter blank, null, etc.
			array_push($parent_subaccounts_list, $parent_account); // add parent itself to form complete parent accounts list

			$subaccounts_list = array_merge($subaccounts_list, $parent_subaccounts_list);
		}
	}

	$purchase_lists = get_posts([
		'post_type' => 'b2bking_list',
	  	'post_status' => 'publish',
	  	'numberposts' => -1,
	  	'author__in' => $subaccounts_list,
	]);

	?>
	<br><br>
	Add to purchase list: &nbsp;
	<select id="chosen_purchase_list">
		<?php
		foreach($purchase_lists as $list){
			echo '<option value="'.$list->ID.'">'.esc_html($list->post_title).'</option>';
		}
	?>
	</select>
	<button type="button" id="save_product_purchase_list" name="save_product_purchase_list" value="<?php echo esc_attr($post->ID);?>">Add to list</button>
	<?php
});

add_action( 'wp_ajax_b2bkingsavetoplist',  'b2bkingsavetoplist') ;
add_action( 'b2bkingsavetoplist',  'b2bkingsavetoplist') ;

function b2bkingsavetoplist(){

	$plist = sanitize_text_field($_POST['plist']);
	$prodid = sanitize_text_field($_POST['prodid']);

	$list_details = get_post_meta($plist,'b2bking_purchase_list_details', true);
	$list_details .= $prodid.':1|';
	update_post_meta($plist,'b2bking_purchase_list_details', $list_details);

}

add_action('wp_head', function(){
	?>
	<script>
		jQuery(document).ready(function(){
			jQuery('#save_product_purchase_list').on('click', function(){
				var plist = jQuery('#chosen_purchase_list').val();
				console.log(plist);

				var datavar = {
		            action: 'b2bkingsavetoplist',
		            plist: plist,
		            prodid: jQuery(this).val()
		        };

				jQuery.post(b2bking_display_settings.ajaxurl, datavar, function(response){
					alert('Added successfully!');
				});
			});
		});
	</script>
	<?php
});