Add Attribute to WooCommerce Product Programmatically

In the world of web development, anything can happen, for instance and the sake of this article, let’s say you’re working with a team utilizing git and for some reason all attributes of a given product have gone missing and your task is to get these attributes back to where they were.  You could do this manually, but why not dive into some code and replace those missing attributes?

Step 1: Get all products and store in an array

        global $product;
	$taxonomy = 'pa_greeting-card-type';
	$term_name = 'holiday';
	$term_slug = sanitize_title($term_name); // The term "slug"
	$product_ids = [];
	$args = array(
		'post_type' => 'product',
			'posts_per_page' => 70,
			'tax_query' => array(
				array(
					'taxonomy' => 'product_tag',
					'field' => 'slug',
					'terms' => array('mothers-day-card', 'valentines-day-card', 'christmas-cards', 'holiday-card', 'new-year-card', 'jewish-card', 'easter-cards', 'new-year' 
					)
				),
			)

		 );
	$loop = new WP_Query($args);
	while ($loop->have_posts()) : $loop->the_post();
			global $product;
			$flag = 0;
			// get product attributes
			$attributes = $product->get_attributes();
			if(empty($attributes)){
				$product_ids[] = get_the_ID(); //products with no attributes
			}
			// if it has product attributes
			else {
				//looping through all product attributes
				foreach($attributes as $attribute) :
					 echo $attribute['name'];

					if($attribute['is_taxonomy']) {
						if($attribute['name'] == $term_name){
							$flag = 1;
						}
					}
				endforeach;
				if ($flag != 1) {
					$product_ids[] = get_the_ID();  //products from our loop without our missing attributes
				}
			}
		endwhile;

		wp_reset_query();

Step 2: Loop through products adding our missing attribute

$product_ids will contain all the Product IDs which do not have our missing attribute, so now we can loop through and set that missing attribute.

		foreach ($product_ids as $product_id) {
		// Check if the term exist and if not it create it (and get the term ID).
		if( ! term_exists( $term_name, $taxonomy ) ){
		    $term_data = wp_insert_term( $term_name, $taxonomy );
		    $term_id   = $term_data['term_id'];
		} else {
		    $term_id   = get_term_by( 'name', $term_name, $taxonomy )->term_id;
		}

		//Initialize new object
		$product = wc_get_product( $product_id );

    	        $attribute = new WC_Product_Attribute();
		$attribute->set_name($taxonomy);
		$attribute->set_options(array($term_id));
		$attribute->set_visible(true);
		$attribute->set_variation(false);
		$attributes[] = $attribute;

		$product->set_attributes($attributes);

		$product->save();

		// Append the new term in the product
		if( ! has_term( $term_name, $taxonomy, $product_id )) {
		    wp_set_object_terms($product_id, $term_slug, $taxonomy, true );
		}
	}

Step 3: Go kiss your loved ones, you’re done here

via GIPHY

Please feel free to comment and let you know if this got you on the right track!

How to migrate to the WP Engine staging environment

In it’s 16th year, WordPress is still leading the pack when it comes to a versatile CMS.  A clear indicator of how powerful and dominant the platform has become is the advent of hosting companies offering specialized managed hosting specifically for the WordPress CMS.  The leading host in this growing market by many of our metrics is WP Engine.  A major feature of WP Engine hosting has been the ease in which sites of any size can be migrated over to the WP Engine servers.  The migration process to WP Engine is simple and straightforward, however you may not be aware of a very cool feature that we’re sure will come in handy on your future or present WordPress projects.

 

If you are familiar with the WP Engine migration plugin, you will be aware that you can migrate easily to the production environment over at WP Engine, but did you know you can do EVEN MORE?  This is a simple step-by-step explanation of how you can migrate a site not to the main production server/environment, but to a WP Engine Staging environment as well. This can be clutch when the available installs on your account become filled up but you still need the powerful features and reliability of WP Engine to ensure a fast and smooth work flow.

 

A Brief History

 

Website migration is complex and difficult which is why WP Engine has developed their migration plugin for WordPress which automates the process and takes out the labor-intensity. In addition to providing an efficient migration solution for developers, WP Engine maintains an impeccable customer experience with unlimited monthly data transfers, daily backups, malware scanning, and 24/7 technical support.

 

The process

 

Step 1: Install ‘WP Engine Automated Migration Plugin

Go to your WordPress Dashboard and download ‘WP Engine Automated Migration’ plugin by following the pathway: ‘Plugin’ > ‘Add new’ and searching for “WP Engine Automated Migration”.

 

Step 2: SFTP Credentials

NOTE: You will need to already have a staging environment created; you can find how to create the environment here.  Once the plugin has been downloaded, select the ‘Site migration’ tab from your WordPress Dashboard.  You will notice a set of credentials you need to supply.  You can fill in your email address immediately, but to generate the rest of the information, you must login to your account on the WP Engine User Portal.

Note: if your current host or WP Engine environment is password protected, you will need to enter that information so the plugin can access everything for migration.

 

Step 3: Website Migration

In order to migrate to the WP Engine staging environment of your website simply fill in the staging environment url you created for your website.  The staging URLs are formatted as sitename.staging.wpengine.com, fill in the remaining information, your SFTP address, username and password into the WP Engine migration plugin.

 

Once you have filled in all of the information correctly, select ‘Migrate’ on the plugin.  If you have followed the steps correctly and provided accurate credentials the migration will begin.   You will be redirected to the BlogVault Dashboard where you can access real-time updates of the process.  The time taken depends on the size of your website.

 

Step 4: Bask in the glory of a job well done

via GIPHY

All done! You now have expanded the usability of the WP Engine staging environment. Visit your newly migrated staging site at sitename.staging.wpengine.com

 

 

Sending Emails From Local With Postfix and MAMP

If you’re anything like me, you love to work locally building websites without relying on a live server, but this can present some drawbacks such as limiting the full functionality of your site, specifically, the ability to test outgoing emails.  In this post I will show you how to take your development even further and without bounds by enabling the ability to send emails from local with Postfix.

[mk_image src=”http://creativeair.co/wp-content/uploads/2018/02/send_email_on_local.png”]

I use MAMP Pro which comes packaged with postfix, however I needed some additional tweaks to get it going smoothly.  I tried many different ways to make postfix work out of the box with MAMP, but alas I was unsuccessful.  A major bummer, because has a “lazy developer” I like the easy straightforward approach as much as the next dev.

 Step 1. Setting up a working Postfix MAMP configuration

These instructions are working for me on OS High Sierra with MAMP version 4.4.1

Open the terminal and enter the following command

$open /var/log/mail.log

This will open the mail log console where you can follow along for warnings and errors.

Open the file /etc/postfix/main.cf in your favorite editor

$open /etc/postfix/main.cf

  • Add the following lines at the bottom of the file.

relayhost = [smtp.gmail.com]:587
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_mechanism_filter = plain
inet_protocols = ipv4
smtp_use_tls = yes
smtp_tls_security_level = encrypt
tls_random_source = dev:/dev/urandom

Step 2. Create then edit the sasl_passwd file to allow authentication with your Google Account

Enter this command in terminal:

$sudo vi /etc/postfix/sasl_passwd

 

Add the following lines

[smtp.gmail.com]:587 youremail@gmail.com:yourpassword

Step 3.  Enter the following commands to restart postfix

$sudo chmod 600 /etc/postfix/sasl_passwd
$sudo postmap /etc/postfix/sasl_passwd
$sudo launchctl stop org.postfix.master
$sudo launchctl start org.postfix.master
$sudo postfix upgrade-configuration

Next, reload Postfix.
$sudo postfix reload
$sudo postfix flush

Test that the configuration is working

$date | mail -s testing someemail@gmail.com

Step 4. Bask in the glory of your accomplishment.

happy Okoye[/vc_wp_text]