wc_product_attach_featured_image()
Attach product featured image. Use image filename to match a product sku when product is not provided.
No Hooks.
Returns
null. Nothing (null).
Usage
wc_product_attach_featured_image( $attachment_id, $product, $save_product );
- $attachment_id(int) (required)
- Media attachment ID.
- $product(WC_Product)
- Optional product object.
Default:null - $save_product(true|false)
- If true, the changes in the product will be saved before the method returns.
Default:true
Changelog
| Since 8.5.0 | Introduced. |
wc_product_attach_featured_image() wc product attach featured image code WC 10.5.0
function wc_product_attach_featured_image( $attachment_id, $product = null, $save_product = true ) {
$attachment_post = get_post( $attachment_id );
if ( ! $attachment_post ) {
return;
}
if ( null === $product && wc_get_container()->get( MatchImageBySKU::class )->is_enabled() ) {
// On upload the attachment post title is the uploaded file's filename.
$file_name = pathinfo( $attachment_post->post_title, PATHINFO_FILENAME );
if ( ! $file_name ) {
return;
}
$product_id = wc_get_product_id_by_sku( $file_name );
$product = wc_get_product( $product_id );
}
if ( ! $product ) {
return;
}
$product->set_image_id( $attachment_id );
if ( $save_product ) {
$product->save();
}
if ( 0 === $attachment_post->post_parent ) {
wp_update_post(
array(
'ID' => $attachment_id,
'post_parent' => $product->get_id(),
)
);
}
}