fbpx

Introduction

The purpose of this developer guide for addons is to show how to add your own discount to the Conditional Discounts for WooCommerce plugin. It is important to understand the use or operation of the Conditional Discounts for WooCommerce plugin before reading and practicalizing this documentation.

Before starting it is also essential to define what a hook is. In the WordPress ecosystem, a hook is a means of modifying and/or interacting with another code at a specific time. There are two types of hooks: actions that allow you to add data or modify the way WordPress works; and filters that allow you to modify the data (variables) of specific functions.

The Conditional Discounts for WooCommerce plugin contains several hooks which you can add to, or manipulate, to create your own discounts. We are going to study them (filters in this case) in the following order:

  • wad_get_discounts_conditions
  • wad_fields_values_match
  • Wad_operators_fields_match
  • wad_is_rule_valid

 

  1. wad_get_discounts_conditions: allows you to modify the list of existing conditions or to add new ones.
  2. wad_fields_values_match: is used to define the list of values ​​available for the condition created using wad_get_discounts_conditions.
  3. wad_operators_fields_match: allows you to define the type of operator which will be used for your discount.
    For example, to verify that a condition belongs to a predefined list we use the operators “IN” and “NOT IN”. In the case of a numerical comparison, we expect the use of operators like superior (>), superior or equal (> =), inferior or equal (<=), inferior or (<), equal ( =) …
    These are the default operators of our Conditional Discounts for WooCommerce plugin.

 

How to add Operators

We can add our own operators. The format for creating an operator is simple and is as follows:

	$arrays_operators = array(
           'KEY1'     =>'VALUE SHOW1',
           'KEY2'     =>'VALUE SHOW2',
       );

	

We create an associative array in which we put the key of our operator and the value that will be displayed for this operator. An application of the previous rule will give the following:

Example 1:

$arrays_operators        = array(
           'IN'     => __( 'IN', 'wad' ),
           'NOT IN' => __( 'NOT IN', 'wad' ),
       );

Example 2:

 
$number_operators        = array(
           '<'  => __( 'is less than', 'wad' ),
           '<=' => __( 'is less or equal to', 'wad' ),
           '==' => __( 'equals', 'wad' ),
           '>'  => __( 'is more than', 'wad' ),
           '> =' => __( 'is more or equal to', 'wad' ),
           '%'  => __( 'is a multiple of', 'wad' ),
       );

So we can create our own operators by following the same rule thanks to the “wad_operators_fields_match” filter. In the application example (the second part of this document) a complete use of the filter was made and demonstrated.

Developer guide for addons
Rules explained

Another simple example, the “if customer role in” rule is associated with a field which contains a dropdown containing the list of existing roles on WordPress. The following image illustrates the example:

1: We have added the condition ‘if customer role’ thanks to the ‘wad_get_discounts_conditions’ filter.
2: We added the type of operator that we want to use, it is ‘IN’ and ‘NOT IN’ thanks to the ‘wad_operators_fields_match’ filter.
3: These are the values ​​that will be associated with our condition, we added them using the ‘wad_fields_values_match’ filter.

  1.  wad_is_rule_valid: this filter allows you to evaluate a condition before applying it or not.  For example, to check if an expression “A = B” is true before applying our reduction in price, we need the ‘wad_is_rule_valid’ filter. ‘A’ represents the condition defined by the administrator in the administration space while ‘B’ represents the second expression which will be compared with ‘A’ and therefore ‘B’ will be recovered thanks to a function that we will write ourselves and ‘A’ will be recovered by the parameter ‘$ rule’ of ‘wad_is_rule_valid’.

Application

We are going to create a discount which lets us reduce the price for a user based on whether he already benefited from certain discounts, which we will define in a list.

Steps

  1. We will first add our discount to the list of rules, using the “wad_get_discounts_conditions” filter.
    First, we add the filter:

     
    add_filter( 'wad_get_discounts_conditions', 'add_my_custom_condition', 10 );
    
    

    Then we add the callback function linked to this filter:

     
       / **
        * This function allows us to add our condition.
        *
        * @param type $ arrays contains all conditions.
        * @return type
        * /
      function add_my_custom_condition( $arrays ) {
           $arrays['has-discount'] = __( 'If Customer has benefited a discount', 'wad' );
           return $arrays;
       }
     
    
    

    By so doing, we have added our “has-discount” discount to the list of rules.

  2. The next step is to add the list of values that can be associated with the discount we just created. We do this by using the ‘wad_fields_values_match’ filter.
    First, we call the filter:

    add_filter('wad_fields_values_match', 'add_available_option_for_my_custom_condition', 10, 3);
    
    

    Then we call the callback function linked to the filter:

     
       / **
        * This function adds the options that are available for our condition.
        * @param array $ arr contains all available options for each condition.
        * @param type  $ condition contains the condition (or the designation of the discount).
        * @param type  $ selected_value contains options that have been selected for the condition ???.
        * @return type
        * /
      function add_available_option_for_my_custom_condition( $arr, $condition, $selected_value ) {
           $field_name = 'o-discount [rules] [{rule-group}] [{rule-index}] [value]';// the value of the name attribute of the select field
               $discounts_title      = wad_get_all_discounts_post_title();
               $discount_get_select = get_wad_html_select( $field_name . '[]', false, '', $discounts_title, $selected_value, true );// get_wad_html_select allows you to create a select type field with the parameters given to it; the square brackets ([]) mean that it is a multiple field, if they are not put then a single field will be rendered.
     
               $arr['has-discount'] = $discount_get_select;
           return $arr;
       }
     
       / **
        * This function return all discounts title
        * @return array
        * /
      function wad_get_all_discounts_post_title() {
           $all_discounts   = wad_get_all_discounts();// we retrieve all discounts. it is a wad's function.
           $discounts_title = array();
           foreach ( $all_discounts as $key => $value ) {
               $discounts_title[ $value->ID ] = $value->post_title;
           }
           return $discounts_title;
       }
    
    
  3. The next step is to add our operators using the ‘wad_operators_fields_match’ filter. These operators will link our discount to the values we added previously:
          add_filter('wad_operators_fields_match', 'add_comparison_operators_for_my_custom_condition', 10, 3);
    
    

    Then

     
       / **
        * This function allows us to associate comparison operators to our condition.
        *
        * @param type $ arrays contains the operators associated with each condition.
        * @param type $ condition contains the condition (or the designation of the discount).
        * @param type $ selected_value contains the operator currently active.
        * @return type
        * /
      function add_comparison_operators_for_my_custom_condition( $arrays, $condition, $selected_value ) {
           $field_name  = 'o-discount [rules] [{rule-group}] [{rule-index}] [operator]';
           $arrays_operators   = array(
               'IN'     => __( 'IN', 'wad' ),
               'NOT IN' => __( 'NOT IN', 'wad' ),
           );
               $arrays_operators_select = get_wad_html_select( $field_name, false, '', $arrays_operators, $selected_value );// get_wad_html_select allows you to create a select type field with the parameters given to it. it's wad's function.
               $arrays['has-discount'] = $arrays_operators_select;
           return $arrays;
       }
    
  4. Finally, we will put in measures to apply our discount after checking that the rules defined the match. We will use the ‘wad_is_rule_valid’ filter to achieve this:
        add_filter('wad_is_rule_valid', 'is_rule_valid', 10, 2);
    
    

    Then

     / **
        * Description
        *
        * @param type $ is_valid after having compared the rules defined in the dashboard and the evaluable condition this boolean allows to say if the rule is valid or not.
        * @param type $ rule comment contains the rules defined in the dashboard.
        * @return type
        * /
      function is_rule_valid( $is_valid, $rule ) {
           $condition = get_all_discounts_customer_has_benefited(); // we recover the discounts from which the customer has benefited and we compare it to the rules defined in the dashboard according to the operators.
     
           if ( 'has-discount' === $rule['condition']) {
     
               $intersection = array_intersect( $rule['value'], $condition );
               if (( 'NOT IN' == $rule['operator'] && $rule['value']! == $intersection ) ||
                           ( 'IN' === $rule['operator'] && $rule['value'] === $intersection )) {
                   $is_valid = true;
               }
           }
           return $is_valid;
       }
     
      
     
     
     
     / **
        * This function recovers all the reductions from which the client has benefited, this will be the evaluable condition that will be used in is_rule_valid function to evaluate our discount.
        *
        * @return array
        * /
      function get_all_discounts_customer_has_benefited() {
           // Get all customer orders.
           $customer_orders = get_posts(
               array(
                   'numberposts' => -1,
                   'meta_key'    => '_customer_user',
                   'orderby'     => 'date',
                   'order'       => 'DESC',
                   'meta_value'  => get_current_user_id(),
                   'post_type'   => wc_get_order_types(),
                   'post_status' => array_keys( wc_get_order_statuses()),
                   'post_status' => array( 'wc-processing' ),
               )
           );
           // get a discount that user have benefitted.
           $customer_discount_id = array();
           foreach ( $customer_orders as $customer_order ) {
               $order_data                 = wc_get_order( $customer_order );// we get the data on each customer's order.
               $customer_discount_id[] = get_post_meta( $order_data->get_id(), $key = 'wad_used_discount', true );// get discount that customer has benefited id.
           }
           return $customer_discount_id;
       }
    

    In reference to the example scenario mentioned earlier in this tutorial, we have been able to achieve the equation: A = B.
    In this context, the function allows us to recover B (all the discounts from which the user has benefited) via the ‘get_my_evaluable_condition’ function, and A (the condition established in the dashboard by the administrator) via the ‘is_rule_valid’ function using the ‘$rule’ parameter.
    Got any questions about this developer guide for addons to our Conditional Discounts for WooCommerce plugin? Please reach out to us via Chat!

7 comments

  1. Din Cheung

    I want to Create a Rule on the Advertising Plan is Select the Any Route that Request without the Quantity Limitation. And Quantity is for the Unit of Package.

    Looking Forward to Hearing your reply.

    August 4, 2020 at 3:48 am
    Reply
    • Hermann

      Hello,
      I’m not sure I understand the context. Are you referring to woocommerce products?

      August 4, 2020 at 7:45 am
      Reply
  2. Lori

    I would like to create a filter checking if there is a subscription in the cart using WC_Subscriptions_Cart::cart_contains_subscription()

    Would someone be able to help me with this?

    August 17, 2020 at 7:10 pm
    Reply
    • Hermann

      Hello Lori,
      Can you provide more details?

      August 18, 2020 at 4:34 am
      Reply
  3. Adrian

    Hey, the plugin is really awesome, i love it, but one question, i need to make a shortcode or something like this, for show ONLY the products with discounts available for the user, could be possible? how? with the meta_key for wp_query is possible? thank you so much.

    September 10, 2020 at 5:03 am
    Reply
    • Hermann

      Hello,
      Thank you for your review. The shortcode part is tricky because the discounts are applied depending on the conditions the store manager set and the customer profile or actions. So unfortunately we did not develop that part yet.

      September 10, 2020 at 5:24 am
      Reply
      • Adrian

        Well nice, thank you!

        I think i can develop it trying to get the active discounts and then the products lists, with this try to get the IDs and make a query for the products. I gonna try to find the way with the functions of the plugin, if you have some information about it and what functions can help me, but anyways thank you for answering and for the plugin development.

        September 11, 2020 at 10:25 pm
        Reply

Leave a comment

Your email address will not be published. Required fields are marked *