WordMove Uknown Collation Error at Line 25

I got this error when trying to use the command “wordmove push – e production -d” to push my database.

ERROR 1273 (HY000) at line 25 in file: ‘dir/to/wp-content/dump.sql’: Unknown collation: ‘utf8mb4_unicode_520_ci’ (Wordmove::ShellCommandError)

To fix this error, make sure that both databases (local and live) have the same collation.

This is how I did it on Digital Ocean using ServerPilot to manage my databases. I logged into my DigitalOcean server with the root user (ssh root@mysite.com). I opened .my.conf (vi /root/.my.conf) to get the password for the root MySQL user. I used phpMyAdmin to login into root (username: root, password: pw), and I was able to see all of the databases. I created a new database with the collation utf8_general_ci, and I created a new user with super privileges to access that database. I updated the production info in my WordMove file with the new database and user. The new database on DO was empty and did not have any tables. This is important because I noticed that tables and columns can also have a collation which might screw up WordMove as well.

Next, I created a new local database using MAMP’s phpMyAdmin with the collation utf8_general_ci, and I also changed the “server connection collation” in MAMP, as well, whatever that is.

In my local WordPress installation, in the wp-config.php file, I changed the DB_CHARSET variable to utf8. I’m not sure if this did anything.

Actually, the only thing that worked for me was to create the database in ServerPilot, pull it, and then push it.

How to Create Menu Items That Become Bold on Hover without Changing Width and Affecting Other Menu Items

https://stackoverflow.com/questions/556153/inline-elements-shifting-when-made-bold-on-hover

HTML

The most important thing to do to the menu item is give it a title with the same text as the menu item itself.

<a href="/entertainment/movies" data-analytics="header_screen" title="Screen">Screen</a>

CSS

The CSS somehow uses the text of that title attribute which we can make bold and invisible.

a.item:hover {
    font-weight: 600;
}
a.item:after {
    content: attr(title);
    font-weight: 600;
    display: block;
    color: transparent;
}

PHP Folder to Text

<?php
foreach (glob(dirname(__FILE__) . '/lib/classes/*/') as $classfilename) {
    var_dump($classfilename);
}

wp_enqueue_scripts not firing

This is definitely a fringe case, but make sure you don’t have any new lines at the top of your header.php file. I’m not sure if this is standard, but the server that I was working on erased the contents of the file because there was a newline at the top of the header.php file. I think the normal error is something like “Headers already sent”. Since header.php is where wp_head() is called, wp_enqueue_scripts wouldn’t fire.

Masonry Grid

CSS

/* Masonry container */
.masonry-blog {
	-moz-column-count: 4;
	-webkit-column-count: 4;
	column-count: 4;
	-moz-column-gap: 1em;
	-webkit-column-gap: 1em;
	column-gap: 1em;
	max-width: 1000px;
	margin: 0 auto;
}

/* Masonry bricks or child elements */

.masonry-blog article {
	display: inline-block;
	margin: 0 0 1em;
	width: 100%;
	position: relative;
}

@media only screen and (max-width : 1024px) {
	.masonry-blog { /* Masonry container */
	-moz-column-count: 3;
	-webkit-column-count: 3;
	column-count: 3;
	}
}

@media only screen and (max-device-width : 1024px) and (orientation : portrait) {
	.masonry-blog { /* Masonry container */
	-moz-column-count: 2;
	-webkit-column-count: 2;
	column-count: 2;
	}
}

@media only screen and (max-width : 768px) {
	.masonry-blog { /* Masonry container */
	-moz-column-count: 2;
	-webkit-column-count: 2;
	column-count: 2;
	}
}

@media only screen and (max-width : 480px) {
	.masonry-blog { /* Masonry container */
	-moz-column-count: 1;
	-webkit-column-count: 1;
	column-count: 1;
	}
}

PHP

<div class="masonry-blog">
  <div class="wrap-1">
    <?php
    $args = array(
    'posts_per_page' => 8,
    'post_type' => 'post'
    );
    $query = new WP_Query( $args );
    ?>


    <?php if ( $query->have_posts() ) : ?>

      <?php while ( $query->have_posts() ) : $query->the_post(); ?>

        <article class=”post”>
          <?php if (get_field('text_position') == 'inside-text'): ?>
            <div class="post-content small text <?php echo get_field('text_position'); ?>">
              <?php the_excerpt(); ?>
            </div>
          <?php endif; ?>
          <a href="<?php the_permalink(); ?>">
            <?php if( get_the_post_thumbnail() ) : ?>
              <?php the_post_thumbnail('small'); ?>
            <?php endif; ?>
          </a>
          <!--<h3 class="title">
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
          </h3>-->
          <?php if (get_field('text_position') == 'outside-text'): ?>
            <div class="post-content small text <?php echo get_field('text_position'); ?>">
              <?php the_excerpt(); ?>
            </div>
          <?php endif; ?>
          <a class="title" href="<?php the_permalink(); ?>">Read More</a>
        </article>

      <?php endwhile; ?>

      <?php
      previous_posts_link('&laquo; Newer posts');
      next_posts_link( 'Older posts &raquo;', $query->max_num_pages );
      ?>

      <?php //wp_reset_postdata(); ?>

    <?php else : ?>
      <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif; ?>

  </div>
</div>

Redirect to SSL/HTTPS with JavaScript

This snippet is a life saver if nothing else is working, and you absolutely must redirect a site to SSL.

<script>
if(location.protocol != 'https:'){
	location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
</script>

 

Custom Genesis Loop (General)

Custom Genesis Loop

 

<?php

remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'child_do_custom_loop' );
 
function child_do_custom_loop() {
 
    global $paged; // current paginated page
    global $query_args; // grab the current wp_query() args
    $args = array(
        'post_type' => 'post'
    );
     
 
    // the query
    $the_query = new WP_Query( $args ); ?>

    <?php if ( $the_query->have_posts() ) : ?>
    
    	<!-- pagination here -->
    
    	<!-- the loop -->
    	<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    	    <article>
            	<h2><?php the_title(); ?></h2>
                <div class="entry-content"><?php the_content(); ?></div>

    	    </article>
    	<?php endwhile; ?>
    	<!-- end of the loop -->
    
    	<!-- pagination here -->
    
    	<?php wp_reset_postdata(); ?>
    
    <?php else : ?>
    	<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif;

}

genesis();

 

dsf

Add a Custom Genesis Footer

Add a custom footer.

remove_action( 'genesis_footer', 'genesis_footer_markup_open', 5 );
remove_action( 'genesis_footer', 'genesis_do_footer' );
remove_action( 'genesis_footer', 'genesis_footer_markup_close', 15 );
//* Customize the site footer
add_action( 'genesis_footer', 'bg_custom_footer' );
function bg_custom_footer() { ?>

	<div class="site-footer"><div class="wrap"><p>Handcrafted with <span class="dashicons dashicons-heart"></span> by moi. Powered by the <a href="http://rainmakerplatform.com/">Rainmaker Platform</a>. <a href="http://briangardner.com/contact/">Get in Touch</a>.</p></div></div>

<?php
}

Loop through All WooCommerce Products and Check if They Have an Image or Attribute

Create a file called page-test.php in your theme folder and a page called Test in WordPress. Put this code in your page-test.php file, and you’re good to go!

<?php

add_action( 'genesis_meta', 'enterprise_home_genesis_meta' );


function create_table($data) {
  $table_string = '';
  $table_string .= '<table>';
  $table_string .= '<tr>';
  $table_string .= '<td>Title</td>';
  $table_string .= '<td>SKU</td>';
  $table_string .= '<td>ID</td>';
  $table_string .= '</tr>';

  foreach ($data as $product) {
    $table_string .= '<tr>';
    $table_string .=  '<td>' . $product['title'] . '</td>';
    $table_string .=  '<td>' . $product['sku'] . '</td>';
    $table_string .=  '<td>' . $product['id'] . '</td>';
    $table_string .= '</tr>';
  }

  $table_string .= '</table>';

  return $table_string;
}


// ********* Get all products and variations and sort alphbetically, return in array (title, sku, id)*******
function get_woocommerce_product_list() {
  $full_product_list = array();

  $loop = new WP_Query( array( 'post_type' => array('product'), 'posts_per_page' => -1 ) );
 
  while ( $loop->have_posts() ) : $loop->the_post();

    $theid = get_the_ID();
    $product = new WC_Product($theid);

    // $product_code is an attribute of the product
    $product_code = $product->get_attribute('pa_new-product-code');
    // use this if statement to record a list of products that don't have images
    //if (!has_post_thumbnail($theid)) {
    // use this if statement to record a list of products that don't have a certain attribute
    if (!$product_code) {

      $sku = get_post_meta($theid, '_sku', true );
      $thetitle = get_the_title();
      // add product to array
      if (!empty($sku)) {
        $full_product_list[] = array(
          'title' => $thetitle, 
          'sku' => $sku, 
          'id' => $theid
        );
      }
    }

  endwhile; wp_reset_query();

  // sort into alphabetical order, by title
  sort($full_product_list);

  $product_table = create_table($full_product_list);

  $no_match_file = get_stylesheet_directory();
  $no_match_file .= '/no_woo_image.log';
  // echo the array onto the screen
  echo '<pre>';
  var_dump($product_table);
  var_dump($full_product_list);
  echo '</pre>';
  // use file_put_contents to dump the array into a file in your theme
  //file_put_contents($no_match_file, print_r($full_product_list, true));
}
get_woocommerce_product_list();

genesis();

CSS Transparent Overlay Background Image

This is a really tiny snippet, but I use it so often that I justified allowing it to be in its own code snippet post. It is a gradient over a background image. It’s a pretty ugly gradient, but it’s a gradient nonetheless!

.background-image-container {
    background: linear-gradient(rgba(221, 120, 120, 0.9),rgba(210, 221, 120, 0.9)),url(https://dust2life.com//wp-content/uploads/2016/12/green-3d-checker-board-pattern.jpeg);
}

 

Replace PNG Images with SVG Files to Control with CSS

Import the PNG into Adobe Illustrator. Click Image Trace > Black and White Logo. Then, click Expand. After that, click Object > Ungroup and make any edits as necessary.

Next, click Edit > Export Selection. In the dropdown, select SVG instead of PNG. In the next window, click Show SVG Code (or something like that). Copy that SVG element and paste it in place of the PNG. Wala! Here’s an example SVG element that I am able to put in place of a PNG. I included the actual icon below for your enjoyment.

<svg class="fp-svg weight-svg" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="-5 -25 150 150">
  <title>hero-icon-1</title>
  <path d="M143.49,68.79a3.44,3.44,0,0,1-.82-0.25h-0.07l-0.43,0a3.46,3.46,0,0,1-3.46-4.05,4.19,4.19,0,0,1,0-.58c0-.11,0-0.23,0-0.34a19.1,19.1,0,0,1-.46-5.94c0-3.07.63-6.32-.19-9.15-0.76-2.64-2.64-6.21-4.8-6.88-3-.94-6.75.44-10.61,0.88,0-3.39.16-7.93,0-12.45-0.22-4.75-3.54-8-7.68-7.94s-7.23,3.27-7.32,8.13c-0.13,7,0,14,0,21,0,5.41,0,10.82,0,16.36H43.06c0-9.83,0-19.2,0-28.57,0-11.82-1.87-15.59-7.72-15.51S27.94,27,28,38.67c0,1.89,0,3.78,0,6.83-3.88-4-7-6.15-11.36-4.19-4.53,2-5.06,6-4.89,10.28,0.1,2.72-.13,5.46.06,8.18a12,12,0,0,1-.11,3s0,0.09,0,.13A4,4,0,0,1,11,66.93a3.23,3.23,0,0,1-2.76,1.9,3.31,3.31,0,0,1-2.12.87,3.16,3.16,0,0,1-1.35,1.15c-2.28,4-1.6,9.46,2.32,12.16H7.88a3.48,3.48,0,0,1,3.44,4.18,4.18,4.18,0,0,1,0,.7,14.29,14.29,0,0,1,.38,5.06c-0.12,2.21.05,4.43,0,6.65-0.18,4.29.23,8.31,4.74,10.38,4.23,1.94,7.55.12,11.51-4.14,0,5.18,0,8.87,0,12.55,0,6.09,2.75,9.52,7.47,9.51s7.6-3.51,7.62-9.5c0-10.06.15-20.12-.06-30.18-0.07-3.6.67-5.16,4.72-5.12,18.41,0.19,36.83.16,55.24,0,3.64,0,4.7,1.29,4.64,4.78-0.17,10.06-.12,20.12,0,30.18,0,5.28,3,8.56,7.37,8.59s7.49-3.32,7.68-8.46c0.13-3.47,0-6.94,0-8.93,4.3,0.16,8.17,1.2,11.41.19,4.45-1.38,4.32-5.95,4.21-10-0.08-3.07.12-6.15-.06-9.2a7.82,7.82,0,0,1,.19-2.46,4.18,4.18,0,0,1,0-.64,3.76,3.76,0,0,1,1.32-3.52,3.25,3.25,0,0,1,2.43-1.23,3.32,3.32,0,0,1,1.34-.53,3.13,3.13,0,0,1,1.23-.94C147.4,77,147.2,71.59,143.49,68.79Z" transform="translate(-3.47 -22.1)"></path>
</svg>

After that, you can style the SVG with the following. Here’s my example styles. These styles are what turn the icon red and also what cause the background to turn white on hover.

.fp-svg:hover {
    fill: white;
    background-color: #c92e27;
}

.fp-svg {
    fill: #c92e27;
    border: 2px solid #c92e27;
    border-radius: 100%;
    transition: all .2s ease-in-out;
    padding: 20px;
    max-width: 170px;
}

 

hero-icon-1

WP All Import WooCommerce Trick: Add Path to Multiple Images Per Product

Rather than use a FOREACH loop, you would need to use a custom PHP function on this data. Here’s the function that I’ve inserted into the Function Editor on your site (All Import -> Settings):

function my_image_func( $url, $id, $images ) {
	$fixed_list = str_replace(", ", ",", $images);
	$images = explode( ",", $fixed_list );
	$return = array();
	foreach( $images as $image ) {
		$return[] = $url . "/" . $id . "/" . $image;
	}
	return implode( ",", $return );
}

The function itself would be used like this on your data:

[my_image_func("http://siresource.com/wp-content/uploads/bull_images",{id[1]},{picture[1]})]

This function replaces spaces with dashes, removes parenthesis, and lower cases the letters. This is good if the images were uploaded to WordPress in the admin area.

function my_image_func($images ) {
	$fixed_list = str_replace(", ", ",", $images);
	$images = explode( ",", $fixed_list );
	$return = array();
	foreach( $images as $image ) {
		$wp_image = str_replace(" ", "-", $image);
		$wp_image = str_replace("(", "", $wp_image);
		$wp_image = str_replace(")", "", $wp_image);
		$wp_image = strtolower($wp_image);
		$return[] = $wp_image;
	}
	return implode( ",", $return );
}

The function can be used like this: [my_image_func({picture[1]})]

It’s still a better idea to rename the images.

Shortcode for Getting a WooCommerce Product

add_shortcode('rm_product', 'get_wc_product_simple');

function get_wc_product_simple($atts) {
  $a = shortcode_atts( array(
      'product_ids' => ''
  ), $atts );
  $product_ids = explode(',', $a['product_ids']);
  
  ob_start();
  $count = 1;
  $product_list = '<ul class="product_list_widget">';
  foreach ($product_ids as $product_id) {
    $product_list .= rm_get_product($product_id, $count);
    $count++;
  }
  $product_list .= '</ul>';
  return $product_list;
}
//confirmation for amanda 262418893 
//confirmation for support 104156488
function rm_get_product($product_id, $count) {

  $product = wc_get_product( $product_id );
  $product_html = '<li class="one-fourth ';
  if ($count == 1) {
    $product_html .= 'first';
  }
  $product_html .= '">';
  $product_html .= '<a href="' . $product->get_permalink() . '"">';
  $product_html .= wp_get_attachment_image( get_post_thumbnail_id($product_id), $size='medium' );
  $product_html .= '</a>';
  $product_html .= '</li>';
  return $product_html;
}

My Favorite WooCommerce Snippets

//Filter out any products with 0 price
add_action( 'pre_get_posts', 'my_modify_main_query' );
function my_modify_main_query( $query ) {
    if( $query->is_main_query() && is_shop() && !is_admin()) {
    $query->set( 'posts_per_page', 12 );
    $meta_query2 = array(
        array(
            'key' => '_price',
            'value' => '0',
            'compare' => '>'
        )
    );
    $query->set( 'meta_query', $meta_query2 );
    }
}


//Order by SKU
//add_action( 'pre_get_posts', 'my_modify_main_query' );
function my_modify_main_query( $query ) {
    if( $query->is_main_query() && is_shop() && !is_admin()) {
    $query->set( 'posts_per_page', 12 );
    $query->set( 'meta_key', '_sku' );
    $query->set( 'orderby', 'meta_value' );
    $query->set( 'order', 'ASC' );
    }
}

//Create custom Add to Cart button (can be used in a loop)
Buy now

//Prevent custom Add to Cart button that goes to Cart from adding two products
add_action('add_to_cart_redirect', 'resolve_dupes_add_to_cart_redirect');
function resolve_dupes_add_to_cart_redirect($url = false) {
  if(!empty($url)) { return $url; }
  return 'xxxxxxx.xxx' . add_query_arg(array(), remove_query_arg('add-to-cart'));
}

//Display an add to cart button using shortcode (use in woocommerce template or anywhere)
echo do_shortcode("[add_to_cart id=$product_id]");

//CSS for add to cart
.product.woocommerce.add_to_cart_inline {
    border: none !important;
    padding: 0 !important;
}
span.woocommerce-Price-amount.amount {
    display: none;
}



//add_action('add_attachment', 'attach_pics_to_prods');

function attach_pics_to_prods( $attachmentID ) {
  if ( ! class_exists( 'WC_Product' ) ) return; // if no WooCommerce do nothing

  // an attachment was jus saved, first of all get the file name
  $src = wp_get_attachment_image_src( $attachmentID, 'full' );
  $filename = pathinfo( $src[0], PATHINFO_FILENAME );

  $str_name = array_shift(explode('-', $filename));

  // now let's see if exits a product with the sku that match filename
  $info = '';
  $args = array(
    'post_type' => 'product',
    'meta_key' => '_sku',
    'meta_value' => $str_name,
    'meta_compare' => 'LIKE' // assuming sku is unique get only one post
  );
  $prods = get_posts( $args );


//cman250-1
//cman255-1
//cman255 (1)
  if ( ! empty($prods) && count($prods) > 1) { //if we found multiple products
    foreach ($prods as $product) {
        // ok we have a match, exists a product having sku that match filename
        if (has_post_thumbnail($product)) {

            delete_post_thumbnail($product);
        }
        // set the thumbnail for the product
        set_post_thumbnail( $product, $attachmentID );

        // now "attach" the post to the product setting 'post_parent'
        $attachment = get_post( $attachmentID );
        $attachment->post_parent = $product->ID;
        wp_update_post( $attachment );          
    }
  } else if (! empty($prods) && count($prods) == 1){ //if we only have one product
    // ok we have a match, exists a product having sku that match filename
    $product = array_pop( $prods );

    if (has_post_thumbnail($product)) {

        delete_post_thumbnail($product);
    }
    // set the thumbnail for the product
    set_post_thumbnail( $product, $attachmentID );

    // now "attach" the post to the product setting 'post_parent'
    $attachment = get_post( $attachmentID );
    $attachment->post_parent = $product->ID;
    wp_update_post( $attachment );
    } else {
        $no_match = $src[0] . '\n' . ': ' . $attachmentID;
        file_put_contents('no_match_woo_error.log', print_r($no_match, true), FILE_APPEND);
    }
};



//Sort by SKU unless Sort & Filter is trying to sort the products
add_action( 'pre_get_posts', 'my_modify_main_query' );
function my_modify_main_query( $query ) {
    if( $query->is_main_query() && is_shop() && !is_admin()) {
      //if Sort & Filter is trying to sort the products, do not sort by SKU
      if (get_query_var( 'sort_order', $default ) === NULL) {;
        $query->set( 'posts_per_page', 12 );
        $query->set( 'meta_key', '_sku' );
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'order', 'ASC' );
      }
    }
}

WooCommerce Shop Code Snippets

Learn how to set up a WooCommerce shop. You’ll use eleven different plugins and many different code snippets to get this WooCommerce shop set up! Please be warned that this tutorial is not complete, but it is definitely packed with useful information.

Initial Setup

Install WooCommerce Plugin and go through installation steps.

Below are various snippets to modify your WooCommerce shop.

Enable theme support for the Genesis Connect plugin and WooCommerce.

/*-- Enable Genesis Connect --*/
add_theme_support( 'genesis-connect-woocommerce' );
add_theme_support("woocommerce");

Next, install Genesis WooCommerce Connect plugin.

Rename the pre-created Shop page to whatever you want. Somehow WooCommerce displays the products on it.

Install WP All Import and WPAI WooCommerce Addon plugin ($140).

Install the Search and Filter Pro plugin ($20).

Install the WooCommerce Additional Variation Images plugin $50).

Install the WooForce USPS Shipping Plugin ($70).

Install the WooForce FedEx Shipping Plugin ($70).

Install WC Variations Radio Buttons ($0).

Create a Drift account and install the Drift plugin ($0).

Install the YITH WooCommerce Gift Cards plugin ($0).

Install the  Login Widget With Shortcode plugin, create a page called Log In and paste the following shortcode into it: [login_widget]. This will be used in conjunction with the login-out-function.php file.

Install the Custom Post Type UI plugin to create the Gender/Age taxonomy on the product post type.

Hide shipping rates when free shipping is available.

 function my_hide_shipping_when_free_is_available( $rates ) {
    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );

Change WooCommerce’s CSS to display three items per row.

add_filter( 'loop_shop_columns', 'wc_loop_shop_columns', 1, 10 );
/*
 * Return a new number of maximum columns for shop archives
 * @param int Original value
 * @return int New number of columns
 */
function wc_loop_shop_columns( $number_columns ) {
	return 6;
}

Change WooCommerce layout to be compatible with Genesis.

/*-- Change WooCommerce layout for Genesis --*/
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);

add_action('woocommerce_before_main_content', 'my_theme_wrapper_start', 10);
add_action('woocommerce_after_main_content', 'my_theme_wrapper_end', 10);

function my_theme_wrapper_start() {
  echo '';
}

function my_theme_wrapper_end() {
  echo '';
}

Remove default Genesis sidebar and add a custom sidebar for WooCommerce pages. This sidebar will be used to display filtering and sorting widgets.

/*-- Register woocommerce sidebar for Search & Filter form --*/
remove_action( 'genesis_after_content', 'genesis_get_sidebar' ); //remove the default Genesis sidebar
genesis_register_sidebar( array(
	'id'            => 'woocommerce-sidebar',
	'name'          => __( 'WooCommerce Sidebar', 'TrueQuality' ),
	'description'   => __( 'This is the WooCommerce primary sidebar', 'TrueQuality' ),
) );

/*-- Display custom woocommerce sidebar if we are on a woocommerce page --*/
add_action('genesis_before_content', 'add_wc_sidebar');
function add_wc_sidebar() {
  if (is_woocommerce() && !is_single()) {
    genesis_widget_area( 'woocommerce-sidebar', array(
	     'before' => '<aside class="sidebar sidebar-primary widget-area" role="complementary" aria-label="Primary Sidebar" itemscope itemtype="http://schema.org/WPSideBar">',
	     'after' => '</aside>',
    ) );
	}
}

Add a custom field to the checkout form.

/*-- Add custom field to checkout form--*/
add_action( 'woocommerce_after_order_notes', 'add_party_field_to_checkout_form' );

function add_party_field_to_checkout_form( $checkout ) {

    echo '<div id="party_name_checkout_field"><h2>' . __('Party/Group') . '</h2>';

    woocommerce_form_field( 'party_name', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('Please specify the name of your party'),
        'placeholder'   => __('Your Party Name'),
        ), $checkout->get_value( 'party_name' ));

    echo '</div>';

}

/**
 * Update the order meta with field value
 */
add_action( 'woocommerce_checkout_update_order_meta', 'party_checkout_field_update_order_meta' );

function party_checkout_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['party_name'] ) ) {
        update_post_meta( $order_id, 'Party/Group', sanitize_text_field( $_POST['party_name'] ) );
    }
}

/**
 * Display field value on the order edit page
 */
add_action( 'woocommerce_admin_order_data_after_billing_address', 'party_checkout_field_display_admin_order_meta', 10, 1 );

function party_checkout_field_display_admin_order_meta($order){
    echo '<p><strong>'.__('Party/Group').':</strong> ' . get_post_meta( $order->id, 'Party/Group', true ) . '</p>';
}

 

Add the following code to functions.php to change the number of products on the shop page to twelve.

/*-- Modify the main woocommerce loop to display twelve products per page --*/
add_action( 'pre_get_posts', 'my_modify_main_query' );
function my_modify_main_query( $query ) {
    if( $query->is_main_query() && (is_shop() || is_product_category() || is_tax('gender_age')) && !is_admin()) {
        $query->set( 'posts_per_page', 12 );
    }
}

Change the Add to Cart button with the following code.

add_action('init','remove_loop_button');
function remove_loop_button(){
	remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
}

add_action('woocommerce_after_shop_loop_item','replace_add_to_cart');
function replace_add_to_cart() {
	global $product;
	$link = $product->get_permalink();
	echo $link;
}

Add this code if you are importing products with WP All Import and have also purchased the WooCommerce plugin to enable additional variation images.

/*-- When WP All Import saves a post, get its gallery and apply it to a new post meta key (allows the WC Add More Variation Images plugin to recognize the gallery) --*/
add_action('pmxi_saved_post', 'post_saved', 10, 1);
function post_saved($id) {
        $product_image_gallery = get_post_meta($id, '_product_image_gallery')[0];
        update_post_meta( $id, '_wc_additional_variation_images', $product_image_gallery );
}

Create a file called login-out-function.php in your themes root folder and add the following code to it. This code will add a Log In link when user’s are logged out and a Log Out link when users are logged in. It will add the link to the menus with the slugs top-menu and footer-2.

<?php
/**
 * Simple helper function for make menu item objects
 * 
 * @param $title      - menu item title
 * @param $url        - menu item url
 * @param $order      - where the item should appear in the menu
 * @param int $parent - the item's parent item
 * @return \stdClass
 */ 
function _custom_nav_menu_item( $title, $url, $order, $parent = 0 ){
  $item = new stdClass();
  $item->ID = 1000000 + $order + parent;
  $item->db_id = $item->ID;
  $item->title = $title;
  $item->url = $url;
  $item->menu_order = $order;
  $item->menu_item_parent = $parent;
  $item->type = '';
  $item->object = '';
  $item->object_id = '';
  $item->classes = array();
  $item->target = '';
  $item->attr_title = '';
  $item->description = '';
  $item->xfn = '';
  $item->status = '';
  return $item;
}



add_filter( 'wp_get_nav_menu_items', 'custom_nav_menu_items', 20, 2 );

function custom_nav_menu_items( $items, $menu ){
  // only add item to a specific menu
  if ( $menu->slug == 'top-menu' || $menu->slug == 'footer-2' ){

    // only add profile link if user is logged in
    if ( get_current_user_id() ){
        $items[] = _custom_nav_menu_item( 'Logout', wp_logout_url( home_url() ), 4 );
       
    } else {
        $items[] = _custom_nav_menu_item( 'Login', '/log-in', 4 );
    }
  }
    
  return $items;
}

Then, add the following code to functions.php to activate the code above.

include('login-out-function.php');

Remove the orderby widget by creating a folder called WooCommerce in your theme’s folder. Create a folder called loop inside of that, and create an empty file called orderby.php inside of that (your-theme-folder > woocommerce > loop > orderby.php).

Create a file called taxonomy.php in the woocommerce folder and insert the following code. The following code can also be found in the Genesis Connect plugin which you should have installed.

This step is completely unnecessary and only exists to help you understand what’s going on in your taxonomy template.

<?php
/**
 * This template displays the archive for Products
 *
 * @package genesis_connect_woocommerce
 * @version 0.9.8
 *
 * Note for customisers/users: Do not edit this file!
 * ==================================================
 * If you want to customise this template, copy this file (keep same name) and place the
 * copy in the child theme's woocommerce folder, ie themes/my-child-theme/woocommerce
 * (Your theme may not have a 'woocommerce' folder, in which case create one.)
 * The version in the child theme's woocommerce folder will override this template, and
 * any future updates to this plugin won't wipe out your customisations.
 *
 * @since 0.9.0
 *
 */

/** Remove default Genesis loop */
remove_action( 'genesis_loop', 'genesis_do_loop' );

/** Remove WooCommerce breadcrumbs */
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20 );

/** Uncomment the below line of code to add back WooCommerce breadcrumbs */
//add_action( 'genesis_before_loop', 'woocommerce_breadcrumb', 10, 0 );

/** Remove Woo #container and #content divs */
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10 );
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10 );


/** Get Shop Page ID */
// @TODO Retained for backwards compatibility with < 1.6.0 WooC installs
global $shop_page_id;
$shop_page_id = get_option( 'woocommerce_shop_page_id' );


add_filter( 'genesis_pre_get_option_site_layout', 'genesiswooc_archive_layout' );
/**
 * Manage page layout for the Product archive (Shop) page
 *
 * Set the layout in the Genesis layouts metabox in the Page Editor
 *
 * @since 0.9.0
 *
 * @param str $layout Genesis layout, eg 'content-sidebar', etc
 * @global string|int $shop_page_id The ID of the Shop WP Page
 * @return str $layout Shop Page layout from postmeta
 */
function genesiswooc_archive_layout( $layout ) {

	global $shop_page_id;

	$layout = get_post_meta( $shop_page_id, '_genesis_layout', true );

	return $layout;
}

add_action( 'genesis_before_loop', 'genesiswooc_archive_product_loop' );
/**
 * Display shop items (product custom post archive)
 *
 * This function has been refactored in 0.9.4 to provide compatibility with
 * both WooC 1.6.0 and backwards compatibility with older versions.
 * This is needed thanks to substantial changes to WooC template contents
 * introduced in WooC 1.6.0.
 *
 * @uses genesiswooc_content_product() if WooC is version 1.6.0+
 * @uses genesiswooc_product_archive() for earlier WooC versions
 *
 * @since 0.9.0
 * @updated 0.9.4
 * @global object $woocommerce
 */
function genesiswooc_archive_product_loop() {

	global $woocommerce;
	
	$new = version_compare( $woocommerce->version, '1.6.0', '>=' );
	
	if ( $new )
		genesiswooc_content_product();
		
	else
		genesiswooc_product_archive();
}

genesis();

Create another file in your woocommerce folder and call it content-product.php and insert the following template code. This adds a class of “last” to the last product in a row. The layout would break without that class.

Editing:  
/home/truequalityshoes/public_html/wp-content/themes/TrueQuality/woocommerce/content-product.php
 Encoding:    Re-open Use Code Editor     Close  Save Changes

<?php
/**
 * The template for displaying product content within loops
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/content-product.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer).
 * will need to copy the new files to your theme to maintain compatibility. We try to do this.
 * as little as possible, but it does happen. When this occurs the version of the template file will.
 * be bumped and the readme will list any important changes.
 *
 * @see     http://docs.woothemes.com/document/template-structure/
 * @author  WooThemes
 * @package WooCommerce/Templates
 * @version 2.5.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

global $product, $woocommerce_loop;

// Store loop count we're currently on
if ( empty( $woocommerce_loop['loop'] ) ) {
	$woocommerce_loop['loop'] = 0;
}

// Store column count for displaying the grid
if ( empty( $woocommerce_loop['columns'] ) ) {
	$woocommerce_loop['columns'] = apply_filters( 'loop_shop_columns', 3 );
}

// Ensure visibility
if ( ! $product || ! $product->is_visible() ) {
	return;
}

// Increase loop count
$woocommerce_loop['loop']++;

// Extra post classes
$classes = array();
if ( 0 === ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 === $woocommerce_loop['columns'] ) {
	$classes[] = 'first';
}
if ( 0 === $woocommerce_loop['loop'] % $woocommerce_loop['columns'] ) {
	$classes[] = 'last';
}
?>
<li <?php post_class( $classes ); ?>>

	<?php
	/**
	 * woocommerce_before_shop_loop_item hook.
	 *
	 * @hooked woocommerce_template_loop_product_link_open - 10
	 */
	do_action( 'woocommerce_before_shop_loop_item' );

	/**
	 * woocommerce_before_shop_loop_item_title hook.
	 *
	 * @hooked woocommerce_show_product_loop_sale_flash - 10
	 * @hooked woocommerce_template_loop_product_thumbnail - 10
	 */
	do_action( 'woocommerce_before_shop_loop_item_title' );

	/**
	 * woocommerce_shop_loop_item_title hook.
	 *
	 * @hooked woocommerce_template_loop_product_title - 10
	 */
	do_action( 'woocommerce_shop_loop_item_title' );

	add_action('woocommerce_after_shop_loop_item_title','woocommerce_template_single_excerpt', 5 );

	/**
	 * woocommerce_after_shop_loop_item_title hook.
	 *
	 * @hooked woocommerce_template_loop_rating - 5
	 * @hooked woocommerce_template_loop_price - 10
	 */
	do_action( 'woocommerce_after_shop_loop_item_title' );

	/**
	 * woocommerce_after_shop_loop_item hook.
	 *
	 * @hooked woocommerce_template_loop_product_link_close - 5
	 * @hooked woocommerce_template_loop_add_to_cart - 10
	 */
	do_action( 'woocommerce_after_shop_loop_item' );
	?>

</li>

Get a Post’s Featured Image the WordPress Way (in the Loop)

The snippet below will get an image tag with src, class, alt, and title attributes. This is a very simple and SEO friendly way of adding images since the alt and title attributes are filled in automatically.

You can use this anywhere in the WordPress loop (archive page or single post page).

get_post_thumbnail_id( get_the_ID()) gets the ID of the post’s featured image which is the only required parameter of wp_get_attachment_image().

<?php echo wp_get_attachment_image( get_post_thumbnail_id( get_the_ID()) ); ?>

This is a great alternative to using the following snippet which only creates an image tag without any alt, class, or title attributes.

<img src="<?php echo get_the_post_thumbnail_url(); ?>" /> //different way of adding images

Find All Products without An Image in WooCommerce

Just paste the following at the bottom of your functions.php file. It will print an array of products without images to a file called no_woo_images.log in your theme’s root directory.

// ********* Get all products and variations and sort alphbetically, return in array (title, sku, id)*******
function get_woocommerce_product_list() {
    $full_product_list = array();
    $loop = new WP_Query( array( 'post_type' => array('product'), 'posts_per_page' => -1 ) );
 
    while ( $loop->have_posts() ) : $loop->the_post();

        $theid = get_the_ID();
        $product = new WC_Product($theid);

        if (!has_post_thumbnail($theid)) {
            
            $sku = get_post_meta($theid, '_sku', true );
            $thetitle = get_the_title();
            // add product to array but don't add the parent of product variations
            if (!empty($sku)) {
                $full_product_list[] = array(
                    'Title' => $thetitle, 
                    'SKU/Item #' => $sku, 
                    'Item ID' => $theid
                );
            }
        }

    endwhile; wp_reset_query();
    // sort into alphabetical order, by title
    sort($full_product_list);

    $no_match_file = get_stylesheet_directory();
    $no_match_file .= '/no_woo_image.log';
    file_put_contents($no_match_file, print_r($full_product_list, true));
}
get_woocommerce_product_list();

Attach Images to Products with the Same SKU

I found a WordPress code snippet for WooCommerce somewhere on the web and coded a couple changes that might be of some benefit to other developers. The code snippet attaches an image to a product with the exact same SKU. I changed it to find all products with a SKU like the name of the image (which means it can find multiple products) and add the image to it. Or if there’s only one match, it gets the one product and adds the image to it. If there is no match for the image, it writes the name of the image to a file in the theme’s directory.

Also, there is one line of commented, that if uncommented, will get the name of the image and remove anything after a dash. For example, animage-02.jpg becomes animage.

add_action('add_attachment', function( $attachmentID ) {
  if ( ! class_exists( 'WC_Product' ) ) return; // if no WooCommerce do nothing

  //Get the name of the file that was just uploaded
  $src = wp_get_attachment_image_src( $attachmentID, 'full' );
  $filename = pathinfo( $src[0], PATHINFO_FILENAME );

  //OPTIONAL: If you upload an image that has a name like agreatimage-234.jpg, the following line removes everything after the dash, so you just get "agreatimage"
  //$str_name = array_shift(explode('-', $filename));

  //Create the query
  $args = array(
    'post_type' => 'product',
    'meta_key' => '_sku',
    'meta_value' => $filename, //replace this with $str_name to get the functionality of the commented out line
    'meta_compare' => 'LIKE' //find all products with a SKU that is similar to the name of the image
  );

  //Get all the products using the query above
  $prods = get_posts( $args );

  //If no products were found and if there is more than one product
  if ( ! empty($prods) && count($prods) > 1) {
    //Loop through each one
    foreach ($prods as $product) {
        //If it already has a thumbnail, delete it
        if (has_post_thumbnail($product)) {
            delete_post_thumbnail($product);
        }
        // set the new thumbnail for the product
        set_post_thumbnail( $product, $attachmentID );

        //Attach the image to the product(?)
        $attachment = get_post( $attachmentID );
        $attachment->post_parent = $product->ID;
        wp_update_post( $attachment );          
    }
  //If there is only one product
  } else if (! empty($prods) && count($prods) == 1){
    //Take that product out of the array
    $product = array_pop( $prods );
    //Do the same
    if (has_post_thumbnail($product)) {
        delete_post_thumbnail($product);
    }
    set_post_thumbnail( $product, $attachmentID );

    $attachment = get_post( $attachmentID );
    $attachment->post_parent = $product->ID;
    wp_update_post( $attachment );
    //If no products were found, copy the name of the image to a file in the theme so that we know which images did not have a match
    } else {
        $no_match_file = get_stylesheet_directory();
        $no_match_file .= '/no_match_woo.log';
        $no_match = $src[0];
        file_put_contents($no_match_file, print_r($no_match, true), FILE_APPEND);
    }
});