2016-04-21 7 views
1

Мой сайт использует wordpress, плагин «Календарь событий» и «woocommerce», и я управляю ролями и возможностями с помощью плагина «Advanced Access Manager».Добавить capabilitie в клиентов по категории товаров

Я пытаюсь добавить функцию, которая добавит возможность роли покупателя в зависимости от категории продукта, которую они только что купили.

Итак, я пытаюсь получить продукт (только что купленный) или категорию события из идентификатора пользователя, но что-то идет не так, и его практически невозможно протестировать шаг за шагом, потому что процесс должен быть завершен, чтобы позволить функция работает.

Вот код:

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; 
} 

Так, например, клиент купить продукт с категорией «course_paris_night» и поэтому он должен иметь возможность роли «course_paris_night». С этой возможностью этот клиент будет обращаться к учебнику по одной и той же категории на примере.

Спасибо за любую помощь по коду или на пути к его тестированию! (необходимо изучить!)

SO !!! 24 апреля ... несколько дней спустя:

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; 
    } 
} 

Но у меня нет хороших результатов. Поэтому тестирование снова здесь это то, что я получаю имеет информацию о пользователе:

WP_User Object 
(
[data] => stdClass Object 
    (
     [ID] => 50 
     [user_login] => buyer.new 
     [user_pass] => $P$BKlx7.CzfvnLL43EZaZdmo84shZQo41 
     [user_nicename] => buyer-new 
     [user_email] => [email protected] 
     [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 уже мой пользователь покупал два новых курса по категории «mycourse Saint-Malo intermédiaire» и «mycourse париж Avance» Я должен иметь под «[ role] => Array "две новые роли ... но вы можете видеть, что это не так.

Мой код добавляет две новые роли в [caps] и [allcaps], но не в [роли] !!!!

Я уверен, что я очень близко. Есть идеи ?

// ОБНОВЛЕНИЕ //

Извините! Я забыл некоторые важные шаги, и я, наконец, выяснить, что не работает в тестовом коде (я Протестируйте его непосредственно на странице не в зависимости ... сделаю это завтра ... вот это 2,3 ат)

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; 
} 
} 
} 
+0

Мне нелегко следовать именно то, что вы просите, если честно с тобой –

+0

это то, что я понимаю. После того как клиент выполнит свой заказ, вы хотели бы создать для них учетную запись и иметь свою роль на основе категории приобретенного продукта. И эта роль напрямую связана с категорией учебника с тем же именем. – imvain2

+0

Предположим, вы хотите ограничить учебное пособие тем людям, которые купили ваш курс, но вы хотите, чтобы они имели доступ только к учебнику, соответствующему категории продукта, который они покупают: например: я покупаю курс «базовый», поэтому я могу получить доступ к " базовый "учебник, а не" продвинутый ". (с помощью плагина для управления доступом на основе возможностей пользователя и возможностей пользователя). Таким образом, клиент регистрируется как «роль клиента» и не имеет доступа к «базовому учебному курсу», потому что для этого ему нужно «базовое» в качестве capabilitie. –

ответ

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; 
} 
} 

... да ... но! при редактировании и анализе в моих функциях под моей дочерней темой он этого не делает. Иногда это обрабатывает его, потому что последнее эхо появляется (иногда) и возвращает мне правильную «роль для создания».

Вот это тот же самый код, но строить будет включать в 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; 
} 

И есть вы можете себе представить, чтобы проверить его, это не так просто, потому что я должен сделать процесс оплаты.

Любая ошибка, которую я допускаю где-нибудь? Я этого не вижу.

+0

РАБОЧЕЕ РЕШЕНИЕ: ... он не работает в функции моей дочерней темы, поэтому я помещаю его в обычную «thankyou.php» в мою дочернюю тему, и теперь он работает на 100%. Если вы хотите использовать его для своего приложения, просто укажите способ, которым я обрабатываю имя роли и категории. Код не является чистым кодом, и если кто-нибудь найдет способ его очистить и заставить его работать как функция ... дайте мне знать. –

+0

Не забудьте сохранить свой php как UTF8 NO BOM ;-) –

 Смежные вопросы

  • Нет связанных вопросов^_^