{"id":2911,"date":"2024-01-15T19:33:35","date_gmt":"2024-01-16T01:33:35","guid":{"rendered":"http:\/\/racmanuel.dev\/?p=2911"},"modified":"2024-01-15T19:33:42","modified_gmt":"2024-01-16T01:33:42","slug":"anadir-productos-en-woocommerce-con-wc_product-guia-tecnica","status":"publish","type":"post","link":"https:\/\/racmanuel.dev\/en\/anadir-productos-en-woocommerce-con-wc_product-guia-tecnica\/","title":{"rendered":"Adding products to WooCommerce with WC_Product(): Technical Guide"},"content":{"rendered":"<h2 class=\"wp-block-heading\" id=\"introduccion-a-woocommerce-y-wc-product\">Introduction to WooCommerce and WC_Product()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">WooCommerce is a very popular e-commerce platform that allows users to create and manage an online store in a simple and efficient manner. One of the key features of WooCommerce is its ability to handle and manage products effectively. In this article, we will explore product development in WooCommerce using the WC_Product() class, a core class used to create and customize products on the platform.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1880\" height=\"1253\" src=\"http:\/\/racmanuel.dev\/wp-content\/uploads\/pexels-photo-7667442-1.jpeg\" alt=\"person doing online shopping\" class=\"wp-image-2924\" title=\"\" srcset=\"https:\/\/racmanuel.dev\/wp-content\/uploads\/pexels-photo-7667442-1.jpeg 1880w, https:\/\/racmanuel.dev\/wp-content\/uploads\/pexels-photo-7667442-1-600x400.jpeg 600w, https:\/\/racmanuel.dev\/wp-content\/uploads\/pexels-photo-7667442-1-300x200.jpeg 300w, https:\/\/racmanuel.dev\/wp-content\/uploads\/pexels-photo-7667442-1-1024x682.jpeg 1024w, https:\/\/racmanuel.dev\/wp-content\/uploads\/pexels-photo-7667442-1-768x512.jpeg 768w, https:\/\/racmanuel.dev\/wp-content\/uploads\/pexels-photo-7667442-1-1536x1024.jpeg 1536w\" sizes=\"(max-width: 1880px) 100vw, 1880px\" \/><figcaption class=\"wp-element-caption\">Photo by MART PRODUCTION on <a href=\"https:\/\/www.pexels.com\/photo\/person-doing-online-shopping-7667442\/\" rel=\"nofollow noopener\" target=\"_blank\">Pexels.com<\/a><\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"creando-un-producto-basico-con-wc-product\">Creating a basic product with WC_Product()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To create a basic product in WooCommerce using the WC_Product() class, we can follow the PHP code below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product = new WC_Product();\n$product-&gt;set_name('Camiseta');\n$product-&gt;set_price(20);\n$product-&gt;set_stock_quantity(50);\n$product-&gt;save();<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, we create a basic product named \u201cT-shirt\u201d with a price of $20 and an initial stock of 50 units. Then, we save the product using the save() method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"personalizando-los-atributos-del-producto\">Customizing product attributes<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The WC_Product() class also allows us to customize a product's attributes. For example, we can set the size and color of a t-shirt as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product-&gt;set_attributes(array('size' =&gt; 'S', 'color' =&gt; 'blue'));<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this case, we set the product's \u2018size\u2019 and \u2018color\u2019 attributes to \u2018S\u2019 and \u2018blue\u2019, respectively. Then, we save the changes using the save() method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"consultando-y-actualizando-informacion-del-producto\">Querying and updating product information<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Once we have created a product, we can also query and update its information using specific methods. For example, to obtain the ID, name, price, and stock quantity of a product, we can use the following methods:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product_id = $product-&gt;get_id();<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">These methods allow us to access and modify the product's information as needed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"asignando-categorias-y-etiquetas-al-producto\">Assigning categories and tags to the product<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In WooCommerce, it is possible to assign categories and tags to a product to organize and classify them more effectively. Using the WC_Product() class, we can assign categories and tags to a product as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product-&gt;set_category_ids(array(8, 12));<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, we assign categories with IDs 8 and 12, and tags with IDs 5 and 9 to the product. Then, we save the changes using the save() method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"anadiendo-imagenes-al-producto\">Adding images to the product<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">An important part of presenting a product online is the inclusion of images. In WooCommerce, we can add images to a product using the WC_Product() class. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product-&gt;set_image_id(15);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this case, we set the main image ID to 15, and the gallery image IDs to 16 and 17. After adding the images, we save the changes using the save() method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"configurando-opciones-de-envio-y-tasas\">Configuring shipping and tax options<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In addition to basic product information, we can also configure shipping and tax options using the WC_Product() class. For example, we can assign a specific shipping class and a reduced tax class as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product-&gt;set_shipping_class_id(3);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, we assign the shipping class with ID 3 and the tax class \u2018reduced-rate\u2019 to the product. Then, we save the changes using the save() method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"vinculando-productos-relacionados\">Linking related products<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Occasionally, it can be useful to link related products together to promote additional purchases. Using the WC_Product() class, we can set up-sells and cross-sells as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product-&gt;set_upsells(array(22, 23));<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this case, we set the up-sells with IDs 22 and 23, and the cross-sells with IDs 30 and 31. After establishing the relationships, we save the changes using the save() method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"gestionando-precios-y-descuentos\">Managing prices and discounts<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The WC_Product() class also allows us to manage prices and discounts for a product in WooCommerce. For example, we can set a regular price, a sale price, and the start and end dates of the offer as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product-&gt;set_regular_price(25);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, we set a regular price of $25, a sale price of $20, and the start and end dates of the offer (from January 1, 2022, to January 31, 2022). Then, we save the changes using the save() method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"eliminando-un-producto\">Deleting a product<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If we need to delete a product from WooCommerce using the WC_Product() class, we can do so using the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product-&gt;delete(true);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this case, we delete the product and all its related data, such as images, attributes, and relationships. The parameter \u2018true\u2019 indicates that all data associated with the product should be deleted.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ejemplo-de-codigo-completo\">Complete Code Example<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">\/**\n * Crea y gestiona un producto en WooCommerce.\n *\n * Esta funci\u00f3n utiliza la clase WC_Product para crear un nuevo producto en WooCommerce,\n * establecer sus propiedades, y finalmente eliminarlo. Se engancha a WordPress para\n * ejecutarse en un momento espec\u00edfico.\n *\n * @return void\n *\/\nfunction crear_y_gestionar_producto_wc() {\n    \/\/ Crear un nuevo producto\n    $product = new WC_Product();\n    $product-&gt;set_name('Camiseta'); \/\/ Establecer el nombre del producto\n    $product-&gt;set_price(20); \/\/ Establecer el precio del producto\n    $product-&gt;set_regular_price(25); \/\/ Establecer el precio regular\n    $product-&gt;set_sale_price(20); \/\/ Establecer el precio de oferta\n    $product-&gt;set_date_on_sale_from('2022-01-01'); \/\/ Fecha de inicio de la oferta\n    $product-&gt;set_date_on_sale_to('2022-01-31'); \/\/ Fecha de fin de la oferta\n    $product-&gt;set_stock_quantity(50); \/\/ Cantidad de stock\n    $product-&gt;set_manage_stock(true); \/\/ Habilitar gesti\u00f3n de stock\n    $product-&gt;set_attributes(array('size' =&gt; 'S', 'color' =&gt; 'blue')); \/\/ Establecer atributos\n    $product-&gt;set_category_ids(array(8, 12)); \/\/ Asignar categor\u00edas por ID\n    $product-&gt;set_tag_ids(array(5, 9)); \/\/ Asignar etiquetas por ID\n    $product-&gt;set_image_id(15); \/\/ Asignar ID de la imagen principal\n    $product-&gt;set_gallery_image_ids(array(16, 17)); \/\/ Asignar IDs de im\u00e1genes de la galer\u00eda\n    $product-&gt;set_shipping_class_id(3); \/\/ Asignar clase de env\u00edo por ID\n    $product-&gt;set_tax_class('reduced-rate'); \/\/ Asignar clase de impuesto\n    $product-&gt;set_upsells(array(22, 23)); \/\/ Establecer productos relacionados por ID\n    $product-&gt;set_cross_sells(array(30, 31)); \/\/ Establecer productos complementarios por ID\n    $product-&gt;save(); \/\/ Guardar el producto\n\n    \/\/ Consultar informaci\u00f3n del producto\n    $product_id = $product-&gt;get_id(); \/\/ Obtener el ID del producto\n    $product_name = $product-&gt;get_name(); \/\/ Obtener el nombre del producto\n    $product_price = $product-&gt;get_price(); \/\/ Obtener el precio del producto\n    $product_stock = $product-&gt;get_stock_quantity(); \/\/ Obtener la cantidad de stock\n\n    \/\/ Actualizar informaci\u00f3n del producto (ejemplo: cambiar el precio)\n    $product-&gt;set_price(22); \/\/ Cambiar el precio del producto\n    $product-&gt;save(); \/\/ Guardar los cambios\n\n    \/\/ Eliminar un producto\n    \/\/ $product-&gt;delete(true); \/\/ Descomentar para eliminar el producto y sus datos relacionados\n}\n\n\/\/ Hook para integrar la funci\u00f3n con WordPress\n\/\/ Este ejemplo utiliza 'init', pero puedes cambiarlo seg\u00fan tus necesidades\nadd_action('init', 'crear_y_gestionar_producto_wc');\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this code:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Function <code>crear_y_gestionar_producto_wc<\/code><\/strong>: This function is responsible for creating and managing a product in WooCommerce. It uses various methods of the <code>WC_Product<\/code> class to set product properties, such as name, price, stock, attributes, categories, images, and more.<\/li>\n\n\n\n<li><strong>Hook <code>add_action<\/code><\/strong>: Integrates the function with WordPress. In this case, the <code>init<\/code>, hook is used, which fires after WordPress has finished loading but before any headers are sent. You can change this hook to another one that better suits your needs.<\/li>\n\n\n\n<li><strong>PHPDoc format comments<\/strong>: Each line of code has an explanatory comment to better understand what it does. The PHPDoc comments are in Spanish and provide a clear description of the function and its components.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Note that this code assumes WooCommerce is installed and active on your WordPress site. Additionally, the IDs for categories, tags, images, and shipping classes must be valid in your WooCommerce installation. Also, the line to delete the product is commented out to prevent accidental deletions; you can uncomment it if you need to use that functionality.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusiones\">Conclusions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this article, we have explored product development in WooCommerce using the WC_Product() class. We have learned how to create a basic product, customize its attributes, query and update its information, assign categories and tags, add images, configure shipping and tax options, link related products, manage prices and discounts, and delete products. This knowledge provides us with a solid foundation for developing and managing products in WooCommerce effectively. In the next stage of development, we can delve into more advanced concepts and further explore the capabilities of the WC_Product() class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"referencias-y-recursos-adicionales\">References and additional resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Official WooCommerce documentation: <a href=\"https:\/\/docs.woocommerce.com\/\" rel=\"nofollow noopener\" target=\"_blank\">https:\/\/docs.woocommerce.com\/<\/a><\/li>\n\n\n\n<li>WC_Product() class in the documentation: <a href=\"https:\/\/woocommerce.github.io\/code-reference\/classes\/WC-Product.html\" rel=\"nofollow noopener\" target=\"_blank\">https:\/\/docs.woocommerce.com\/wc-apidocs\/class-WC_Product.html<\/a><\/li>\n<\/ul>\n\n\n<style><\/style><style><\/style>\n<div class=\"wp-block-group is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-group is-layout-constrained wp-block-group-is-layout-constrained\">\n<h4 class=\"wp-block-heading has-large-font-size\" id=\"necesitas-ayuda-con-un-proyecto-web\">Do you need help with a web project?<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Do you need help with a web project? Don&#039;t hesitate to contact me. I develop complete and customized solutions with WordPress and PHP, using modern tools and processes, HTML, CSS, SCSS, PHP, JavaScript, Bootstrap, and more. Ready? Send me a message and let&#039;s talk about your web project!<\/p>\n\n\n<div class=\"wp-block-groundhogg-forms\">\n\t<div class=\"gh-form-wrapper\"><form method=\"post\" class=\"gh-form gh-form-v2\" target=\"_parent\" enctype=\"multipart\/form-data\" name=\"Formulario de Contacto\" id=\"gh-form-24\" data-id=\"24\" action=\"\"><div class=\"gh-form-fields\"><div class=\"gh-form-column col-1-of-2\"><label for=\"first_name\">Name <span class=\"required\">*<\/span><\/label><div class=\"gh-form-input-field\"><input type=\"text\" name=\"first_name\" id=\"first_name\" class=\"gh-input gh-first-name\" value=\"\" required><\/div><\/div><div class=\"gh-form-column col-1-of-2\"><label for=\"last_name\">Last name(s) <span class=\"required\">*<\/span><\/label><div class=\"gh-form-input-field\"><input type=\"text\" name=\"last_name\" id=\"last_name\" class=\"gh-input gh-last-name\" value=\"\" required><\/div><\/div><div class=\"gh-form-column col-1-of-1\"><label for=\"email\">Email <span class=\"required\">*<\/span><\/label><div class=\"gh-form-input-field\"><input type=\"email\" name=\"email\" id=\"email\" class=\"gh-input gh-email\" value=\"\" required><\/div><\/div><div class=\"gh-form-column col-1-of-1\"><label for=\"primary_phone\">Phone or WhatsApp <span class=\"required\">*<\/span><\/label><div class=\"gh-form-input-field\"><input type=\"tel\" name=\"primary_phone\" id=\"primary_phone\" class=\"gh-input\" value=\"\" required><\/div><\/div><div class=\"gh-form-column col-1-of-1\"><label for=\"nombre_de_tu_negocio_o_empresa\">Name of your Business or Company<\/label><div class=\"gh-form-input-field\"><input type=\"text\" name=\"nombre_de_tu_negocio_o_empresa\" id=\"nombre_de_tu_negocio_o_empresa\" class=\"gh-input\" value=\"\"\/><\/div><\/div><div class=\"gh-form-column col-1-of-1\"><label for=\"link_de_tu_pagina_web\">Link to your website<\/label><div class=\"gh-form-input-field\"><input type=\"url\" name=\"link_de_tu_pagina_web\" id=\"link_de_tu_pagina_web\" class=\"gh-input\" value=\"\" placeholder=\"If your business or company has a website, enter the link here.\"\/><\/div><\/div><div class=\"gh-form-column col-1-of-1\"><label for=\"question_type\">What kind of question do you have? <span class=\"required\">*<\/span><\/label><div class=\"gh-form-input-field\"><select name=\"question_type\" id=\"question_type\" class=\"gh-input\" required><option value=\"Cotizaci\u00f3n\">Price<\/option><option value=\"General\">General<\/option><option value=\"Soporte\">Medium<\/option><\/select><\/div><\/div><div class=\"gh-form-column col-1-of-1\"><label for=\"message\">Ask <span class=\"required\">*<\/span><\/label><div class=\"gh-form-input-field\"><textarea name=\"message\" id=\"message\" class=\"gh-input\" rows=\"7\" placeholder=\"Your question or doubt...\" type=\"text\" required><\/textarea><\/div><\/div><div class=\"gh-form-column col-1-of-1\"><div class=\"consent gh-gdpr\" id=\"gdpr_consent\"><div ><label class=\"gh-checkbox-label\"><input type=\"checkbox\" name=\"data_processing_consent\" id=\"data-processing-consent\" class=\"\" value=\"yes\" required><span class=\"checkbox-label\">I agree to racmanuel.dev&#8217;s storage and processing of my personal data. <span class=\"required\">*<\/span><\/span><\/label><\/div><div ><label class=\"gh-checkbox-label\"><input type=\"checkbox\" name=\"marketing_consent\" id=\"marketing-consent\" class=\"\" value=\"yes\"\/><span class=\"checkbox-label\">I agree to receive marketing offers and updates from racmanuel.dev.<\/span><\/label><\/div><\/div><\/div><div class=\"gh-form-column col-1-of-3\"><button type=\"submit\" class=\"gh-submit gh-button primary\" value=\"\">Get in touch!<\/button><\/div><\/div><input type=\"hidden\" name=\"trp-form-language\" value=\"en\"\/><\/form><\/div><\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Product Development in WooCommerce with WC_Product(): A Technical Guide for Experts.<\/p>","protected":false},"author":1,"featured_media":2924,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_gspb_post_css":"","_glsr_average":0,"_glsr_ranking":0,"_glsr_reviews":0,"footnotes":""},"categories":[48],"tags":[],"niveles":[38],"class_list":["post-2911","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutoriales","niveles-intermedio"],"blocksy_meta":[],"acf":[],"_links":{"self":[{"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/posts\/2911","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/comments?post=2911"}],"version-history":[{"count":7,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/posts\/2911\/revisions"}],"predecessor-version":[{"id":2927,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/posts\/2911\/revisions\/2927"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/media\/2924"}],"wp:attachment":[{"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/media?parent=2911"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/categories?post=2911"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/tags?post=2911"},{"taxonomy":"niveles","embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/niveles?post=2911"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}