Untitled
unknown
plain_text
8 months ago
2.9 kB
6
Indexable
// Display the custom order number field in the product edit page
add_action('marketking_edit_product_after_tags', function($post) {
$product_id = $post->ID;
$order_number = get_post_meta($product_id, '_custom_order_number', true);
?>
<div class="col-xxl-12 col-md-12 marketking_card_gal_cat_tags" style="background: white; padding:20px;border-radius: 4px;">
<div class="custom-order-field">
<label for="custom_order_number"><strong><?php _e('Sort Number', 'marketking'); ?></strong></label>
<input type="number" id="custom_order_number" name="custom_order_number" value="<?php echo esc_attr($order_number); ?>" min="0" step="1">
<p class="description"><?php _e('Configure a sort number for this product to control the order in which it is shown in your shop (optional).', 'marketking'); ?></p>
</div>
</div>
<?php
});
// Save the custom order number when the product is saved
add_action('marketking_after_save_product', function($product_id, $vendor_id) {
// Check if our custom field was submitted
if (isset($_POST['custom_order_number'])) {
// Sanitize the input
$order_number = absint($_POST['custom_order_number']);
// Update the post meta
update_post_meta($product_id, '_custom_order_number', $order_number);
}
}, 10, 2);
add_filter('woocommerce_shortcode_products_query', function($query_args, $atts, $shortcode_name) {
add_filter('posts_clauses', function($clauses) {
global $wpdb;
// This creates a custom ORDER BY that puts products with _custom_order_number first
// and sorts them by that value in DESCENDING order (higher numbers first)
$clauses['orderby'] = "
CASE WHEN {$wpdb->postmeta}.meta_key = '_custom_order_number' THEN 0 ELSE 1 END ASC,
CASE WHEN {$wpdb->postmeta}.meta_key = '_custom_order_number'
THEN CAST({$wpdb->postmeta}.meta_value AS SIGNED)
ELSE -1 END DESC,
{$wpdb->posts}.post_title ASC
";
// Make sure we're joining the postmeta table
$clauses['join'] .= " LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_custom_order_number'";
// Group by post ID to avoid duplicates
$clauses['groupby'] = "{$wpdb->posts}.ID";
return $clauses;
}, 10);
// Remove the filter after the query runs (to avoid affecting other queries)
add_action('pre_get_posts', function() {
add_action('posts_selection', function() {
remove_all_filters('posts_clauses', 10);
});
});
// Remove default orderby parameters to avoid conflicts
unset($query_args['orderby']);
unset($query_args['order']);
unset($query_args['meta_key']);
return $query_args;
}, 10, 3);Editor is loading...
Leave a Comment