Created
August 29, 2024 12:18
-
-
Save nreljed/07a665f5c5407c5a36f0640877d47d10 to your computer and use it in GitHub Desktop.
This file contains 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 | |
/** | |
* Restricts product attachment selection to the current post in the media library | |
* | |
* This function modifies the attachment query arguments to only show attachments | |
* associated with the current product being edited. | |
* | |
* @param array $query The current attachment query arguments. | |
* @return array The modified attachment query arguments. | |
*/ | |
function restrict_product_attachment_to_current_post($query) { | |
// 1. Validate user permissions (unchanged) | |
if (!current_user_can('upload_files')) { | |
wp_send_json_error(); | |
} | |
// 2. Ensure a valid post ID is provided (unchanged) | |
if (!isset($_REQUEST['post_id'])) { | |
wp_send_json_error(); | |
} | |
// 3. Retrieve the post object (unchanged) | |
$post = get_post((int)$_REQUEST['post_id']); | |
if (!$post instanceof \WP_Post) { | |
return $query; | |
} | |
// 4. Restrict to WooCommerce product posts and their variations | |
if ($post->post_type !== 'product' && $post->post_type !== 'product_variation') { | |
return $query; | |
} | |
// 5. Filter by post parent (product) or post ID (variation) | |
$query['post_parent'] = ($post->post_type === 'product') ? $post->ID : $post->post_parent; | |
return $query; | |
} | |
add_filter('ajax_query_attachments_args', 'restrict_product_attachment_to_current_post'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment