WordPress / Woocommerce function: Add a custom column to Woocommerce Order Overview Page / A ChatGPT Experience

in #developmentlast year

Yesterday evening I faced a minor challenge with a WordPress based online store. The customer who orders in the online store has the option that his order is shipped on a certain day instead of the shipping starts immediately. We have solved the technical solution by means of a plugin, which displays an input form for a calendar in the frontend and adds the date for shipping to the meta data of the order in the database when the order is placed. Now the task was to display exactly this date in the overview page of the Woocommerce orders, so that the employee can see exactly and quickly which order has to be shipped soon.

Since there is a plugin for this at WooCommerce, which offers the solution, but costs 99 US dollars and brings far too many features than are needed at all, I have made myself on the search and searched about 15 minutes on the web for a solution. Unfortunately I didn't find any code that could help me. So I decided to ask the ChatGPT AI to help me with this problem. The result is amazing and took only one or two tries until I had fully functional code that I could simply add as a snippet on the page and did exactly what I wanted.

Here are the inputs from Chat GPT and the associated code, in case anyone also wants to add another table column with info about an order to the Woocommerce order overview page sometime:


Chat GPT AI generated Content + Code

Task:
Write me a WordPress function to specify another row with a custom value on the order overview page, where all orders can be seen.

Response:
Sure, here is an example of a WordPress function you can use to add another column on the order summary page and display custom values in it. The following function adds an additional column called "Custom Value" and displays the value of the order ID as a custom value:

function add_custom_column_to_orders($columns) {
    $columns['custom_value'] = __('Custom Value', 'text-domain');
    return $columns;
}
add_filter('manage_edit-shop_order_columns', 'add_custom_column_to_orders');

function display_custom_value_column_content($column) {
    global $post;
    if ('custom_value' === $column) {
        $order = wc_get_order($post->ID);
        echo $order->get_id(); // Here you can display the desired custom value instead of the order ID.
    }
}
add_action('manage_shop_order_posts_custom_column', 'display_custom_value_column_content');

You will need to add these functions to your functions.php file within your WordPress theme or create a separate plugin to use these functions.

Adding custom columns to other WordPress list views follows a similar pattern. For example, if you want to add an additional column to the user overview page, you will need to use manage_users_columns and manage_users_custom_column filters and actions.


Awesome, that works!

But we can do more - Bring the new Row on the fourth place in the order:

Task:
Enhance the code so that the custom value is in the fourth position in the table.

Response:
Sure, to display the custom value in the fourth position in the table, you need to change the order of the columns in the Order Summary. Here is the updated code that places the "Custom Value" column fourth in the table:

function add_custom_column_to_orders($columns) {
    // Add the "Custom Value" column in the fourth position
    $new_columns = array_slice($columns, 0, 3, true)
        + array('custom_value' => __('Custom Value', 'text-domain'))
        + array_slice($columns, 3, null, true);

    return $new_columns;
}
add_filter('manage_edit-shop_order_columns', 'add_custom_column_to_orders');

function display_custom_value_column_content($column) {
    global $post;
    if ('custom_value' === $column) {
        $order = wc_get_order($post->ID);
        echo $order->get_id(); // Here you can display the desired custom value instead of the order ID.
    }
}
add_action('manage_shop_order_posts_custom_column', 'display_custom_value_column_content');

In this updated code, the array_slice() function is used to extract the first three columns in the columns variable and reassemble them with the "Custom Value" column and the remaining columns. This ensures that the "Custom Value" column appears fourth in the table.

Hope this helps!


Awesome! I have now found out the exact SQL query using a developer plugin and asked ChatGPT to use this SQL command to get the date from the database and display it as text in the column. An example SQL query was as follows:

SELECT meta_value
FROM `WPDBPREFIX_woocommerce_order_itemmeta`
WHERE meta_key IN ('_prdd_date','_qty')
AND order_item_id = 114

That worked and I could see the date in the column. I have then still the date to the German date format by Chat GPT adapt and also two other ideas have come to my mind. Once, if the date of the shipment is in the past, the text should be strikethrough and if the date is still in the future, this should be displayed bold and green. The final version that I now have running in a version looks accordingly:

Task:
Please add me the code that the output corresponds to the date format DD.MM.YYYY: $custom_value = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id = %d AND meta_key IN ('_prdd_date','_date')", $order_item_id ) );

Task:
Thank you very much, the code works as requested. Please strike me the output as text if the shipping date is in the past.

Task:
Thanks a lot! That works. Make me the text also in bold and green if the date is still in the future.

Final Response:

function add_custom_column_to_orders($columns) {
    // Add the "Custom Value" column in the fourth position
    $new_columns = array_slice($columns, 0, 3, true)
        + array('custom_value' => __('Custom Value', 'text-domain'))
        + array_slice($columns, 3, null, true);

    return $new_columns;
}
add_filter('manage_edit-shop_order_columns', 'add_custom_column_to_orders');

function display_custom_value_column_content($column) {
    global $post, $wpdb;
    if ('custom_value' === $column) {
        $order = wc_get_order($post->ID);
        $order_item_id = $wpdb->get_var($wpdb->prepare("SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d LIMIT 1", $order->get_id()));
        $custom_value = $wpdb->get_var($wpdb->prepare("SELECT meta_value FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id = %d AND meta_key IN ('_prdd_date', '_date')", $order_item_id));
        if ($custom_value) {
            $timestamp = strtotime($custom_value);
            $formatted_date = date('d.m.Y', $timestamp);
            if ($timestamp < time()) {
                echo '<del>' . $formatted_date . '</del>';
            } else {
                echo '<span style="font-weight: bold; color: green;">' . $formatted_date . '</span>';
            }
        } else {
            echo '-';
        }
    }
}
add_action('manage_shop_order_posts_custom_column', 'display_custom_value_column_content');

And here the result in the Backend of the Onlineshop looks like expected :) The Code is only run in the Backend of the Shop.

image.png

This was the first time I used ChatGPT to create functional code. I am surprised that it was so easy and the result was exactly what I expected and everything worked on the first try. I'm curious to see where else I can use ChatGPT for coding tasks - for smaller snippets, tweaks etc. it already works very well. What I also find special is that the chat history always reacts to previous chat inputs and uses them as a basis for further discussion with the AI.

Sort:  

Ive seen more people around me use chatgpt for writing code and in general it works quite decent. surely you have to run it over, but already for inspiration its is really something that will take over. super cool!

Those AI tools are very helpful to get a lot of things done faster.

untitled.gif

Niiiice. Congrats that it works now 🙏🏼☘️✨

great job my friend.

This deserves a !BEER


Hey @louis88, here is a little bit of BEER from @detlev for you. Enjoy it!

Did you know that <a href='https://dcity.io/cityyou can use BEER at dCity game to buy cards to rule the world.