{"id":2760,"date":"2023-10-23T11:32:54","date_gmt":"2023-10-23T16:32:54","guid":{"rendered":"http:\/\/racmanuel.dev\/?p=2760"},"modified":"2023-10-23T11:33:01","modified_gmt":"2023-10-23T16:33:01","slug":"como-crear-ordenes-en-woocommerce-de-manera-programatica-una-guia-paso-a-paso","status":"publish","type":"post","link":"https:\/\/racmanuel.dev\/en\/como-crear-ordenes-en-woocommerce-de-manera-programatica-una-guia-paso-a-paso\/","title":{"rendered":"How to Create Orders Programmatically in WooCommerce: A Step-by-Step Guide"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Welcome to this tutorial, where I will guide you step by step through the process of programmatically creating WooCommerce orders. This can be useful when you need to integrate WooCommerce with external systems or when you want to automate certain internal processes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-preparacion\"><strong>1. Preparation<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before you begin, ensure you have access to the file <code>functions.php<\/code> of your theme or, better yet, a custom plugin. This is where we will place our code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-creando-una-orden-basica\"><strong>2. Creating a Basic Order<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To create an order, we need to instantiate an object of the class <code>WC_Order<\/code>. Here is a basic example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$order = wc_create_order();\r<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">However, this order is very basic. Let's see how to add details to this order.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-anadir-productos-a-la-orden\"><strong>3. Adding Products to the Order<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To add products, we use the method <code>add_product()<\/code>. Here is an example of how to add a product to our order:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$product = wc_get_product(123); \/\/ Where 123 is the product ID;\r\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-establecer-direcciones\"><strong>4. Setting Addresses<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To set the shipping and billing addresses, we use the methods <code>set_billing_address()<\/code> y <code>set_shipping_address()<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$address = array(;\r<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-anadir-notas-a-la-orden\"><strong>5. Adding Notes to the Order<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Order notes are useful for storing additional information. Here is how to add one:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$note = \"This is an example note for the order.\";\r<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-establecer-metodos-de-envio\"><strong>6. Setting Shipping Methods<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to specify a shipping method, you can do so as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$shipping_method = new WC_Shipping_Rate('id', 'Env\u00edo Est\u00e1ndar', 5.00, array(), 'flat_rate');\r\n$order-&gt;add_shipping($shipping_method);\r<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Make sure to adjust the values according to your configuration and needs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-anadir-cupones\"><strong>7. Adding Coupons<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If the customer has used a coupon, we can add it to our order programmatically:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$coupon_code = 'MY_COUPON';\r<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8-establecer-metodos-de-pago-y-pagar-la-orden\"><strong>8. Setting Payment Methods and Paying the Order<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">First, let's set the payment method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$order-&gt;set_payment_method('bacs'); \/\/ 'bacs' is for bank transfer. Adjust according to your payment methods.\r<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to mark the order as paid:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$order-&gt;payment_complete();\r<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9-guardar-y-finalizar\"><strong>9. Saving and Finalizing<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">It is crucial to remember to save the order after making all modifications:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">$order-&gt;save();\r<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ejemplo-completo\">Complete Example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a complete example of how to programmatically create an order in WooCommerce, with proper checks and comments to ensure everything works correctly:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">&lt;?php\n\/\/ Verificamos si WooCommerce est\u00e1 activo\r\nif (in_array('woocommerce\/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {\r\n\r\n    \/\/ Creamos una nueva orden\r\n    $order = wc_create_order();\r\n\r\n    \/\/ A\u00f1adimos un producto a la orden (por ejemplo, el producto con ID 123)\r\n    $product = wc_get_product(123);\r\n    $quantity = 1;\r\n    $order-&gt;add_product($product, $quantity);\r\n\r\n    \/\/ Definimos una direcci\u00f3n para facturaci\u00f3n y env\u00edo\r\n    $address = array(\r\n        'first_name' =&gt; 'Juan',\r\n        'last_name'  =&gt; 'P\u00e9rez',\r\n        'company'    =&gt; 'Mi Empresa',\r\n        'email'      =&gt; 'juan@example.com',\r\n        'phone'      =&gt; '123-456-7890',\r\n        'address_1'  =&gt; 'Calle 123',\r\n        'address_2'  =&gt; '', \r\n        'city'       =&gt; 'Madrid',\r\n        'state'      =&gt; 'M',\r\n        'postcode'   =&gt; '28001',\r\n        'country'    =&gt; 'ES'\r\n    );\r\n    $order-&gt;set_billing_address($address);\r\n    $order-&gt;set_shipping_address($address);\r\n\r\n    \/\/ A\u00f1adimos una nota a la orden\r\n    $note = \"Esta es una nota de ejemplo para la orden.\";\r\n    $order-&gt;add_order_note($note);\r\n\r\n    \/\/ Establecemos un m\u00e9todo de env\u00edo (por ejemplo, env\u00edo est\u00e1ndar por 5.00)\r\n    $shipping_method = new WC_Shipping_Rate('id', 'Env\u00edo Est\u00e1ndar', 5.00, array(), 'flat_rate');\r\n    $order-&gt;add_shipping($shipping_method);\r\n\r\n    \/\/ Aplicamos un cup\u00f3n si es necesario\r\n    $coupon_code = 'MI_CUPON';\r\n    $order-&gt;apply_coupon($coupon_code);\r\n\r\n    \/\/ Establecemos el m\u00e9todo de pago y marcamos la orden como pagada\r\n    $order-&gt;set_payment_method('bacs'); \/\/ 'bacs' es para transferencia bancaria. Ajusta seg\u00fan tus m\u00e9todos de pago.\r\n    $order-&gt;payment_complete();\r\n\r\n    \/\/ Guardamos todos los cambios hechos en la orden\r\n    $order-&gt;save();\r\n\r\n    \/\/ Imprimimos el ID de la orden para referencia\r\n    echo 'Se ha creado la orden con el ID: ' . $order-&gt;get_id();\r\n\r\n} else {\r\n    echo 'WooCommerce no est\u00e1 activo. Aseg\u00farate de activarlo para proceder.';\r\n}\n?&gt;\r<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This code first checks if WooCommerce is active. If it is, it creates an order, adds a product, sets the addresses, adds a note, sets the shipping method, applies a coupon, sets the payment method, and finally saves the order. If WooCommerce is not active, it displays an error message.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I hope this example is useful to you and helps you in your development with WooCommerce. Let me know if there is anything else I can help you with!<\/p>\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>Discover how to programmatically create orders in WooCommerce with our detailed tutorial. From basic setup to advanced customization, we&#039;ll guide you step-by-step to integrate and automate your WooCommerce processes. Optimize your store today!<\/p>","protected":false},"author":1,"featured_media":2764,"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":[40,42],"niveles":[39],"class_list":["post-2760","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutoriales","tag-woocommerce","tag-wordpress","niveles-avanzado"],"blocksy_meta":[],"acf":[],"_links":{"self":[{"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/posts\/2760","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=2760"}],"version-history":[{"count":5,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/posts\/2760\/revisions"}],"predecessor-version":[{"id":2766,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/posts\/2760\/revisions\/2766"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/media\/2764"}],"wp:attachment":[{"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/media?parent=2760"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/categories?post=2760"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/tags?post=2760"},{"taxonomy":"niveles","embeddable":true,"href":"https:\/\/racmanuel.dev\/en\/wp-json\/wp\/v2\/niveles?post=2760"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}