Home > database >  Woocommerce how to get categories ids of a product in the admin post edit page
Woocommerce how to get categories ids of a product in the admin post edit page

Time:12-18

I'm trying to restrict products from a certain category from editing for a specific user role. Any idea how to get the catgories IDs of a product in ...wp-admin/post.php?post=1702&action=edit ?

Here's my code so far:

function restrict_edit_if_in_manufacturing_cat($post){
    global $pagenow, $post_type;

    // Targeting admin edit single product screen
    if ($pagenow === 'post.php' && $post_type === 'product') {

        // Get current user
        $user = wp_get_current_user();

        // Roles
        $roles = (array) $user->roles;

        // Roles to check
        $roles_to_check = array('shop_manager'); // several can be added, separated by a comma

        // Compare
        $compare = array_diff($roles, $roles_to_check);

        // Result is empty
        if (empty($compare)) {

            // $category_ids = ...Get Category IDs here...

            // If 458 is in the category id list die
            if (strpos($category_ids, '458') !== false) {

                wp_die('cheatn');
            } else {

                // do something if needed

            }
        }
    }
}
add_action('pre_get_posts', 'restrict_edit_if_in_manufacturing_cat', 10, 1);

CodePudding user response:

You could use get_the_terms function to get the categories for the current post and then, get their ids, like this:

add_action('pre_get_posts', 'restrict_edit_if_in_manufacturing_cat');

function restrict_edit_if_in_manufacturing_cat($post)
{

    global $pagenow, $post_type;

    if ($pagenow === 'post.php' && $post_type === 'product') 
    {

        $current_user = wp_get_current_user();

        $user_roles = $current_user->roles;

        if (in_array("shop_manager", $user_roles)) 
        {

            $categories_for_the_current_post = get_the_terms($_GET['post'], 'product_cat');

            $categories_ids = array();
            foreach ($categories_for_the_current_post as $category_object) {
                array_push($categories_ids, $category_object->term_id);
            }

            if (in_array('458', $categories_ids)) 
            {

                wp_die('cheatn');

            } else {

                // do something if needed
            }
        }
    }
}

This snippet has been tested on the standard woo installation 5.7.1 and works fine.

  • Related