Last active
October 1, 2022 08:17
-
-
Save FrancoStino/f65fe58368b392922f418832b960a00c to your computer and use it in GitHub Desktop.
Register a new column that will show if an order was a first order for a customer - Woocommerce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Register a new column that will show if an order was a first order for a customer | |
add_filter( 'manage_edit-shop_order_columns', 'register_is_first_order_column', 10, 1 ); | |
function register_is_first_order_column( $columns ) { | |
$columns['is_first_order'] = 'Primo ordine'; | |
return $columns; | |
} | |
// Show a checkmark emoji in the column if it's true | |
add_action( 'manage_shop_order_posts_custom_column', 'display_is_first_order_column', 10, 1 ); | |
function display_is_first_order_column( $column ) { | |
global $post; | |
if ( 'is_first_order' === $column ) { | |
$is_first_order = get_post_meta( $post->ID, 'is_first_order', true ); | |
if ( false !== $is_first_order && strlen( $is_first_order ) > 0 ) { | |
echo "✔️"; | |
} | |
} | |
} | |
// Display our custom checkbox near the default WooCommerce filter options | |
add_action( 'restrict_manage_posts', 'show_is_first_order_checkbox' ); | |
function show_is_first_order_checkbox() { | |
?> | |
<label> | |
Solo i primi ordini | |
<input type="checkbox" name="is_first_order" id="is_first_order" <?php echo isset( $_GET['is_first_order'] ) ? 'checked' : ''; ?>> | |
</label> | |
<?php | |
} | |
// Modify a query if the checkbox was checked | |
add_action( 'pre_get_posts', 'filter_woocommerce_orders_in_the_table', 99, 1 ); | |
function filter_woocommerce_orders_in_the_table( $query ) { | |
if ( ! is_admin() ) { | |
return; | |
} | |
global $pagenow; | |
if ( 'edit.php' === $pagenow && 'shop_order' === $query->query['post_type'] ) { | |
// We don't need to modify a query if a checkbox wasn't checked | |
if ( ! isset( $_GET['is_first_order'] ) ) { | |
return $query; | |
} | |
$meta_query = array( | |
array( | |
'key' => 'is_first_order', | |
'value' => 1, | |
'compare' => '=' | |
) | |
); | |
$query->set( 'meta_query', $meta_query ); | |
} | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment