Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Instantiate this class to stop product images from being duplicated when creating a product using the WooCommerce API
<?php
class MyCustomProductsController extends WC_REST_Products_Controller
{
public function register_routes()
{
register_rest_route( $this->namespace, '/' . $this->rest_base, array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'create_item' ),
'permission_callback' => array( $this, 'create_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
),
'schema' => array( $this, 'get_public_item_schema' ),
), true );
register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
'args' => array(
'id' => array(
'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
'type' => 'integer',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => array(
'context' => $this->get_context_param( array(
'default' => 'view',
) ),
),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_item' ),
'permission_callback' => array( $this, 'delete_item_permissions_check' ),
'args' => array(
'force' => array(
'default' => false,
'description' => __( 'Whether to bypass trash and force deletion.', 'woocommerce' ),
'type' => 'boolean',
),
),
),
'schema' => array( $this, 'get_public_item_schema' ),
), true );
}
protected function prepare_object_for_database($request, $creating = false)
{
/**
* Check if the image already exists,
* if it does remove it from the request so it is not duplicated
*/
$images = $request['images'];
$first = true;
foreach ($images as $key => $image) {
$post = get_page_by_title($image['name'], OBJECT, 'attachment');
if (is_a($post, 'WP_Post')) {
$images[$key] = ['id' => $post->ID];
}
if (!isset($images[$key]['position']) && $first == true) {
$images[$key]['position'] = 0;
}
$first = false;
}
$request->set_param('images', $images);
return parent::prepare_object_for_database($request, $creating);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.