add capabilitie to customer based on product categorie

时间:2016-04-21 22:09:50

标签: php woocommerce categories product role

My website is using wordpress, "the events calendar" plugin and "woocommerce" and I manage roles and capabilities with "Advanced Access Manager" plugin.

I try to add a function that will add a capability to the role of a buyer based on the product category they have just bought.

So I try to get the product (just bought) or the event category from the user ID, but something is going wrong and it's almost impossible to test step by step, because the process need to be finish to let the function work.

Here is the code:

add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);

function custom_process_order($order_id) {
    $order = new WC_Order( $order_id );
    $myuser_id = (int)$order->user_id;
    $user_info = get_userdata($myuser_id);
    $items = $order->get_items();

    // need to test that :

    $beta= str_replace(
        ':',
        '',
        tribe_get_event_categories($event->ID, array(
            'echo'         => false,
            'label'        => '',
            ' label_before' => '',
            'label_after'  => '',
            'wrap_before'  => '',
            'wrap_after'   => '',
    )));
    $beta = strip_tags($beta);

    foreach ($items as $item) {

        //check if user already have capabilitie
        if ( ! user_can( $user_id, $capability )){

            //add capability to specific user
            $user = new WP_User( $user_id );
            $user->add_cap( $beta );
        }
    }
    return $order_id;
}

So for example a customer buy a product with the category "course_paris_night" and so it should have the role capability "course_paris_night". With that capability this customer will access tutorial on the same category by example.

Thanks for any help on the code or on the way to test it ! (need to learn !)

SO !!! 24 April...few days later :

add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);

function custom_process_order($order_id) {
    global $current_user;
    global $wp_roles;

    $order = new WC_Order($item->ID);

    $order->populate($item);        
    $items = $order->get_items();

    foreach ($items as $key => $item2 ) :
        $event_id_in_product = absint($item2['product_id']);
    endforeach;

    // trouve la catégorie du produit acheté par le stagiaire
    // Get all terms associated with post in woocommerce's taxonomy 'product_cat'
    $terms = get_the_terms( $event_id_in_product, 'product_cat' );

    //Get an array of their IDs
    $term_ids = wp_list_pluck($terms,'term_id');

    //Get array of parents - 0 is not a parent
    $parents = array_filter(wp_list_pluck($terms,'parent'));

    //Get array of IDs of terms which are not parents.
    $term_ids_not_parents = array_diff($term_ids, $parents);

    //Get corresponding term objects.
    $terms_not_parents = array_intersect_key($terms, $term_ids_not_parents);

    //Extract the name of the category from the array and post it.
    foreach($terms_not_parents as $term_not_parent){
        $beta = $term_not_parent->name;

        $alpha = strip_tags($beta);
        $alpha = trim(strip_tags($alpha));
        $alpha = str_replace(' - ',' ',$alpha);
        $alpha = strtolower($alpha);


        $all_roles = $wp_roles->roles;
        $user = new WP_User( $current_user->ID );
        $result = $user->add_role($alpha);

        return $order_id;
    }
}

But I don't get any good results. So testing again here it is what I get has user info:

WP_User Object
(
[data] => stdClass Object
    (
        [ID] => 50
        [user_login] => buyer.new
        [user_pass] => $P$BKlx7.CzfvnLL43EZaZdmo84shZQo41
        [user_nicename] => buyer-new
        [user_email] => mymail@mysite.com
        [user_url] => 
        [user_registered] => 2016-04-23 22:05:27
        [user_activation_key] => 
        [user_status] => 0
        [display_name] => New
    )

[ID] => 50
[caps] => Array
    (
        [mycourse saint-malo intermédiaire] => 1
        [mycourse paris avancé] => 1
    )

[cap_key] => lep_capabilities
[roles] => Array
    (
        [0] => mycourse saint-malo intermédiaire
    )

[allcaps] => Array
    (
        [read] => 1
        [level_0] => 1
        [read_private_tribe_organizers] => 1
        [mycourse saint-malo intermédiaire] => 1
        [mycourse paris avancé] => 1
    )

[filter] => 
)

Normaly has my user was buying two new course under category "mycourse saint-malo intermédiaire" and "mycourse paris avancé" I should have under "[roles] => Array" the two new roles ...but has you can see it's not.

My code is adding the two new role into [caps] and [allcaps] but not into [roles] !!!!

I am sure I am very close. Any idea ?

//UPDATE//

Sorry !!! I forgot some important steps and I finally discover what was not working in my test code (I Test it directly on a page not in a function...will do that tomorrow...here it's 2.3 am)

add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);

function custom_process_order($order_id) {
    global $current_user;
    global $wp_roles;

    $all_orders = get_posts( array(
    'numberposts' => -1,
        //'meta_key'    => '_customer_user',
        //'meta_value'  => get_current_user_id(),
        'post_type'   => 'shop_order',
    'post_status' => 'completed',
    ) );

    $args = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(),
    'post_type'   => 'shop_order',
    'post_status' => 'completed',
    ) );

if( ! empty($args)){
foreach($args as $item) {
    setup_postdata( $item );

 $order = new WC_Order($item->ID);

$order->populate($item);        
$items = $order->get_items();

foreach ($items as $key => $item2 ) :
    $event_id_in_product = absint($item2['product_id']);
    endforeach;

      //trouve la catégorie du produit acheté par le stagiaire
    //Get all terms associated with post in woocommerce's taxonomy 'product_cat'
    $terms = get_the_terms( $event_id_in_product, 'product_cat' );

    //Get an array of their IDs
    $term_ids = wp_list_pluck($terms,'term_id');

    //Get array of parents - 0 is not a parent
    $parents = array_filter(wp_list_pluck($terms,'parent'));

    //Get array of IDs of terms which are not parents.
    $term_ids_not_parents = array_diff($term_ids, $parents);

    //Get corresponding term objects.
    $terms_not_parents = array_intersect_key($terms, $term_ids_not_parents);

    //Extract the name of the category from the array and post it.
    foreach($terms_not_parents as $term_not_parent){
        $beta = $term_not_parent->name;

    $alpha = strip_tags($beta);
    $alpha = trim(strip_tags($alpha));
    $alpha = str_replace(' - ',' ',$alpha);
    $alpha = str_replace('Stage','stagiaire',$alpha);
    $alpha = strtolower($alpha);


$all_roles = $wp_roles->roles;
    $user = new WP_User( $current_user->ID );
    $result = $user->add_role($alpha, $alpha, array($alpha =>true,)); // Array was missing in previous version !

return $order_id;
}
}
}

1 个答案:

答案 0 :(得分:0)

这是解决方案,它在我的测试页面下工作得很好但是......

// Retrieve customer order
$blc_args = get_posts( array('numberposts' => -1,'meta_key'    =>'_customer_user','meta_value'  => get_current_user_id(),'post_type'   => 'shop_order','post_status' => 'completed',) );

if( ! empty($blc_args)){
foreach($blc_args as $blc_item) {
    setup_postdata( $item );

    $blc_order = new WC_Order($blc_item->ID);

    $blc_order->populate($blc_item);

    $blc_items = $blc_order->get_items();

    foreach ($blc_items as $blc_key => $blc_item2 ) :
    //print_r($item2);
    $event_id_in_product = absint($blc_item2['product_id']);

    //Get all terms associated with post in woocommerce's taxonomy 'product_cat'
    $blc_terms = get_the_terms( $event_id_in_product, 'product_cat' );

    //echo"</br>";
    //echo "Event ID embed in product bought : " . $event_id_in_product;
    //echo"</br>";

    //Get an array of their IDs
    $blc_term_ids = wp_list_pluck($blc_terms,'term_id');

    //Get array of parents - 0 is not a parent
    $blc_parents = array_filter(wp_list_pluck($blc_terms,'parent'));

    //Get array of IDs of terms which are not parents.
    $blc_term_ids_not_parents = array_diff($blc_term_ids, $blc_parents);

    //Get corresponding term objects.
    $blc_terms_not_parents = array_intersect_key($blc_terms, $blc_term_ids_not_parents);

    //Extract the name of the category from the array and post it.
    foreach($blc_terms_not_parents as $blc_term_not_parent){
        $blc_start = $blc_term_not_parent->name;
    }

    if(preg_match("/(Ultérieure|cadeau)/i", $blc_start)){

    }else{
        $beta = utf8_decode($blc_start);
        $beta = trim(strip_tags($beta));
        $beta_without_accent = strtr($beta, utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'), 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
        $beta_with_minuscule = strtolower($beta_without_accent);
        $beta_with_minuscule = str_replace('balade - ','stagiaire_',$beta_with_minuscule);
        $beta_with_underscore = str_replace(' - ', '_', $beta_with_minuscule);
        $beta_stagiaire = str_replace('stage','stagiaire',$beta_with_underscore);

        global $current_user;

        $user = new WP_User( $current_user->ID );
        $user->add_role($beta_stagiaire);
    }
    endforeach;
}
}

......是的......但是!在我的子主题下编辑和解析我的函数时,它没有做到。有时它似乎处理它,因为最后的回声出现(有时)并向我发回正确的#34;角色来创建&#34;。

这里是相同的代码,但构建要包含在function.php中:

add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);

function custom_process_order($order_id) {
    global $current_user;

    $order = wc_get_order( $order_id );
    $items = $order->get_items();

//      echo"</br>";
//      echo "Product ID : " . ($order->id);

    //$order->populate($item);
     //print_r($order);

    $items = $order->get_items();

    foreach ($items as $key => $item2 ) :
    //print_r($item2);
    $event_id_in_product = absint($item2['product_id']);

    //Get all terms associated with post in woocommerce's taxonomy 'product_cat'
    $terms = get_the_terms( $event_id_in_product, 'product_cat' );

    //echo"</br>";
    //echo "Event ID embed in product bought : " . $event_id_in_product;
    //echo"</br>";

    //Get an array of their IDs
    $term_ids = wp_list_pluck($terms,'term_id');

    //Get array of parents - 0 is not a parent
    $parents = array_filter(wp_list_pluck($terms,'parent'));

    //Get array of IDs of terms which are not parents.
    $term_ids_not_parents = array_diff($term_ids, $parents);

    //Get corresponding term objects.
    $terms_not_parents = array_intersect_key($terms, $term_ids_not_parents);

    //Extract the name of the category from the array and post it.
    foreach($terms_not_parents as $term_not_parent){
        $start = $term_not_parent->name;            
    }

    //echo"</br>";
    //echo "Product Category : " . $start;
    //echo"</br>";

    if(preg_match("/(Ultérieure|cadeau)/i", $start)){
//echo"</br>";
    //echo "Don't add that Product Category : " . $start;
    //echo"</br>";
    }else{
    $beta = utf8_decode($start);
    $beta = trim(strip_tags($beta));
    $beta_without_accent = strtr($beta, utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'), 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
    $beta_with_minuscule = strtolower($beta_without_accent);
    $beta_with_minuscule = str_replace('balade - ','stagiaire_',$beta_with_minuscule);
    $beta_with_underscore = str_replace(' - ', '_', $beta_with_minuscule);
    $beta_stagiaire = str_replace('stage','stagiaire',$beta_with_underscore);

    echo"</br>";
    echo "Role to create : " . $beta_stagiaire;
    echo"</br>";

    $user = new WP_User( $current_user->ID );

    $user->add_role($beta_stagiaire);
    }
    endforeach;


return $order_id;
 }

你可以想象一下测试它并不容易,因为我必须进行支付过程。

我在某处发生任何错误?我没有看到它。