Search code examples
phpwordpresswoocommerceordershighperformance

Custom column with order metadata in WooCommerce HPOS admin orders list


Due to upgradation in woocommmerce plugin the filter by which the medium/source was shown got disappeared. I some how retrieve the column og medium/source back but my data is not populating in it. The code is totally optimized with HPOS and my code is:

This is the part that shows the column:

    public function source_medium_column($columns)
    {

        $new_columns                     = (is_array($columns)) ? $columns : array();
        $new_columns['MyPluginOne_source'] = __('Source/Medium', 'wp-MyPluginOne-woocommerce');

        return $new_columns;
    }

This is the part that shows the data for the medium/source but this part is not working:

public function source_medium_value($column, $order_id)
{
    $order = wc_get_order($order_id);

    if ($column == 'MyPluginOne_source') {

        // Check for the new meta key first
        $source = $order->get_meta('MyPluginOne_woo_order_source', true);

        if ($source) {
            echo $source;
            return;
        }

        // If the new meta key is not found, try the deprecated one
        $source_medium_deprecated = $order->get_meta('MyPluginOne_woo_single_source', true);

        if ($source_medium_deprecated) {
            echo $source_medium_deprecated;
            return;
        }

        // Fetch source/medium on request.
        if (!$source && isset($_GET['MyPluginOne_woo_fetch_sale_source'])) {
            error_log('Fetching source/medium for order ' . $order_id);

            $post_date  = get_the_date('Y-m-d', $order->get_id());
            $start_date = date('Y-m-d', strtotime($post_date . ' - 5 days'));
            $end_date   = date('Y-m-d', strtotime($post_date . ' + 5 days'));

            // Get sources from ga4.
            if (method_exists('WPMyPluginOne_Utils', 'get_ga_mode') && 'ga4' === WPMyPluginOne_Utils::get_ga_mode()) {
                $stats = $GLOBALS['WP_MyPluginOne']->get_reports(
                    'MyPluginOne_woo_order_source',
                    array(),
                    array(
                        'start' => $start_date,
                        'end'   => $end_date
                    ),
                    array(
                        'sourceMedium',
                        'transactionId',
                    ),
                    array(),
                    array(
                        'logic' => 'AND',
                        'filters' => array(
                            array(
                                'type' => 'dimension',
                                'name' => 'transactionId',
                                'match_type' => 1,
                                'value'      => $order->get_id()
                            )
                        )
                    ),
                    0,
                    false
                );
                error_log('Stats: ' . print_r($stats, true));
                if (!empty($stats['rows'][0]['sourceMedium'])) {
                    $order->update_meta_data('MyPluginOne_woo_order_source', $stats['rows'][0]['sourceMedium']);
                    $source = $stats['rows'][0]['sourceMedium'];
                }
            } else {
                $stats = $GLOBALS['WP_MyPluginOne']->pa_get_analytics_dashboard('ga:totalEvents', $start_date, $end_date, 'ga:sourceMedium,ga:eventCategory,ga:eventLabel', false, 'ga:eventCategory==MyPluginOne_orders;ga:eventAction==order_created;ga:eventLabel==' . $post->ID);

                if (isset($stats['rows'][0][0])) {
                    $source = $stats['rows'][0][0];
                    $order->update_meta_data('MyPluginOne_woo_order_source', $source);
                }
            }
        }
        error_log('Final source: ' . $source);
        echo $source;
    }
}

The hooks are:

add_filter('manage_woocommerce_page_wc-orders_columns', array($this, 'source_medium_column'));
add_action('manage_woocommerce_page_wc-orders_custom_column', array($this, 'source_medium_value'),10,2);

My previous code was not compatabile with HPOS. I did a that compatabaility by looking to the documentation but the source/medium is still not showing up. And I now just want to know from where I am doing mistake.


Solution

  • Important note: WooCommerce HPOS requires that all WC Order metadata has been set using CRUD methods (not WordPress post meta functions). Only WooCommerce related setter methods will populate WooCommerce custom database tables used by HPOS.

    As you are using WC Order custom fields and foreign Classes / methods, I can't really test your code from the 2nd function.

    Now, for manage_woocommerce_page_wc-orders_custom_column hook, the 2 available arguments are $column and $order (but not $order_id), so I have revised your code below:

    public function source_medium_column( $columns ) {
        $columns['analytify_source'] = __('Source/Medium', 'wp-analytify-woocommerce');
        return $columns;
    }
    
    public function source_medium_value( $column, $order )
    {
        if ($column === 'analytify_source') {
    
            // Check for the new meta key first
            $source = $order->get_meta('analytify_woo_order_source');
    
            if ( $source ) {
                echo $source; return;
            }
    
            // If the new meta key is not found, try the deprecated one
            $source_medium_deprecated = $order->get_meta('analytify_woo_single_source');
    
            if ( $source_medium_deprecated ) {
                echo $source_medium_deprecated; return;
            }
    
            // Fetch source/medium on request.
            if ( ! $source && isset($_GET['analytify_woo_fetch_sale_source']) ) {
                error_log('Fetching source/medium for order ' . $order->get_id());
    
                $date_created = $order->get_date_created()->format('Y-m-d');
                $start_date   = date('Y-m-d', strtotime($date_created . ' - 5 days'));
                $end_date     = date('Y-m-d', strtotime($date_created . ' + 5 days'));
    
                // Get sources from ga4.
                if (method_exists('WPANALYTIFY_Utils', 'get_ga_mode') && 'ga4' === WPANALYTIFY_Utils::get_ga_mode()) {
                    $stats = $GLOBALS['WP_ANALYTIFY']->get_reports(
                        'analytify_woo_order_source',
                        array(),
                        array(
                            'start' => $start_date,
                            'end'   => $end_date
                        ),
                        array(
                            'sourceMedium',
                            'transactionId',
                        ),
                        array(),
                        array(
                            'logic' => 'AND',
                            'filters' => array(
                                array(
                                    'type' => 'dimension',
                                    'name' => 'transactionId',
                                    'match_type' => 1,
                                    'value'      => $order->get_id()
                                )
                            )
                        ),
                        0,
                        false
                    );
                    error_log('Stats: ' . print_r($stats, true));
                    
                    if (!empty($stats['rows'][0]['sourceMedium'])) {
                        $source = $stats['rows'][0]['sourceMedium'];
                        $order->update_meta_data('analytify_woo_order_source', $source);
                        $order->save();
                    }
                } else {
                    $stats = $GLOBALS['WP_ANALYTIFY']->pa_get_analytics_dashboard('ga:totalEvents', $start_date, $end_date, 'ga:sourceMedium,ga:eventCategory,ga:eventLabel', false, 'ga:eventCategory==analytify_orders;ga:eventAction==order_created;ga:eventLabel==' . $order->get_id());
    
                    if (isset($stats['rows'][0][0])) {
                        $source = $stats['rows'][0][0];
                        $order->update_meta_data('analytify_woo_order_source', $source);
                        $order->save();
                    }
                }
            }
            error_log('Final source: ' . $source);
            echo $source;
        }
    }
    

    And keep the following as it is:

    add_filter('manage_woocommerce_page_wc-orders_columns', array($this, 'source_medium_column'));
    add_action('manage_woocommerce_page_wc-orders_custom_column', array($this, 'source_medium_value'), 10, 2);
    

    It should work (untested).

    Related: Add columns to admin orders list in WooCommerce (+ HPOS)