Skip to content

Instantly share code, notes, and snippets.

@crazyyy
Last active September 21, 2024 21:03
Show Gist options
  • Save crazyyy/d2e83531317513383490de37d87cdd5d to your computer and use it in GitHub Desktop.
Save crazyyy/d2e83531317513383490de37d87cdd5d to your computer and use it in GitHub Desktop.
#wordpress #php || Snipets

Other Snippets

If / Else load Pages

  if ( is_front_page() && is_home() ){
      // Default homepage
  } elseif ( is_front_page()){
      //Static homepage
  } elseif ( is_home()){
      //Blog page
  } else {
      //everything else
  }

Query Monitor Debuger

Logging Variables https://querymonitor.com/docs/logging-variables/

qm/emergency qm/alert qm/critical qm/error qm/warning qm/notice qm/info qm/debug

do_action( 'qm/warning', 'Warning );
do_action( 'qm/info', 'Title' );
do_action( 'qm/debug', $variable );

if ( is_wp_error( $response ) ) {
    do_action( 'qm/error', $response );
}

try {
    // your code
} catch ( Exception $e ) {
    do_action( 'qm/error', $e );
}

Profiling with Query Monitor

// Start the 'foo' timer:
do_action( 'qm/start', 'foo' );

// Run some code
my_potentially_slow_function();

// Stop the 'foo' timer:
do_action( 'qm/stop', 'foo' );

Include

<?php include(TEMPLATEPATH.'/pagenavi.php'); ?>
<?php include_once('advanced-custom-fields/acf.php'); ?>

echo json multistring to ajax call

echo json_encode(array('loggedin' => true, 'message' => $phone, 'user_id' => $user_signon->ID));

enqueue script or style

add_action('init', 'gutschlafen_enqueue_theme_scripts_170921');
function gutschlafen_enqueue_theme_scripts_170921()
{

  //core
  wp_enqueue_script( 'jquery' );

  // Better to use local jquery
  //wp_register_script('jquery', '//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js', array(), '3.4.1');
  //wp_enqueue_script('jquery');
  // wp_deregister_script('jquery');
  // wp_deregister_script('jquery-migrate');
  //wp_deregister_script('modernizr');
  wp_deregister_script('jquery-form');

  wp_enqueue_script('select2', THEME_URL . '/assets/js/libs/select2.min.js', array('jquery'), '1.0.0', true);
  wp_enqueue_script('fancybox', THEME_URL . '/assets/js/libs/fancybox.umd.min.js', array('jquery'), '1.0.0', true);
  wp_enqueue_script('swiper', THEME_URL . '/assets/js/libs/swiper-bundle.min.js', array('jquery'), '1.0.0', true);
  wp_enqueue_script('wishlist', THEME_URL . '/assets/js/wishlist.js', array('jquery'), filemtime( get_stylesheet_directory() . '/assets/js/wishlist.js'), true);
  // Theme main scripts file
  wp_enqueue_script('wpeScripts', THEME_URL . '/assets/js/main.js', array('jquery', 'select2', 'fancybox', 'swiper', 'wishlist'), filemtime( get_stylesheet_directory() . '/assets/js/main.js'), true);

  wp_localize_script('wpeScripts', 'adminAjax', array(
    'ajaxurl' => admin_url('admin-ajax.php'),
    'templatePath' => THEME_URL,
    'posts_per_page' => get_option('posts_per_page')
  ));
}

debug function

debug($data);

function debug($data){
    echo '<pre>'. print_r($data, 1) .'</pre>';
}

custom single template by category

// http://saitobaza.ru/specialnyj-shablon-zapisej-dlya-opredelennyx-kategorij-wordpress.htm
add_filter('single_template', 'check_for_category_single_template');
function check_for_category_single_template( $t )
{
  foreach( (array) get_the_category() as $cat )
  {
    if ( file_exists(TEMPLATEPATH . "/single-category-{$cat->slug}.php") ) return TEMPLATEPATH . "/single-category-{$cat->slug}.php";
    if($cat->parent)
    {
      $cat = get_the_category_by_ID( $cat->parent );
      if ( file_exists(TEMPLATEPATH . "/single-category-{$cat->slug}.php") ) return TEMPLATEPATH . "/single-category-{$cat->slug}.php";
    }
  }
  return $t;
}

Search and Replace text

  function replace_text_wps($text){
    $replace = array(
      // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
      'wordpress' => '<a href="#">wordpress</a>',
      'excerpt' => '<a href="#">excerpt</a>',
      'function' => '<a href="#">function</a>'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
  }
  add_filter('the_content', 'replace_text_wps');
  add_filter('the_excerpt', 'replace_text_wps');

ACF get uploaded file size

  <?php
    $attachment_id = get_field('dl-fb2');
    $url = wp_get_attachment_url( $attachment_id );
    $title = get_the_title( $attachment_id );
    $myfile = filesize( get_attached_file( $attachment_id ) );
    $bytes = size_format($myfile, 2);
    if(get_field('dl-fb2')) { ?>

    <tr>
        <td><a href="<?php echo $url; ?>" title="<?php echo $title; ?>">Скачать в формате fb2</a></td>
        <td>Размер файла: <?php echo $bytes; ?></td>
    </tr>

  <?php } ?>

set ACF images gallery and add post thumbains

  $ids = get_posts(
      array(
      'post_type'      => 'attachment',
      'post_mime_type' => 'image',
      'post_status'    => 'inherit',
      'posts_per_page' => -1,
      'fields'         => 'ids',
    )
  );
  $media_libriary_images = array();
  foreach ($ids as $id) {
      $media_libriary_images[]= $id;
  }

  query_posts("showposts=20&post_type=product");
  if (have_posts()) : while (have_posts()) : the_post();
    shuffle($media_libriary_images);
    $post_gallery_images = $media_libriary_images;
    $random_number = random_int(0, 10);
    $post_gallery_images = array_slice($post_gallery_images, $random_number);

    $post_id = get_the_ID();
    $gallery_array = get_field('gallery', $post_id, false);

    echo '<pre>';
    print_r($gallery_array);
    echo '</pre>';

    if (!is_array($gallery_array)) {
        $gallery_array = array();
    }

    update_field('gallery', $gallery_array, $post_id);
    update_post_meta($post_id, '_thumbnail_id', $post_gallery_images[0]);

  endwhile;
  endif;
  wp_reset_query();

wordpress copy taxonomies beetween terms

$terms_filter = get_terms(array(
  'taxonomy'      => array( 'dclass' ), // название таксономии с WP 4.5
  'orderby'       => 'id',
  'order'         => 'ASC',
  'hide_empty'    => false,
  'object_ids'    => null,
  'include'       => array(),
  'exclude'       => array(),
  'exclude_tree'  => array(),
  'number'        => '',
  'fields'        => 'all',
  'count'         => false,
  'slug'          => '',
  'parent'         => '',
  'hierarchical'  => true,
  'child_of'      => 0,
  'get'           => '', // ставим all чтобы получить все термины
  'name__like'    => '',
  'pad_counts'    => false,
  'offset'        => '',
  'search'        => '',
  'cache_domain'  => 'core',
  'name'          => '',    // str/arr поле name для получения термина по нему. C 4.2.
  'childless'     => false, // true не получит (пропустит) термины у которых есть дочерние термины. C 4.2.
  'update_term_meta_cache' => true, // подгружать метаданные в кэш
  'meta_query'    => '',
));

foreach ($terms_filter as $term) {
  echo $term->name;  wp_set_object_terms( 410, $term->name, 'product_drug_class' );
}

ajax example

/*
 * Обрабатываем AJAX-запрос типа ncAction
 */
add_action( 'wp_ajax_ncAction', 'ncAction_callback' );
add_action( 'wp_ajax_nopriv_ncAction', 'ncAction_callback' );
function ncAction_callback() {
  $args = wp_parse_args( $_POST, array(
    'test' => false,
  ) );

  $result = array(
    'test' => $args['test'],
  );

  if ( $result['test'] ) {
    wp_send_json_success( $result );
  } else {
    wp_send_json_error( $result );
  }
}
/*
 * Отправляем AJAX-запрос типа ncAction
 */
$.ajax({
    type: 'POST',
    url: ncVar.ajaxurl,
    data: {
        'test': 'Hello, world!',
        'action': 'ncAction',
    },
    dataType: 'json',
    success: function(result) {
        console.log('success: ' + result.success);
        console.log(result.data);
    }
});

Load post with AJAX

<?php
  add_action('wp_ajax_get_new', 'get_new');
  add_action('wp_ajax_nopriv_get_new', 'get_new'); // not really needed

  function get_new() {

    // args
    $args = array(
      'post_type' => 'product',
      'showposts' => 100,
      'meta_query' => array(
        array(
          'key' => 'new',
          'value' => '1',
          'compare' => '=='
        )
      )
    );

    // query
    $the_query = new WP_Query( $args );

    if( $the_query->have_posts() ):
      while( $the_query->have_posts() ) : $the_query->the_post();

        if ( has_post_thumbnail()) {
          $post_thumbnail_id = get_post_thumbnail_id( $post );
          $image = '<img src="'. wp_get_attachment_image_url( $post_thumbnail_id, "medium" ) .'" title="'. get_the_title() .'" alt="'. get_the_title() .'" />';
        } else {
          $image = '<img src="'. catchFirstImage() .'" title="'. the_title() .'" alt="'. the_title() .'" />';
        }
        if( get_field('sale') ) {
          $action = '<span class="action upper fira-bold">НА АКЦИИ</span>';
        } else {
          $action = '';
        }

        $output = $output .'<div id="post-'. get_the_ID() .'" class="col-xs-6 col-md-4 nopadding card-product__img card-product__img--cat">
          <a href="'. get_the_permalink() .'">'. $image .'
            '. $action .'
            <span class="num upper fira-bold">'. get_the_title() .'</span>
            <i class="ic ic-loop"></i>
          </a>
          <a href="#" class="like" like-id="'. get_the_ID() .'"><i class="ic ic-like"></i></a>
        </div><!-- end card-product__img -->';
      endwhile;
    endif;

    // Reset Query
    wp_reset_query();
    die($output);
  }
$(document).ready(function() {

    $(".sidebar-links--new").click(function(e) {
        e.preventDefault();
        var category = '<?php echo strtolower($category); ?>';
        // var id              = '<?php echo $blogger_id; ?>';
        // var firstname       = '<?php echo $firstname; ?>';
        // var surname         = '<?php echo $surname; ?>';
        // alert(posts + category + id + firstname + surname);
        $.ajax({
            type: "GET",
            url: "http://curtains.dev/wp-admin/admin-ajax.php",
            dataType: 'html',
            data: ({
                action: 'get_new',
                id: 46
                // firstname: firstname,
                // surname: surname,
                // posts: posts,
                // category: category
            }),

            success: function(data) {
                $('.card-product__img--cat').hide('fast');
                $('.card-products-cat-wrap').hide().fadeIn('slow').html(data);
                $('.card-products-cat-wrap').append('<div className="clearfix"></div>');
            }
        });

    });
});

wp_parse_args

$default_args = array('status' => null, 'customer_id' => null, 'customer_note' => null, 'parent' => null, 'created_via' => null, 'cart_hash' => null, 'order_id' => 0);
    $args = wp_parse_args($args, $default_args);
    $order = new WC_Order($args['order_id']);

Error example

if (!$customer_id) {
    return new WP_Error('simplify_error', __('Customer not found', 'woocommerce'));
}

Loading jQuery from the Google CDN

// Even more smart jQuery inclusion :)
add_action( 'init', 'jquery_register' );
// Register from Google and for footer
function jquery_register() {
  if ( !is_admin() ) {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', ( '//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js' ), false, '3.6.0', true );
    wp_enqueue_script( 'jquery' );
  }
}

Add Thumbnails in Manage Posts/Pages List

if ( !function_exists('add_thumb_column') && function_exists('add_theme_support') ) {
    // for post and page
    add_theme_support('post-thumbnails', array( 'post', 'page' ) );
    function add_thumb_column($cols) {
        $cols['thumbnail'] = __('Thumbnail');
        return $cols;
    }

    function add_thumb_value($column_name, $post_id) {
            $width = (int) 35;
            $height = (int) 35;

            if ( 'thumbnail' == $column_name ) {
                // thumbnail of WP 2.9
                $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
                // image from gallery
                $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
                if ($thumbnail_id)
                    $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
                elseif ($attachments) {
                    foreach ( $attachments as $attachment_id => $attachment ) {
                        $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
                    }
                }
                    if ( isset($thumb) && $thumb ) {
                        echo $thumb;
                    } else {
                        echo __('None');
                    }
            }
    }

    // for posts
    add_filter( 'manage_posts_columns', 'add_thumb_value' );
    add_action( 'manage_posts_custom_column', 'add_thumb_value', 10, 2 );

    // for pages
    add_filter( 'manage_pages_columns', 'add_thumb_value' );
    add_action( 'manage_pages_custom_column', 'add_thumb_value', 10, 2 );
}

Remove pings to your own blog

// Remove pings to self
function no_self_ping( &$links ) {
    $home = get_option( 'home' );
    foreach ( $links as $l => $link )
        if ( 0 === strpos( $link, $home ) )
            unset($links[$l]);
}
add_action( 'pre_ping', 'no_self_ping' );

Remove unwanted dashboard items

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');
function my_custom_dashboard_widgets() {
    global $wp_meta_boxes;
    // Right Now - Comments, Posts, Pages at a glance
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
    // Recent Comments
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
    // Incoming Links
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
    // Plugins - Popular, New and Recently updated Wordpress Plugins
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
    // WordPress Development Blog Feed
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
    // Other WordPress News Feed
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
    // Quick Press Form
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
    // Recent Drafts List
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);
}

Remove superfluous info and HTML within the <head> tag

add_action( 'init', 'remove_header_info' );
function remove_header_info() {
    remove_action( 'wp_head', 'rsd_link' );
    remove_action( 'wp_head', 'wlwmanifest_link' );
    remove_action( 'wp_head', 'wp_generator' );
    remove_action( 'wp_head', 'start_post_rel_link' );
    remove_action( 'wp_head', 'index_rel_link' );
    remove_action( 'wp_head', 'adjacent_posts_rel_link' );         // for WordPress < 3.0
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head' ); // for WordPress >= 3.0
}

register custom favicons from theme folder

function set_custom_generated_favicons() {
    echo '<link rel="apple-touch-icon" sizes="180x180" href="' . BNM_THEME_DIRECTORY . '/img/favicon/apple-touch-icon.png">';
    echo '<link rel="icon" type="image/png" sizes="32x32" href="' . BNM_THEME_DIRECTORY . '/img/favicon/favicon-32x32.png">';
    echo '<link rel="icon" type="image/png" sizes="16x16" href="' . BNM_THEME_DIRECTORY . '/img/favicon/favicon-16x16.png">';
    echo '<link rel="manifest" href="' . BNM_THEME_DIRECTORY . '/img/favicon/site.webmanifest">';
    echo '<link rel="mask-icon" href="' . BNM_THEME_DIRECTORY . '/img/favicon/safari-pinned-tab.svg" color="#5bbad5">';
    echo '<meta name="apple-mobile-web-app-title" content="Brands &amp; Madrid">';
    echo '<meta name="application-name" content="Brands &amp; Madrid">';
    echo '<meta name="msapplication-TileColor" content="#da532c">';
    echo '<meta name="theme-color" content="#ffffff">';
}
add_filter( 'wp_head' , 'set_custom_generated_favicons' );

// remove default favicon ability
//function remove_sections_favicon($wp_customize) {
//    $wp_customize->remove_control('site_icon');
//}
//add_action( 'customize_register', 'remove_sections_favicon', 20, 1 );

add preconect and prefetch to head

// add preconect and prefetch to head
function add_preconect_prefetch(){
    echo '<link rel="dns-prefetch" href="http://cloudflare.com">';
    echo '<link rel="preconnect" href="https://cdnjs.cloudflare.com">';
}
add_filter( 'wp_head' , 'add_preconect_prefetch' );

replace all style tags with preloader

function add_style_attr_rel_preload($html, $handle, $href, $media) {
    if (is_admin()) {
        return $html;
    }
    $html = '<link rel="preload" as="style" onload="this.onload=null;this.rel=\'stylesheet\'" id=' . $handle . ' href="' . $href . '" type="text/css" media="all" />';
    return $html;
}
add_filter( 'style_loader_tag', 'add_style_attr_rel_preload', 10, 4 );

enqueue scripts

if ( ! defined( '_WPE_THEME_URI' ) ) {
    define( '_WPE_THEME_URI', get_template_directory_uri() );
}

if ( ! defined( '_S_VERSION' ) ) {
    // Replace the version number of the theme on each release.
    define( '_S_VERSION', '1.2.0' );
}

function wpe_enque_scripts() {
    wp_enqueue_style( 'bnm-style', _WPE_THEME_URI . '/css/main.css', array(), _S_VERSION );

    wp_dequeue_script( 'jquery' );
    wp_dequeue_script( 'jquery-core' );
    wp_deregister_script( 'jquery' );
    wp_enqueue_script( 'jquery', '//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js', array(), '3.6.0', true );

    wp_register_script( 'wpe-main', _WPE_THEME_URI . '/js/main.js', array('jquery'), _S_VERSION, $in_footer = true );

    $public_settings = array(
        'custom_variable' => 'custom_variable_value',
        'ajax' => array(
          'url' => admin_url('admin-ajax.php'),
          'nonce' => wp_create_nonce('wpe-nonce')
        )
    );
    wp_localize_script( 'wpe-main', 'wpeSettings', $public_settings );
    wp_enqueue_script( 'wpe-main' );
}
add_action( 'wp_enqueue_scripts', 'wpe_enque_scripts' );

deregister useless styles

function deregister_useless_styles() {
    wp_dequeue_style('full-screen-search');
    wp_dequeue_style('prettyPhoto');
    wp_deregister_style('full-screen-search');
    wp_deregister_style('prettyPhoto');
}
add_action( 'wp_print_styles', 'deregister_useless_styles', 100 );

async and defer js load

 function add_async_attribute($tag, $handle) {
   // add script handles to the array below
   $scripts_to_async = array('my-js-handle', 'another-handle');

   foreach($scripts_to_async as $async_script) {
      if ($async_script === $handle) {
         return str_replace(' src', ' async="async" src', $tag);
        //  return str_replace(' src', ' defer="defer" src', $tag);
      }
   }
   return $tag;
}
add_filter('script_loader_tag', 'add_async_attribute', 10, 2);

insert script after page loaded

// defer script loading
function load_script_after_page_loaded($tag, $handle, $src) {
    // add script handles to the array below
    $scripts_to_defer = array(
        'bnm-compiled',
        'bnm-main',
    );

    foreach($scripts_to_defer as $defer_script) {
        if ($defer_script === $handle) {
            return $tag = '<script>if(document.addEventListener){console.log("'.$handle.'"); window.addEventListener("DOMContentLoaded", function() {var s = document.createElement("script");s.src = "' . $src . '";document.body.appendChild(s);});}</script>';
        }
    }

    return $tag;
}
add_filter('script_loader_tag', 'load_script_after_page_loaded', 10, 3);

Duplicate Order functionality for WooCommerce

https://gist.github.com/gerdneuman/9406ff1964ccbfe8fef83e7dd020f724

/**
 * Duplicate order functionality
 *
 * @author      WooThemes
 * @category    Admin
 * @package     WooCommerce/Admin
 * @version     2.7.0
 */

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

if ( ! class_exists( 'WC_Admin_Duplicate_Order' ) ) :

/**
 * WC_Admin_Duplicate_Order Class.
 */
class WC_Admin_Duplicate_Order {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_action_duplicate_order', array( $this, 'duplicate_order_action' ) );
		add_filter( 'post_row_actions', array( $this, 'dupe_link' ), 10, 2 );
		add_filter( 'page_row_actions', array( $this, 'dupe_link' ), 10, 2 );

    // TODO: This should probably go directly into includes/admin/meta-boxes/class-wc-meta-box-order-actions.php
    // directly above the delete_action
    // Cannot use the 'woocommerce_order_actions_start' hook as it does not retain the same order as for
    // duplicationg products
		add_action( 'post_submitbox_start', array( $this, 'dupe_button' ) );
	}

	/**
	 * Show the "Duplicate" link in admin orders list.
	 * @param  array   $actions
	 * @param  WP_Post $post Post object
	 * @return array
	 */
	public function dupe_link( $actions, $post ) {
		// TODO: Add new permission woocommerce_duplicate_order_capability
		if ( ! current_user_can( apply_filters( 'woocommerce_duplicate_product_capability', 'manage_woocommerce' ) ) ) {
			return $actions;
		}

		if ( $post->post_type != 'shop_order' ) {
			return $actions;
		}

		$actions['duplicate'] = '<a href="' . wp_nonce_url( admin_url( 'edit.php?post_type=shop_order&action=duplicate_order&amp;post=' . $post->ID ), 'woocommerce-duplicate-order_' . $post->ID ) . '" title="' . esc_attr__( 'Make a duplicate from this order', 'woocommerce' )
			. '" rel="permalink">' .  __( 'Duplicate', 'woocommerce' ) . '</a>';

		return $actions;
	}

	/**
	 * Show the dupe order link in admin.
	 */
	public function dupe_button() {
		global $post;

		// TODO: Add new permission woocommerce_duplicate_order_capability
		if ( ! current_user_can( apply_filters( 'woocommerce_duplicate_product_capability', 'manage_woocommerce' ) ) ) {
			return;
		}

		if ( ! is_object( $post ) ) {
			return;
		}

		if ( $post->post_type != 'shop_order' ) {
			return;
		}

		if ( isset( $_GET['post'] ) ) {
			$notifyUrl = wp_nonce_url( admin_url( "edit.php?post_type=shop_order&action=duplicate_order&post=" . absint( $_GET['post'] ) ), 'woocommerce-duplicate-order_' . $_GET['post'] );
			?>
			<div id="duplicate-action"><a class="submitduplicate duplication" href="<?php echo esc_url( $notifyUrl ); ?>"><?php _e( 'Copy to a new draft', 'woocommerce' ); ?></a></div>
			<?php
		}
	}

	/**
	 * Duplicate a order action.
	 */
	public function duplicate_order_action() {

		if ( empty( $_REQUEST['post'] ) ) {
			wp_die( __( 'No order to duplicate has been supplied!', 'woocommerce' ) );
		}

		// Get the original page
		$id = isset( $_REQUEST['post'] ) ? absint( $_REQUEST['post'] ) : '';

		check_admin_referer( 'woocommerce-duplicate-order_' . $id );

		$post = wc_get_order( $id );

		// Copy the page and insert it
		if ( ! empty( $post ) ) {
			$new_id = $this->duplicate_order( $post );

			// If you have written a plugin which uses non-WP database tables to save
			// information about a page you can hook this action to dupe that data.
			// TODO: Document this hook
			do_action( 'woocommerce_duplicate_order', $new_id, $post );

			// Redirect to the edit screen for the new draft page
			wp_redirect( admin_url( 'post.php?action=edit&post=' . $new_id ) );
			exit;
		} else {
			wp_die( __( 'Order creation failed, could not find original order:', 'woocommerce' ) . ' ' . $id );
		}
	}

	/**
	 * Function to create the duplicate of the order.
	 *
	 * @param mixed $post
	 * @return int
	 */
	public function duplicate_order( $post ) {
		global $wpdb;

		$original_order_id = $post->id;
		$original_order = $post;

		$order_id = $this->create_order($original_order_id);

		if ( is_wp_error( $order_id ) ){
			$msg = 'Unable to create order: ' . $order_id->get_error_message();;
			throw new Exception( $msg );
		} else {

			$order = new WC_Order($order_id);

			$this->duplicate_order_header($original_order_id, $order_id);
			$this->duplicate_billing_fieds($original_order_id, $order_id);
			$this->duplicate_shipping_fieds($original_order_id, $order_id);

			$this->duplicate_line_items($original_order, $order_id);
			$this->duplicate_shipping_items($original_order, $order_id);
			$this->duplicate_coupons($original_order, $order_id);
			$this->duplicate_payment_info($original_order_id, $order_id, $order);
      $order->calculate_taxes();
			$this->add_order_note($original_order_id, $order);

			return $order_id;
		}
	}

	private function create_order($original_order_id) {
		$new_post_author    = wp_get_current_user();
		$new_post_date      = current_time( 'mysql' );
		$new_post_date_gmt  = get_gmt_from_date( $new_post_date );

		$order_data =  array(
			'post_author'   => $new_post_author->ID,
			'post_date'     => $new_post_date,
			'post_date_gmt' => $new_post_date_gmt,
			'post_type'     => 'shop_order',
			'post_title'    => __( 'Duplicate Order', 'woocommerce' ),
			/* 'post_status'   => 'draft', */
			'post_status'   => 'pending',
			'ping_status'   => 'closed',
			/* 'post_excerpt'  => 'Duplicate Order based on original order ' . $original_order_id, */
			'post_password' => uniqid( 'order_' ),   // Protects the post just in case
			'post_modified'             => $new_post_date,
			'post_modified_gmt'         => $new_post_date_gmt
		);

		$new_post_id = wp_insert_post( $order_data, true );

		return $new_post_id;
	}

	private function duplicate_order_header($original_order_id, $order_id) {
		update_post_meta( $order_id, '_order_shipping',         get_post_meta($original_order_id, '_order_shipping', true) );
		update_post_meta( $order_id, '_order_discount',         get_post_meta($original_order_id, '_order_discount', true) );
		update_post_meta( $order_id, '_cart_discount',          get_post_meta($original_order_id, '_cart_discount', true) );
		update_post_meta( $order_id, '_order_tax',              get_post_meta($original_order_id, '_order_tax', true) );
		update_post_meta( $order_id, '_order_shipping_tax',     get_post_meta($original_order_id, '_order_shipping_tax', true) );
		update_post_meta( $order_id, '_order_total',            get_post_meta($original_order_id, '_order_total', true) );

		update_post_meta( $order_id, '_order_key',              'wc_' . apply_filters('woocommerce_generate_order_key', uniqid('order_') ) );
		update_post_meta( $order_id, '_customer_user',          get_post_meta($original_order_id, '_customer_user', true) );
		update_post_meta( $order_id, '_order_currency',         get_post_meta($original_order_id, '_order_currency', true) );
		update_post_meta( $order_id, '_prices_include_tax',     get_post_meta($original_order_id, '_prices_include_tax', true) );
		update_post_meta( $order_id, '_customer_ip_address',    get_post_meta($original_order_id, '_customer_ip_address', true) );
		update_post_meta( $order_id, '_customer_user_agent',    get_post_meta($original_order_id, '_customer_user_agent', true) );
	}

	private function duplicate_billing_fieds($original_order_id, $order_id) {
		update_post_meta( $order_id, '_billing_city',           get_post_meta($original_order_id, '_billing_city', true));
		update_post_meta( $order_id, '_billing_state',          get_post_meta($original_order_id, '_billing_state', true));
		update_post_meta( $order_id, '_billing_postcode',       get_post_meta($original_order_id, '_billing_postcode', true));
		update_post_meta( $order_id, '_billing_email',          get_post_meta($original_order_id, '_billing_email', true));
		update_post_meta( $order_id, '_billing_phone',          get_post_meta($original_order_id, '_billing_phone', true));
		update_post_meta( $order_id, '_billing_address_1',      get_post_meta($original_order_id, '_billing_address_1', true));
		update_post_meta( $order_id, '_billing_address_2',      get_post_meta($original_order_id, '_billing_address_2', true));
		update_post_meta( $order_id, '_billing_country',        get_post_meta($original_order_id, '_billing_country', true));
		update_post_meta( $order_id, '_billing_first_name',     get_post_meta($original_order_id, '_billing_first_name', true));
		update_post_meta( $order_id, '_billing_last_name',      get_post_meta($original_order_id, '_billing_last_name', true));
		update_post_meta( $order_id, '_billing_company',        get_post_meta($original_order_id, '_billing_company', true));
	}

	private function duplicate_shipping_fieds($original_order_id, $order_id) {
		update_post_meta( $order_id, '_shipping_country',       get_post_meta($original_order_id, '_shipping_country', true));
		update_post_meta( $order_id, '_shipping_first_name',    get_post_meta($original_order_id, '_shipping_first_name', true));
		update_post_meta( $order_id, '_shipping_last_name',     get_post_meta($original_order_id, '_shipping_last_name', true));
		update_post_meta( $order_id, '_shipping_company',       get_post_meta($original_order_id, '_shipping_company', true));
		update_post_meta( $order_id, '_shipping_address_1',     get_post_meta($original_order_id, '_shipping_address_1', true));
		update_post_meta( $order_id, '_shipping_address_2',     get_post_meta($original_order_id, '_shipping_address_2', true));
		update_post_meta( $order_id, '_shipping_city',          get_post_meta($original_order_id, '_shipping_city', true));
		update_post_meta( $order_id, '_shipping_state',         get_post_meta($original_order_id, '_shipping_state', true));
		update_post_meta( $order_id, '_shipping_postcode',      get_post_meta($original_order_id, '_shipping_postcode', true));
	}

  // TODO: same as duplicating order from user side
	private function duplicate_line_items($original_order, $order_id) {
		foreach($original_order->get_items() as $originalOrderItem){
			$itemName = $originalOrderItem['name'];
			$qty = $originalOrderItem['qty'];
			$lineTotal = $originalOrderItem['line_total'];
			$lineTax = $originalOrderItem['line_tax'];
			$productID = $originalOrderItem['product_id'];

			$item_id = wc_add_order_item( $order_id, array(
					'order_item_name'       => $itemName,
					'order_item_type'       => 'line_item'
			) );

			wc_add_order_item_meta( $item_id, '_qty', $qty );
      // TODO: Is it ok to uncomment this?
			wc_add_order_item_meta( $item_id, '_tax_class', $originalOrderItem['tax_class'] );
			wc_add_order_item_meta( $item_id, '_product_id', $productID );
      // TODO: Is it ok to uncomment this?
			wc_add_order_item_meta( $item_id, '_variation_id', $originalOrderItem['variation_id'] );
			wc_add_order_item_meta( $item_id, '_line_subtotal', wc_format_decimal( $lineTotal ) );
			wc_add_order_item_meta( $item_id, '_line_total', wc_format_decimal( $lineTotal ) );
			/* wc_add_order_item_meta( $item_id, '_line_tax', wc_format_decimal( '0' ) ); */
			wc_add_order_item_meta( $item_id, '_line_tax', wc_format_decimal( $lineTax ) );
      // TODO: Is it ok to uncomment this?
			/* wc_add_order_item_meta( $item_id, '_line_subtotal_tax', wc_format_decimal( '0' ) ); */
			wc_add_order_item_meta( $item_id, '_line_subtotal_tax', wc_format_decimal( $originalOrderItem['line_subtotal_tax'] ) );
		}

    // TODO This is what is in order_again of class-wc-form-handler.php
    // Can it be reused or refactored into own function?
    //
		// Copy products from the order to the cart
		/* foreach ( $order->get_items() as $item ) { */
		/* 	// Load all product info including variation data */
		/* 	$product_id   = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $item['product_id'] ); */
		/* 	$quantity     = (int) $item['qty']; */
		/* 	$variation_id = (int) $item['variation_id']; */
		/* 	$variations   = array(); */
		/* 	$cart_item_data = apply_filters( 'woocommerce_order_again_cart_item_data', array(), $item, $order ); */

		/* 	foreach ( $item['item_meta'] as $meta_name => $meta_value ) { */
		/* 		if ( taxonomy_is_product_attribute( $meta_name ) ) { */
		/* 			$variations[ $meta_name ] = $meta_value[0]; */
		/* 		} elseif ( meta_is_product_attribute( $meta_name, $meta_value[0], $product_id ) ) { */
		/* 			$variations[ $meta_name ] = $meta_value[0]; */
		/* 		} */
		/* 	} */
	}

	private function duplicate_shipping_items($original_order, $order_id) {
		$original_order_shipping_items = $original_order->get_items('shipping');

		foreach ( $original_order_shipping_items as $original_order_shipping_item ) {
			$item_id = wc_add_order_item( $order_id, array(
				'order_item_name'       => $original_order_shipping_item['name'],
				'order_item_type'       => 'shipping'
			) );
			if ( $item_id ) {
				wc_add_order_item_meta( $item_id, 'method_id', $original_order_shipping_item['method_id'] );
				wc_add_order_item_meta( $item_id, 'cost', wc_format_decimal( $original_order_shipping_item['cost'] ) );

        // TODO: Does not store the shipping taxes
				/* wc_add_order_item_meta( $item_id, 'taxes', $original_order_shipping_item['taxes'] ); */
			}
		}
	}

	private function duplicate_coupons($original_order, $order_id) {
		$original_order_coupons = $original_order->get_items('coupon');
		foreach ( $original_order_coupons as $original_order_coupon ) {
			$item_id = wc_add_order_item( $order_id, array(
				'order_item_name'       => $original_order_coupon['name'],
				'order_item_type'       => 'coupon'
			) );
			// Add line item meta
			if ( $item_id ) {
				wc_add_order_item_meta( $item_id, 'discount_amount', $original_order_coupon['discount_amount'] );
			}
		}
	}

	private function duplicate_payment_info($original_order_id, $order_id, $order) {
		update_post_meta( $order_id, '_payment_method',         get_post_meta($original_order_id, '_payment_method', true) );
		update_post_meta( $order_id, '_payment_method_title',   get_post_meta($original_order_id, '_payment_method_title', true) );
		/* update_post_meta( $order->id, 'Transaction ID',         get_post_meta($original_order_id, 'Transaction ID', true) ); */
		/* $order->payment_complete(); */
	}

	private function add_order_note($original_order_id, $order) {
		$updateNote = 'This order was duplicated from order ' . $original_order_id . '.';
		/* $order->update_status('processing'); */
		$order->add_order_note($updateNote);
	}

}

endif;

return new WC_Admin_Duplicate_Order();

Meta

Display all post meta keys and meta values of the same post ID in wordpress

Get the meta for all keys:

$meta = get_post_meta($post_id);

Get the meta for a single key:

$key_1_values = get_post_meta( 76, 'key_1' );

Display all post meta keys and meta values of the same post ID in wordpress

$myvals = get_post_meta($post_id);
foreach($myvals as $key=>$val)
{
    echo $key . ' : ' . $val[0] . '<br/>';
}

get all Meta from post

$meta_values = get_post_meta( get_the_ID() );
var_dump( $meta_values );

get and show all post meta

$myvals = get_post_meta( get_the_ID());
foreach($myvals as $key=>$val){
  foreach($val as $vals){
    if ($key=='Youtube'){
       echo $vals
    }
   }
}

get_post_meta() https://wp-kama.ru/function/get_post_meta

Set random taxonomy ter from loop taxonoies for custom post type

  $array_taxonomy_terms = ['product_category', 'product_pet', 'product_brand', 'product_condition', 'product_form', 'product_drug_class', 'product_prescription', 'product_flavor', 'product_lifestage', 'product_breed', 'product_dimension'];

  foreach ($array_taxonomy_terms as $taxonomy_terms) {
      $get_all_terms = get_terms(array(
    'taxonomy'      => array( $taxonomy_terms),
    'orderby'       => 'id',
    'order'         => 'ASC',
    'hide_empty'    => false,
    'object_ids'    => null,
    'include'       => array(),
    'exclude'       => array(),
    'exclude_tree'  => array(),
    'number'        => '',
    'fields'        => 'all',
    'count'         => false,
    'slug'          => '',
    'parent'         => '',
    'hierarchical'  => true,
    'child_of'      => 0,
    'get'           => '',
    'name__like'    => '',
    'pad_counts'    => false,
    'offset'        => '',
    'search'        => '',
    'cache_domain'  => 'core',
    'name'          => '',
    'childless'     => false,
    'update_term_meta_cache' => true,
    'meta_query'    => '',
  ));

      $elements_in_array_count = sizeof($get_all_terms);
      if ($elements_in_array_count > 4) {
          $elements_in_array_count =  intval($elements_in_array_count / 2);
      }

      query_posts("showposts=20&post_type=product");
      if (have_posts()) : while (have_posts()) : the_post();
      shuffle($get_all_terms);
      $category_tax_features = get_taxonomy($get_all_terms[0]->taxonomy);

      if ($get_all_terms[0]->taxonomy === 'product_category') {
          //echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[0]->name. "<br>";
        //wp_set_object_terms( get_the_ID(), $get_all_terms[0]->name, $get_all_terms[0]->taxonomy );
      }

      if ($get_all_terms[0]->taxonomy === 'product_pet') {
//          $random_number_taxonomy_add = random_int(1, $elements_in_array_count);
//          $i = 0;
//          while ($i < $random_number_taxonomy_add) {
//              echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[$i]->name. "<br>";
//              wp_set_object_terms(get_the_ID(), $get_all_terms[$i]->name, $get_all_terms[$i]->taxonomy);
//              $i++;
//          }
      }

      if ($get_all_terms[0]->taxonomy === 'product_brand') {
//          $random_number_taxonomy_add = random_int(1, $elements_in_array_count);
//          $i = 1;
//          while ($i < $random_number_taxonomy_add) {
//              echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[$i]->name. "<br>";
//              wp_set_object_terms(get_the_ID(), $get_all_terms[$i]->name, $get_all_terms[$i]->taxonomy);
//              $i++;
//          }
      }

      if ($get_all_terms[0]->taxonomy === 'product_condition') {
//          $random_number_taxonomy_add = random_int(1, $elements_in_array_count);
//          $i = 0;
//          while ($i < $random_number_taxonomy_add) {
//              echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[$i]->name. "<br>";
//              wp_set_object_terms(get_the_ID(), $get_all_terms[$i]->name, $get_all_terms[$i]->taxonomy);
//              $i++;
//          }
      }

      if ($get_all_terms[0]->taxonomy === 'product_prescription') {
        echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[0]->name. "<br>";
        wp_set_object_terms( get_the_ID(), $get_all_terms[0]->name, $get_all_terms[0]->taxonomy );
      }

      if ($get_all_terms[0]->taxonomy === 'product_drug_class') {
          $random_number_taxonomy_add = random_int(1, $elements_in_array_count);
          $i = 0;
          while ($i < $random_number_taxonomy_add) {
              echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[$i]->name. "<br>";
              wp_set_object_terms(get_the_ID(), $get_all_terms[$i]->name, $get_all_terms[$i]->taxonomy);
              $i++;
          }
      }

      if ($get_all_terms[0]->taxonomy === 'product_form') {
//          $random_number_taxonomy_add = random_int(1, $elements_in_array_count);
//          $i = 0;
//          while ($i < $random_number_taxonomy_add) {
//              echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[$i]->name. "<br>";
//              wp_set_object_terms(get_the_ID(), $get_all_terms[$i]->name, $get_all_terms[$i]->taxonomy);
//              $i++;
//          }
      }

      if ($get_all_terms[0]->taxonomy === 'product_flavor') {
          $random_number_taxonomy_add = random_int(1, $elements_in_array_count);
          $i = 0;
          while ($i < $random_number_taxonomy_add) {
              echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[$i]->name. "<br>";
              wp_set_object_terms(get_the_ID(), $get_all_terms[$i]->name, $get_all_terms[$i]->taxonomy);
              $i++;
          }
      }

      if ($get_all_terms[0]->taxonomy === 'product_lifestage') {
//          $random_number_taxonomy_add = random_int(1, $elements_in_array_count);
//          $i = 0;
//          while ($i < $random_number_taxonomy_add) {
//              echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[$i]->name. "<br>";
//              wp_set_object_terms(get_the_ID(), $get_all_terms[$i]->name, $get_all_terms[$i]->taxonomy);
//              $i++;
//          }
      }

      if ($get_all_terms[0]->taxonomy === 'product_breed') {
//          $random_number_taxonomy_add = random_int(1, $elements_in_array_count);
//          $i = 0;
//          while ($i < $random_number_taxonomy_add) {
//              echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[$i]->name. "<br>";
//              wp_set_object_terms(get_the_ID(), $get_all_terms[$i]->name, $get_all_terms[$i]->taxonomy);
//              $i++;
//          }
      }
      if ($get_all_terms[0]->taxonomy === 'product_dimension') {
//          $random_number_taxonomy_add = random_int(1, $elements_in_array_count);
//          $i = 0;
//          while ($i < $random_number_taxonomy_add) {
//              echo "Post's ID: " . get_the_ID() . ", " . the_title() . " <strong>" . $category_tax_features->label . "</strong>: " . $get_all_terms[$i]->name. "<br>";
//              wp_set_object_terms(get_the_ID(), $get_all_terms[$i]->name, $get_all_terms[$i]->taxonomy);
//              $i++;
//          }
      }

      //product_condition

      endwhile;
      endif;
      wp_reset_query();
  } // end of foreach of all taxonomies

nav menu with thumbains

<div class="widget widget-sales-top">
  <h6>Топ-продаж</h6>
  <?
    // Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu)
    // This code based on wp_nav_menu's code to get Menu ID from menu slug
    $menu_name = 'sidebar-menu'; // change this if necessary

    if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
        $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
        $menu_items = wp_get_nav_menu_items($menu->term_id);
        $menu_list = '<ul id="' . $menu_name . '">';
        foreach ( (array) $menu_items as $key => $menu_item ) {
            $title = $menu_item->title;
            $url = $menu_item->url;
            $mid = $menu_item->object_id;
            if(has_post_thumbnail($mid)) {
                $thumbnail = get_the_post_thumbnail( $mid, 'thumb' );
            }
            $menu_list .= '<li><a href="' . $url . '"><span class="thumb">' .$thumbnail. '</span>' . $title . '</a></li>';
        }
        $menu_list .= '</ul>';
    } else {
        $menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
    }
    // $menu_list now ready to output
    echo $menu_list;
  ?>
</div><!-- widget widget-sales-top -->

custom navigation pagenavi

<?php
// functions.php
// http://www.wpbeginner.com/wp-themes/how-to-add-numeric-pagination-in-your-wordpress-theme/
function wpbeginner_numeric_posts_nav() {

    if( is_singular() )
        return;

    global $wp_query;

    /** Stop execution if there's only 1 page */
    if( $wp_query->max_num_pages <= 1 )
        return;

    $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
    $max     = intval( $wp_query->max_num_pages );

    /**	Add current page to the array */
    if ( $paged >= 1 )
        $links[] = $paged;

    /**	Add the pages around the current page to the array */
    if ( $paged >= 3 ) {
        $links[] = $paged - 1;
        $links[] = $paged - 2;
    }

    if ( ( $paged + 2 ) <= $max ) {
        $links[] = $paged + 2;
        $links[] = $paged + 1;
    }

    echo '<div class="navigation"><ul>' . "\n";

    /**	Previous Post Link */
    if ( get_previous_posts_link() )
        printf( '<li>%s</li>' . "\n", get_previous_posts_link() );

    /**	Link to first page, plus ellipses if necessary */
    if ( ! in_array( 1, $links ) ) {
        $class = 1 == $paged ? ' class="active"' : '';

        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );

        if ( ! in_array( 2, $links ) )
        echo '<li>…</li>';
    }

    /**	Link to current page, plus 2 pages in either direction if necessary */
    sort( $links );
    foreach ( (array) $links as $link ) {
        $class = $paged == $link ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
    }

    /**	Link to last page, plus ellipses if necessary */
    if ( ! in_array( $max, $links ) ) {
        if ( ! in_array( $max - 1, $links ) )
        echo '<li>…</li>' . "\n";

        $class = $paged == $max ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
    }

    /**	Next Post Link */
    if ( get_next_posts_link() )
        printf( '<li>%s</li>' . "\n", get_next_posts_link() );

    echo '</ul></div>' . "\n";

    }
// category.php
<?php wpbeginner_numeric_posts_nav(); ?>

Usefull Wordpress plugins

Logs and debug

Images

AMP and PWA

htaccess

Metabox

Cache

SEO

Accessibility

REST API

WooCommerce

Telegram

Frameworks

Settings

Auth

Emails

CF7

Development

Demo content

Optimize

Security

Check and troubleshoting

Other

wp cli

Wordpress Query Examples

simple loop HTML

<?php query_posts("showposts=4&cat=1"); ?>
  <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  	// loop post
  <?php endwhile; endif; ?>
<?php wp_reset_query(); ?>

simple loop php

query_posts("showposts=4&cat=1");
  if ( have_posts() ) : while ( have_posts() ) : the_post();
  	// loop post
  endwhile; endif;
wp_reset_query();

query CPT posts

query_posts("showposts=4&post_type=reviews");
  if ( have_posts() ) : while ( have_posts() ) : the_post();
    // loop
  endwhile; endif;
wp_reset_query();

Query CPT and display

<?php
  query_posts( array(
    'post_type' => portfolio,
    'cat' => 80,
    'showposts' => 2 )
  );
?>
<?php while ( have_posts() ) : the_post(); ?>

  <div class="post_type">
    <?php if ( 'post' == get_post_type()  ) : ?>FEATURE<?php endif; ?>
    <?php if ( 'report' == get_post_type()  ) : ?>REPORT<?php endif; ?>
    <?php if ( 'opinion' == get_post_type()  ) : ?>OPINION<?php endif; ?>
    <?php if ( 'bookmark' == get_post_type()  ) : ?>BOOKMARK<?php endif; ?>
  </div>

  <a href="<?php the_permalink(); ?> "><?php the_title(); ?></a>

<?php endwhile; ?>

query by 2 Meta Fields

$query = new WP_Query( array(
  'post_type' => 'product',
    'meta_query' => array(
      array(
        'key' => 'color',
        'value' => 'red',
      ),
      array(
        'key' => 'size',
        'value' => 'XL',
      ),
    ),
  )
);

Query Post by Meta

$query = new WP_Query( array(
    'post_type' => 'product',
    'meta_query' => array(
        array(
            'key' => 'color',
            'value' => array( 'red', 'blue' ),
            'compare' => 'IN',
        ),
    ),
) );

Query by Extended Meta

  $query = new WP_Query( array(
      'post_type' => 'property',
      'meta_query' => array(
          array(
              'key' => 'price',
              'value' => 50000,
              'compare' => '<=',
              'type' => 'NUMERIC',
          ),
      ),
  ) );

Query by 2 Meta Fields with OR relation

$queryArgs = array(
  "post_type" => array( "post", "match-report" ),
  "meta_query" => array(
    "relation" => "OR",
    array(
      "key" => "show_in_news",
      "compare" => "NOT EXISTS",
    ),
    array(
      "key" => "show_in_news",
      "value" => "true",
    ),
  ),
);

search ACF Repeater sub field value with WP_User_query

  function user_meta_callback( $user_query )
  {
    global $wpdb;
    $user_query->query_where = str_replace("meta_key = 'coupons_$", "meta_key LIKE 'coupons_%", $user_query->query_where);
  }
  add_filter('pre_user_query', 'user_meta_callback');

  $q = new WP_User_Query(array(
    'numberposts' => -1,
    'meta_query' =>
    array(
      'relation' => 'OR',
      array(
        'key' => 'coupons_$_date',
        'compare' => '>=',
        'value' => '2018-11-01',
        'type' => 'DATE'
      )
    )
  ));

Your AFC field is a post object, which means the meta value is either a single post id, or a serialized array of post ids.

If your custom field is set to only allow a single selection, then it will be a single id, and can be queried like this:

$post_id = get_the_ID();
$the_query = new WP_Query( array(
      'posts_per_page'=>9,
      'post_type'=>'brand-name',
      'order'   => 'ASC',
      'meta_query' => array(
       array(
            'key' => 'generic-name',// this key is advance custom field: type post_object
            'value' => $post_id,
       ),
    ),
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
  );`

If your custom field allows multiple selection, then it will a serialized php array of ids. Since mysql does not know how to read php serialized data, the best you can do is use a LIKE query:

$post_id = get_the_ID();
$the_query = new WP_Query( array(
      'posts_per_page'=>9,
      'post_type'=>'brand-name',
      'order'   => 'ASC',
      'meta_query' => array(
       array(
            'key' => 'generic-name',// this key is advance custom field: type post_object
            'value' => sprintf("\"%s\"", $post_id),
            'compare' => 'LIKE'
       ),
    ),
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
  );`

Query Post by ACF Repeater Field

  $the_query = new WP_Query(
    array(
      'posts_per_page' => 100,
      'post_type' => 'games',
      'orderby' => 'date',
      'order' => 'DESC',
      // 'order'   => 'ASC',
      'meta_query' => array(
        "relation" => "OR",
        array(
          'key' => 'home_team', // this key is advance custom field: type post_object
          // 'value' => 136,
          'value' => $this->player_team->ID,
          // 'value' => $player_team->ID,
        ),
        array(
          'key' => 'guest_team', // this key is advance custom field: type post_object
          'value' => 136,
          'value' => $this->player_team->ID,
          // 'value' => $player_team->ID,
        ),
      ),
      'paged' => get_query_var('paged') ? get_query_var('paged') : 1
    )
  );
  $posts = $the_query->posts;

Query with pagination

<ul class="all-review-page">
  <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $temp = $wp_query;
    $wp_query= null;
    query_posts('post_type=reviews'.'&showposts=10'.'&paged='.$paged);
  while (have_posts()) : the_post();?>

  <li>
    <?php the_content(); ?>
    <p class="user-name"><?php the_title(); ?><span class="user-from user-from-<?php the_field('country'); ?>"><?php
    $field = get_field_object('country');
    $value = get_field('country');
    $label = $field['choices'][ $value ];
    echo $label; ?></span></p>
  </li>


  <?php endwhile; ?>
  <?php html5wp_pagination(); ?>
  <?php $wp_query = null; $wp_query = $temp;?>
</ul><!-- all-review-page -->

query Post by ratin and sort

<?php query_posts( array( 'meta_key' => 'ratings_average', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) ); ?>
  <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    <a class="rate-game" href="http://777casino-vulkan.com/igrovye-avtomaty/rock-climber.html">
      <img width="188" height="125" src="./single_files/rock-climber-logo.jpg" class="attachment-post-thumbnail wp-post-image" alt="Игровой автомат Rock Climber">
      <?php if(function_exists('the_ratings')) { the_ratings(); } ?>
      <div class="title-rate-game">Rock Climber</div>
    </a>

  <?php endwhile; endif; ?>
<?php wp_reset_query(); ?>

query post by Views and display sorted

<?php
  $args = array(
    'orderby'      => 'meta_value',
    'meta_key'     => 'post_views_count',
    'order'        => 'DESC',
    'post_status'  => 'publish'
  );
  $ranking = 0;
?>
<?php query_posts($args); ?>
<?php if ( have_posts() ) : ?>
  <?php while ( have_posts()) : the_post();  $ranking++; ?>

  <!-- HTML -->

<?php endwhile; endif;  wp_reset_query(); ?>

query with pagination

<?php
  $args = array(
    'cat' => '8',
    'post_type' => 'post',
    'posts_per_page' => 10,
    'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1),
  );
  query_posts($args); ?>

  <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix looper'); ?>>
      <h2 class="looper-title inner-title">
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
      </h2>
      <!-- /post title -->
      <?php wpeExcerpt('wpeExcerpt30'); ?>
    </article>
  <?php endwhile;  ?>
  <?php endif; ?>

  <?php get_template_part('pagination'); ?>
<?php wp_reset_query(); ?>

query by Page Template

<?php
  $args = array(
    'post_type' => 'page',
    'meta_query' => array(
      array(
        'key' => '_wp_page_template',
        'value' => 'page-services.php', // template name as stored in the dB
      )
    )
  );
  query_posts( $args );
  while (have_posts()) : the_post();?>
  <?php if( have_rows('services') ): while ( have_rows('services') ) : the_row(); ?>
    <div class="wide-slider-block" style="background-image: url(<?php the_sub_field('image'); ?>);">
      <span class="inner diliganse">
        <h4><?php the_sub_field('title-first'); ?></h4>
        <a href="<?php the_sub_field('order'); ?>" class="button-order">заказать</a>
        <h6 class="price"><?php the_sub_field('price'); ?> <span>руб</span></h6>
      </span>
    </div>
  <?php endwhile; endif; ?>
<?php endwhile; ?>

Query by Taxonomy Slug

  $args = array(
    'post_type' => 'product',
    'tax_query' => array(
      'relation' => 'OR',
      array(
        'taxonomy' => 'properties',
        'terms' => $term,
        'field' => 'slug'

      ),
    ),
    'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1),
    'posts_per_page' => 10,
  );
  query_posts($args);

Query post with TRUE / FALSE acf fields

  $news_secondary_args = array(
    'post_type' => 'post',
    // Fetch two posts to go right of Primary Featured story
    'posts_per_page' => 2,
    // Query posts' meta
    'meta_query' => array(
      array(
        // Require post to have Featured Image
        'key' => '_thumbnail_id'
      ),
      array(
        // Key = ACF Field Name (True/False field)
        'key' => 'feature_on_news_center',
        // Value = 1, so 'True' radio button is selected
        'value' => '1'
      ),
      array(
        // Key = ACF Field Name (Radio Button)
        'key' => 'news_placement',
        // The value selected (other options include 'primary' & 'tertiary')
        'value' => 'secondary'
      )
    )
  );

  // The Loop
  $news_secondary_query = new WP_Query( $news_secondary_args );
  while ( $news_secondary_query->have_posts() ) :
    $news_secondary_query->the_post();

// loop

endwhile; // End Loop
wp_reset_postdata(); // Reset post data in order to run additional loops such as this

Woocommerce

Get all order item meta data

foreach ( $order->get_items() as $item_id => $item ) {
  $meta_data = $item->get_formatted_meta_data();

  // Get the meta data value
  $meta_value = $item->get_meta("custom_meta_field");

  echo $meta_value; // Display the value
}

Get order item custom field

if ( $custom_price = wc_get_order_item_meta( $item_id, 'custom_price', true )) {
  echo '<p>Clients Custom Price: <strong>' . $custom_price . ' ₴</strong></p>';
}

How to Override WooCommerce Templates in your Plugin

/**
 * How to Override WooCommerce Templates in your Plugin
 * https://wisdmlabs.com/blog/override-woocommerce-templates-plugin/
 * https://wpdevdesign.com/how-to-override-woocommerce-templates-using-a-custom-functionality-plugin/
 */
add_filter( 'woocommerce_locate_template', 'woo_adon_plugin_template', 1, 3 );
function woo_adon_plugin_template( $template, $template_name, $template_path ) {
  do_action( 'qm/warning', $template );

  global $woocommerce;
  $_template = $template;
  if ( ! $template_path )
    $template_path = $woocommerce->template_url;

  $plugin_path = untrailingslashit( plugin_dir_path( __FILE__ ) )  . '/template/woocommerce/';

  // Look within passed path within the theme - this is priority
  $template = locate_template(
    array(
      $template_path . $template_name,
      $template_name
    )
  );

  if( ! $template && file_exists( $plugin_path . $template_name ) )
    $template = $plugin_path . $template_name;

  if ( ! $template )
    $template = $_template;

  return $template;
}

Hiding item meta

add_filter( 'woocommerce_hidden_order_itemmeta', 'hide_my_item_meta' );
/**
 * Hiding item meta
 * @param array $hidden_meta Array of all meta data to hide.
 * @return array
 */
function hide_my_item_meta( $hidden_meta ) {
    // Let's hide the meta 'something'.
  $hidden_meta[] = 'something';
  return $hidden_meta;
}

Order item display meta

add_filter( 'woocommerce_order_item_display_meta_key', 'change_order_item_meta_title', 20, 3 );
/**
 * Changing a meta title
 * @param  string        $key  The meta key
 * @param  WC_Meta_Data  $meta The meta object
 * @param  WC_Order_Item $item The order item object
 * @return string        The title
 */
function change_order_item_meta_title( $key, $meta, $item ) {
    // By using $meta-key we are sure we have the correct one.
    if ( 'something' === $meta->key ) { $key = 'SOMETHING'; }
    return $key;
}

add_filter( 'woocommerce_order_item_display_meta_value', 'change_order_item_meta_value', 20, 3 );
/**
 * Changing a meta value
 * @param  string        $value  The meta value
 * @param  WC_Meta_Data  $meta   The meta object
 * @param  WC_Order_Item $item   The order item object
 * @return string        The title
 */
function change_order_item_meta_value( $value, $meta, $item ) {
    // By using $meta-key we are sure we have the correct one.
    if ( 'something' === $meta->key ) { $value = 'SOMETHING'; }

    return $value;
}

Filterting the meta data of an order item

add_filter( 'woocommerce_order_item_get_formatted_meta_data', 'change_formatted_meta_data', 20, 2 );
/**
 * Filterting the meta data of an order item.
 * @param  array         $meta_data Meta data array
 * @param  WC_Order_Item $item      Item object
 * @return array                    The formatted meta
 */
function change_formatted_meta_data( $meta_data, $item ) {
    $new_meta = array();
    foreach ( $meta_data as $id => $meta_array ) {
        // We are removing the meta with the key 'something' from the whole array.
        if ( 'something' === $meta_array->key ) { continue; }
        $new_meta[ $id ] = $meta_array;
    }
    return $new_meta;
}

Shipping add meta

add_action( 'woocommerce_checkout_create_order_shipping_item', 'order_shipping_item', 20, 4 );
/**
 * @param $item
 * @param $package_key
 * @param $package
 */
function order_shipping_item( &$item, $package_key, $package, $order ) {
    // Let's assume that we have a textarea field as a shipping note on the checkout field.
    // This can be a note for the delivery company, for example: "Deliver between 12:00 and 19:00"
    $note = isset( $_POST['shipping_note'] ) ? sanitize_text_field( $_POST['shipping_note'] ) : '';
    if ( $note ) {
      $item->add_meta_data( '_note', $note, true );
    }
}

Add shipping lines to the order

// WC_Checkout
/**
 * Add shipping lines to the order.
 *
 * @param WC_Order $order                   Order Instance.
 * @param array    $chosen_shipping_methods Chosen shipping methods.
 * @param array    $packages                Packages.
 */
public function create_order_shipping_lines( &$order, $chosen_shipping_methods, $packages ) {
  foreach ( $packages as $package_key => $package ) {
    if ( isset( $chosen_shipping_methods[ $package_key ], $package['rates'][ $chosen_shipping_methods[ $package_key ] ] ) ) {
      $shipping_rate            = $package['rates'][ $chosen_shipping_methods[ $package_key ] ];
      $item                     = new WC_Order_Item_Shipping();
      // ... code removed for reading purposes.

      /**
       * Action hook to adjust item before save.
       *
       * @since 3.0.0
       */
      do_action( 'woocommerce_checkout_create_order_shipping_item', $item, $package_key, $package, $order );

      // Add item to order and save.
      $order->add_item( $item );
    }
  }
}

Shipping meta title

add_filter( 'woocommerce_order_item_display_meta_key', 'change_shipping_note_title', 20, 3 );
/**
 * Changing the shipping note title
 * @param  string        $key  The meta key
 * @param  WC_Meta_Data  $meta The meta object
 * @param  WC_Order_Item $item The order item object
 * @return string        The title
 */
function change_shipping_note_title( $key, $meta, $item ) {
    // By using $meta-key we are sure we have the correct one.
    if ( '_note' === $meta->key ) { $key = __( 'Note', 'your_textdomain'); }
    return $key;
}

Add a brand Column to WooCommerce Products

https://rudrastyh.com/woocommerce/columns.html

add_filter( 'manage_edit-product_columns', 'misha_brand_column', 20 );
function misha_brand_column( $columns_array ) {
	// I want to display Brand column just after the product name column
	return array_slice( $columns_array, 0, 3, true )
	+ array( 'brand' => 'Brand' )
	+ array_slice( $columns_array, 3, NULL, true );
}

add_action( 'manage_posts_custom_column', 'misha_populate_brands' );
function misha_populate_brands( $column_name ) {
	if( $column_name  == 'brand' ) {
		// if you suppose to display multiple brands, use foreach();
		$x = get_the_terms( get_the_ID(), 'pa_brand'); // taxonomy name
		echo $x[0]->name;
	}
}

ADDING COLUMNS IN WOOCOMMERCE ADMIN ORDERS LIST

https://stackoverflow.com/questions/36446617/add-columns-to-admin-orders-list-in-woocommerce

// ADDING 2 NEW COLUMNS WITH THEIR TITLES (keeping "Total" and "Actions" columns at the end)
add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column', 20 );
function custom_shop_order_column($columns)
{
    $reordered_columns = array();

    // Inserting columns to a specific location
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key ==  'order_status' ){
            // Inserting after "Status" column
            $reordered_columns['my-column1'] = __( 'Title1','theme_domain');
            $reordered_columns['my-column2'] = __( 'Title2','theme_domain');
        }
    }
    return $reordered_columns;
}

// Adding custom fields meta data for each new column (example)
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
    switch ( $column )
    {
        case 'my-column1' :
            // Get custom post meta data
            $my_var_one = get_post_meta( $post_id, '_the_meta_key1', true );
            if(!empty($my_var_one))
                echo $my_var_one;

            // Testing (to be removed) - Empty value case
            else
                echo '<small>(<em>no value</em>)</small>';

            break;

        case 'my-column2' :
            // Get custom post meta data
            $my_var_two = get_post_meta( $post_id, '_the_meta_key2', true );
            if(!empty($my_var_two))
                echo $my_var_two;

            // Testing (to be removed) - Empty value case
            else
                echo '<small>(<em>no value</em>)</small>';

            break;
    }
}

Adds a "Featured" flash to featured WooCommerce products (like a sale flash)

function wc_add_featured_product_flash() {
	global $product;

	if ( $product->is_featured() ) {
		echo '<span class="onsale">Featured</span>';
	}
}
add_action( 'woocommerce_before_shop_loop_item_title', 'wc_add_featured_product_flash' );
add_action( 'woocommerce_before_single_product_summary', 'wc_add_featured_product_flash' );

Add a WooCommerce custom order action

/**
 * Add a custom action to order actions select box on edit order page
 * Only added for paid orders that haven't fired this action yet
 *
 * @param array $actions order actions array to display
 * @return array - updated actions
 */
function sv_wc_add_order_meta_box_action( $actions ) {
	global $theorder;

	// bail if the order has been paid for or this action has been run
	if ( ! $theorder->is_paid() || get_post_meta( $theorder->id, '_wc_order_marked_printed_for_packaging', true ) ) {
		return $actions;
	}

	// add "mark printed" custom action
	$actions['wc_custom_order_action'] = __( 'Mark as printed for packaging', 'my-textdomain' );
	return $actions;
}
add_action( 'woocommerce_order_actions', 'sv_wc_add_order_meta_box_action' );


/**
 * Add an order note when custom action is clicked
 * Add a flag on the order to show it's been run
 *
 * @param \WC_Order $order
 */
function sv_wc_process_order_meta_box_action( $order ) {

	// add the order note
	$message = sprintf( __( 'Order information printed by %s for packaging.', 'my-textdomain' ), wp_get_current_user()->display_name );
	$order->add_order_note( $message );

	// add the flag so this action won't be shown again
	update_post_meta( $order->id, '_wc_order_marked_printed_for_packaging', 'yes' );
}
add_action( 'woocommerce_order_action_wc_custom_order_action', 'sv_wc_process_order_meta_box_action' );

WooCommerce Order Emails: Add product images to the order email (WooCommerce 2.5+)

/**
 * Adds product images to the WooCommerce order emails table
 * Uses WooCommerce 2.5 or newer
 *
 * @param string $output the buffered email order items content
 * @param \WC_Order $order
 * @return $output the updated output
 */
function sww_add_images_woocommerce_emails( $output, $order ) {

	// set a flag so we don't recursively call this filter
	static $run = 0;

	// if we've already run this filter, bail out
	if ( $run ) {
		return $output;
	}

	$args = array(
		'show_image'   	=> true,
		'image_size'    => array( 100, 100 ),
	);

	// increment our flag so we don't run again
	$run++;

	// if first run, give WooComm our updated table
	return $order->email_order_items_table( $args );
}
add_filter( 'woocommerce_email_order_items_table', 'sww_add_images_woocommerce_emails', 10, 2 );

WC settings section sample

// Add a new section to WooCommerce > Settings > Products
function add_my_products_section( $sections ) {
	$sections['tshirt_designer'] = __( 'T-Shirt Designer', 'my-textdomain' );
	return $sections;
}
add_filter( 'woocommerce_get_sections_products', 'add_my_products_section' );

// Add Settings for new section
function add_my_products_settings( $settings, $current_section ) {

	// make sure we're looking only at our section
	if ( 'tshirt_designer' === $current_section ) {

		$my_settings = array(
			array(
				'title'     => __( 'My Settings Section', 'my-textdomain' ),
					'type'      => 'title',
					'id'        => 'my_settings_section',
			),

			array(
				'id'       => 'my_settings_radio',
				'type'     => 'radio',
				'title'    => __( 'A Radio input', 'my-textdomain' ),
				'options'  => array(
					'uno'  => __( 'The first option', 'my-textdomain' ),
					'dos' => __( 'The second option', 'my-textdomain' ),
				),
				'default'  => 'uno',
				'desc'     => __( 'What this radio does.', 'my-textdomain' ),
				'desc_tip' => true,
			),

			array(
				'type'  => 'sectionend',
				'id'    => 'my_settings_section',
			),
		);

		return $my_settings;

	} else {
		// otherwise give us back the other settings
		return $settings;
	}
}
add_filter( 'woocommerce_get_settings_products', 'add_my_products_settings', 10, 2 );

Edits the WooCommerce email order items table to enable purchase notes

/**
 * Edits the email order items table to enable purchase notes always.
 *
 * @param array $args the email template arguments
 * @return array updated args
 */
function sww_add_wc_order_email_purchase_notes( $args ) {

	$args['show_purchase_note'] = true;

	return $args;
}
add_filter( 'woocommerce_email_order_items_args', 'sww_add_wc_order_email_purchase_notes' );

Add images to WooCommerce emails

// Edit order items table template defaults
function sww_add_wc_order_email_images( $table, $order ) {

	ob_start();

	$template = $plain_text ? 'emails/plain/email-order-items.php' : 'emails/email-order-items.php';
	wc_get_template( $template, array(
		'order'                 => $order,
		'items'                 => $order->get_items(),
		'show_download_links'   => $show_download_links,
		'show_sku'              => $show_sku,
		'show_purchase_note'    => $show_purchase_note,
		'show_image'            => true,
		'image_size'            => $image_size
	) );

	return ob_get_clean();
}
add_filter( 'woocommerce_email_order_items_table', 'sww_add_wc_order_email_images', 10, 2 );

Add content below WooCommerce Featured image

/**
 * Adds content below featured images
 * Tutorial: http://www.skyverge.com/blog/add-content-woocommerce-featured-images/
**/

function skyverge_add_below_featured_image() {
    echo '<h4 style="text-align:center;margin-top:10px;">Click to Enlarge</h4>';
}
add_action( 'woocommerce_product_thumbnails' , 'skyverge_add_below_featured_image', 9 );

Add content and notices to the WooCommerce checkout - sample code

/**
 * Each of these samples can be used - note that you should pick one rather than add them all.
 *
 * How to use WC notices: https://github.com/woothemes/woocommerce/blob/master/includes/wc-notice-functions.php#L96
 * Tutorial: http://www.skyverge.com/blog/edit-woocommerce-templates/
**/

/**
 * Add a content block after all notices, such as the login and coupon notices.
 *
 * Reference: https://github.com/woothemes/woocommerce/blob/master/templates/checkout/form-checkout.php
 */
add_action( 'woocommerce_before_checkout_form', 'skyverge_add_checkout_content', 12 );
function skyverge_add_checkout_content() {
	echo 'This content that you can use to tell customers stuff. You could make it a div class="checkout-message" and style it if you wanted.';
}


/**
 * Add a content in a notice instead. Let's add it before other notices with a priority = 9
 *
 * Reference: https://github.com/woothemes/woocommerce/blob/master/templates/checkout/form-checkout.php
 */
add_action( 'woocommerce_before_checkout_form', 'skyverge_add_checkout_success', 9 );
function skyverge_add_checkout_success() {
	wc_print_notice( __( 'A success message with high priority.', 'woocommerce' ), 'success' );
}


/**
 * Add an info notice instead. Let's add it after other notices with priority = 11
 *
 * Reference: https://github.com/woothemes/woocommerce/blob/master/templates/checkout/form-checkout.php
 */
add_action( 'woocommerce_before_checkout_form', 'skyverge_add_checkout_notice', 11 );
function skyverge_add_checkout_notice() {
	wc_print_notice( __( 'A notice message instead.', 'woocommerce' ), 'notice' );
}


/**
 * Add add a notice before the payment form - let's use an eror notice. Could also use content, etc.
 *
 * Reference: https://github.com/woothemes/woocommerce/blob/master/templates/checkout/review-order.php
 */
add_action( 'woocommerce_review_order_before_payment', 'skyverge_before_paying_notice' );
function skyverge_before_paying_notice() {
	wc_print_notice( __( 'An error message.', 'woocommerce' ), 'error' );
}

Add customer name to WooCommerce Admin New Order Email subject

https://gist.github.com/bekarice/50900986dc58f00ec765

/**
 * Adds customer first and last name to admin new order email subject.
 *
 * @param string $subject email subject
 * @param \WC_Order $order the order object for the email
 * @return string updated subject
 */
function skyverge_add_customer_to_email_subject( $subject, $order ) {

	$subject .= ' from ' . $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();

	return $subject;
}
add_filter( 'woocommerce_email_subject_new_order', 'skyverge_add_customer_to_email_subject', 10, 2 );

Adding a Featured Product flash in WooCommerce

function ignition_feature_flash() {
 global $post, $product;
 if ( $product->is_featured() ) :
  echo apply_filters( 'woocommerce_featured_flash', '<span class="is-featured">' . __( 'Hot!', 'ignition-theme' ) . '</span>', $post, $product );
 endif;
 if ( ! $product->is_in_stock() ) :
  echo apply_filters( 'woocommerce_stock_flash', '<span class="out-of-stock">' . __( 'Sold Out!', 'ignition-theme' ) . '</span>', $post, $product );
 endif;
}
add_action( 'woocommerce_before_shop_loop_item_title', 'ignition_feature_flash', 15 );

How Can I remove a particular product from an completed order

$order = wc_get_order(35);
foreach ($order->get_items() as $item_id => $item) {
  if ($item_id == 3) {
    wc_delete_order_item($item_id);
  }
}

admin sms alert

function admin_sms_alert($order_id)
{
    global $woocommerce;
    $order = new WC_Order($order_id);
    $billing_firstname = get_post_meta($order_id, '_billing_first_name', true);
    $billing_lastname = get_post_meta($order_id, '_billing_last_name', true);
    $billing_phone = get_post_meta($order_id, '_billing_phone', true);
    $shipping_address1 = get_post_meta($order_id, '_billing_address_1', true);
    $shipping_address2 = get_post_meta($order_id, '_billing_address_2', true);
    $medallion = strtoupper(get_user_meta($order->user_id, 'loyalty_status', true));
    $order_amount = get_post_meta($order_id, '_order_total', true);
    $pay_type = get_post_meta($order_id, '_payment_method', true);
    if ($pay_type == 'cod') {
        $pay_method = 'Cash on delivery';
    } else {
        $pay_method = 'Credit card on delivery';
    }
    $order_item = $order->get_items();
    foreach ($order_item as $product) {
        $product_meta[] = $product['name'] . ' (' . strtok($product['item_meta']['size'][0], ' ') . ')';
    }
    $product_list = implode("\n", $product_meta);
    $admin_sms = "New Order #{$order_id}\n" . "{$product_list}\n" . "{$medallion}\n" . "Total \${$order_amount}\n" . "{$pay_method}\n" . "{$billing_firstname} {$billing_lastname}\n" . "{$shipping_address1}" . ($shipping_address2 ? " {$shipping_address2}" : '') . "\n" . "{$billing_phone}";
    require 'twilio-php/Services/Twilio.php';
    $account_sid = 'AC48732db704fe33f0601c8b61bd1519b8';
    $auth_token = 'b881c619f25d20143bbbf6ac4d0d3429';
    $admin_phone = array('+13109253443', '+18185102424', '+18183392676');
    foreach ($admin_phone as $number) {
        $client = new Services_Twilio($account_sid, $auth_token);
        $client->account->messages->create(array('To' => $number, 'From' => "+13232104996", 'Body' => $admin_sms));
    }
}

Triggered when an order is paid

/**
  * Triggered when an order is paid
  * @param  int $order_id
  */
 public function order_paid($order_id)
 {
     // Get the order
     $order = new WC_Order($order_id);
     if (get_post_meta($order_id, 'wc_paid_listings_packages_processed', true)) {
         return;
     }
     foreach ($order->get_items() as $item) {
         $product = wc_get_product($item['product_id']);
         if ($product->is_type(array('job_package', 'resume_package', 'job_package_subscription', 'resume_package_subscription')) && $order->customer_user) {
             // Give packages to user
             for ($i = 0; $i < $item['qty']; $i++) {
                 $user_package_id = wc_paid_listings_give_user_package($order->customer_user, $product->id, $order_id);
             }
             // Approve job or resume with new package
             if (isset($item['job_id'])) {
                 $job = get_post($item['job_id']);
                 if (in_array($job->post_status, array('pending_payment', 'expired'))) {
                     wc_paid_listings_approve_job_listing_with_package($job->ID, $order->customer_user, $user_package_id);
                 }
             } elseif (isset($item['resume_id'])) {
                 $resume = get_post($item['resume_id']);
                 if (in_array($resume->post_status, array('pending_payment', 'expired'))) {
                     wc_paid_listings_approve_resume_with_package($resume->ID, $order->customer_user, $user_package_id);
                 }
             }
         }
     }
     update_post_meta($order_id, 'wc_paid_listings_packages_processed', true);
 }

Add meta boxes

public function add_meta_boxes()
 {
     global $post;
     if (isset($_GET['post'])) {
         if (get_post_meta($_GET['post'], '_payment_method', true) == 'inicis_escrow_bank') {
             $payment_method = get_post_meta($_GET['post'], '_payment_method', true);
             $tmp_settings = get_option('woocommerce_' . $payment_method . '_settings', true);
             $refund_mypage_status = $tmp_settings['possible_register_delivery_info_status_for_admin'];
             //관리자 배송정보 등록/환불 가능 주문상태 지정
             $order = new WC_Order($post->ID);
             $paid_order = get_post_meta($post->ID, "_paid_date", true);
             if (in_array($order->get_status(), $refund_mypage_status) && !empty($paid_order)) {
                 add_meta_box('ifw-order-escrow-register-delivery-request', __('이니시스 에스크로', 'codem_inicis'), 'IFW_Meta_Box_Escrow_Register_Delivery::output', 'shop_order', 'side', 'default');
             }
         } else {
             if (get_post_meta($_GET['post'], '_payment_method', true) == 'inicis_vbank') {
                 add_meta_box('ifw-order-vbank-refund-request', __('가상계좌 무통장입금 환불 처리', 'codem_inicis'), 'IFW_Meta_Box_Vbank_Refund::output', 'shop_order', 'side', 'default');
             } else {
                 if (in_array(get_post_meta($_GET['post'], '_payment_method', true), array('inicis_card', 'inicis_bank', 'inicis_hpp', 'inicis_kpay', 'inicis_stdcard'))) {
                     $order = new WC_Order($_GET['post']);
                     if (!in_array($order->get_status(), array('pending', 'on-hold'))) {
                         add_meta_box('ifw-order-refund-request', __('결제내역', 'codem_inicis'), 'IFW_Meta_Box_Refund::output', 'shop_order', 'side', 'default');
                     }
                 }
             }
         }
     }
 }

Add content to the WC emails.

/**
  * Add content to the WC emails.
  *
  * @access public
  * @param WC_Order $order
  * @param bool $sent_to_admin
  * @param bool $plain_text
  *
  * @return void
  */
 public function email_instructions($order, $sent_to_admin, $plain_text = false)
 {
     if (!$sent_to_admin && 'bKash' === $order->payment_method && $order->has_status('on-hold')) {
         if ($this->instructions) {
             echo wpautop(wptexturize($this->instructions)) . PHP_EOL;
         }
     }
 }

Get a link to the transaction on the 3rd party gateway size (if applicable)

 /**
  * Get a link to the transaction on the 3rd party gateway size (if applicable)
  *
  * @param  WC_Order $order the order object
  * @return string transaction URL, or empty string
  */
 public function get_transaction_url($order)
 {
     $return_url = '';
     $transaction_id = $order->get_transaction_id();
     if (!empty($this->view_transaction_url) && !empty($transaction_id)) {
         $return_url = sprintf($this->view_transaction_url, $transaction_id);
     }
     return apply_filters('woocommerce_get_transaction_url', $return_url, $order, $this);
 }

Retrieve an order

/**
  * Retrieve an order.
  *
  * @param int $order_id
  * @return WC_Order or null
  */
 public static function get_order($order_id = '')
 {
     $result = null;
     $order = new WC_Order($order_id);
     if ($order->get_order($order_id)) {
         $result = $order;
     }
     return $result;
 }

Output for the order received page.

/**
  * Output for the order received page.
  */
 public function thankyou_page($order_id)
 {
     $order = new WC_Order($order_id);
     if ('completed' == $order->get_status()) {
         echo '<p>' . __('Your booking has been confirmed. Thank you.', 'woocommerce-bookings') . '</p>';
     } else {
         echo '<p>' . __('Your booking is awaiting confirmation. You will be notified by email as soon as we\'ve confirmed availability.', 'woocommerce-bookings') . '</p>';
     }
 }

pos cashback

/**
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     // get order object
     $order = new WC_Order($order_id);
     $cashback = isset($_POST['pos-cashback']) ? wc_format_decimal($_POST['pos-cashback']) : 0;
     if ($cashback !== 0) {
         // add order meta
         update_post_meta($order_id, '_pos_card_cashback', $cashback);
         // add cashback as fee line item
         // TODO: this should be handled by $order->add_fee after WC 2.2
         $item_id = wc_add_order_item($order_id, array('order_item_name' => __('Cashback', 'woocommerce-pos'), 'order_item_type' => 'fee'));
         if ($item_id) {
             wc_add_order_item_meta($item_id, '_line_total', $cashback);
             wc_add_order_item_meta($item_id, '_line_tax', 0);
             wc_add_order_item_meta($item_id, '_line_subtotal', $cashback);
             wc_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
             wc_add_order_item_meta($item_id, '_tax_class', 'zero-rate');
         }
         // update the order total to include fee
         $order_total = get_post_meta($order_id, '_order_total', true);
         $order_total += $cashback;
         update_post_meta($order_id, '_order_total', $order_total);
     }
     // payment complete
     $order->payment_complete();
     // success
     return array('result' => 'success');
 }

Create a new order programmatically

/**
 * Create a new order programmatically.
 *
 * Returns a new order object on success which can then be used to add additional data.
 *
 * @param  array $args
 * @return WC_Order
 */
function wc_create_order($args = array())
{
    $default_args = array('status' => null, 'customer_id' => null, 'customer_note' => null, 'parent' => null, 'created_via' => null, 'cart_hash' => null, 'order_id' => 0);
    $args = wp_parse_args($args, $default_args);
    $order = new WC_Order($args['order_id']);
    // Update props that were set (not null)
    if (!is_null($args['parent'])) {
        $order->set_parent_id(absint($args['parent']));
    }
    if (!is_null($args['status'])) {
        $order->set_status($args['status']);
    }
    if (!is_null($args['customer_note'])) {
        $order->set_customer_note($args['customer_note']);
    }
    if (!is_null($args['customer_id'])) {
        $order->set_customer_id(is_numeric($args['customer_id']) ? absint($args['customer_id']) : 0);
    }
    if (!is_null($args['created_via'])) {
        $order->set_created_via(sanitize_text_field($args['created_via']));
    }
    if (!is_null($args['cart_hash'])) {
        $order->set_cart_hash(sanitize_text_field($args['cart_hash']));
    }
    // Update other order props set automatically
    $order->set_currency(get_woocommerce_currency());
    $order->set_prices_include_tax('yes' === get_option('woocommerce_prices_include_tax'));
    $order->set_customer_ip_address(WC_Geolocation::get_ip_address());
    $order->set_customer_user_agent(wc_get_user_agent());
    $order->save();
    return $order;
}

Foreach order items

$order = new WC_Order($order->ID);
$items = $order->get_items();
$user_orders = array();
foreach ($items as $item) {
    // if the product id on the order and the one given to this function
    // this order has been placed by the given user on the given course.
    $product = wc_get_product($item['product_id']);
    if ($product->is_type('variable')) {
        $item_product_id = $item['variation_id'];
    } else {
        $item_product_id = $item['product_id'];
    }
    if ($course_product_id == $item_product_id) {
        return $order->id;
    }
}
//end for each order item

Get order line items (products) in a neatly-formatted array of objects with properties

/**
  * Get order line items (products) in a neatly-formatted array of objects
  * with properties:
  *
  * + id - item ID
  * + name - item name, usually product title, processed through htmlentities()
  * + description - formatted item meta (e.g. Size: Medium, Color: blue), processed through htmlentities()
  * + quantity - item quantity
  * + item_total - item total (line total divided by quantity, excluding tax & rounded)
  * + line_total - line item total (excluding tax & rounded)
  * + meta - formatted item meta array
  * + product - item product or null if getting product from item failed
  * + item - raw item array
  *
  * @since 3.0.0
  * @param \WC_Order $order
  * @return array
  */
 public static function get_order_line_items($order)
 {
     $line_items = array();
     foreach ($order->get_items() as $id => $item) {
         $line_item = new stdClass();
         $product = $order->get_product_from_item($item);
         $item_desc = array();
         // add SKU to description if available
         if (is_callable(array($product, 'get_sku')) && $product->get_sku()) {
             $item_desc[] = sprintf('SKU: %s', $product->get_sku());
         }
         // get meta + format it
         $item_meta = new WC_Order_Item_Meta($item);
         $item_meta = $item_meta->get_formatted();
         if (!empty($item_meta)) {
             foreach ($item_meta as $meta) {
                 $item_desc[] = sprintf('%s: %s', $meta['label'], $meta['value']);
             }
         }
         $item_desc = implode(', ', $item_desc);
         $line_item->id = $id;
         $line_item->name = htmlentities($item['name'], ENT_QUOTES, 'UTF-8', false);
         $line_item->description = htmlentities($item_desc, ENT_QUOTES, 'UTF-8', false);
         $line_item->quantity = $item['qty'];
         $line_item->item_total = isset($item['recurring_line_total']) ? $item['recurring_line_total'] : $order->get_item_total($item);
         $line_item->line_total = $order->get_line_total($item);
         $line_item->meta = $item_meta;
         $line_item->product = is_object($product) ? $product : null;
         $line_item->item = $item;
         $line_items[] = $line_item;
     }
     return $line_items;
 }

Iterating through each WC_Order_Item_Product objects

// Get an instance of the WC_Order object
$order = wc_get_order($order_id);

// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):

    ## Using WC_Order_Item methods ##

    // Item ID is directly accessible from the $item_key in the foreach loop or
    $item_id = $item->get_id();

    ## Using WC_Order_Item_Product methods ##

    $product      = $item->get_product(); // Get the WC_Product object

    $product_id   = $item->get_product_id(); // the Product id
    $variation_id = $item->get_variation_id(); // the Variation id

    $item_type    = $item->get_type(); // Type of the order item ("line_item")

    $item_name    = $item->get_name(); // Name of the product
    $quantity     = $item->get_quantity();
    $tax_class    = $item->get_tax_class();
    $line_subtotal     = $item->get_subtotal(); // Line subtotal (non discounted)
    $line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
    $line_total        = $item->get_total(); // Line total (discounted)
    $line_total_tax    = $item->get_total_tax(); // Line total tax (discounted)

    ## Access Order Items data properties (in an array of values) ##
    $item_data    = $item->get_data();

    $product_name = $item_data['name'];
    $product_id   = $item_data['product_id'];
    $variation_id = $item_data['variation_id'];
    $quantity     = $item_data['quantity'];
    $tax_class    = $item_data['tax_class'];
    $line_subtotal     = $item_data['subtotal'];
    $line_subtotal_tax = $item_data['subtotal_tax'];
    $line_total        = $item_data['total'];
    $line_total_tax    = $item_data['total_tax'];

    // Get data from The WC_product object using methods (examples)
    $product        = $item->get_product(); // Get the WC_Product object

    $product_type   = $product->get_type();
    $product_sku    = $product->get_sku();
    $product_price  = $product->get_price();
    $stock_quantity = $product->get_stock_quantity();

endforeach;

Remove Default Sorting Options

https://rudrastyh.com/woocommerce/sorting-options.html

add_filter( 'woocommerce_catalog_orderby', 'misha_remove_default_sorting_options' );
function misha_remove_default_sorting_options( $options ){
	unset( $options[ 'popularity' ] );
	//unset( $options[ 'menu_order' ] );
	//unset( $options[ 'rating' ] );
	//unset( $options[ 'date' ] );
	//unset( $options[ 'price' ] );
	//unset( $options[ 'price-desc' ] );
	return $options;
}

Rename the Default Sorting Options

add_filter( 'woocommerce_catalog_orderby', 'misha_rename_default_sorting_options' );
function misha_rename_default_sorting_options( $options ){
	unset( $options[ 'price-desc' ] ); // remove
	$options[ 'price' ] = 'Sort by price'; // rename
	return $options;
}

Handle WooCommerce Product Settings

https://rudrastyh.com/woocommerce/product-data-metabox.html

// Let’s add some options now!
add_action( 'woocommerce_product_options_advanced', 'misha_adv_product_options');
function misha_adv_product_options(){
	echo '<div class="options_group">';
	woocommerce_wp_checkbox( array(
		'id'      => 'super_product',
		'value'   => get_post_meta( get_the_ID(), 'super_product', true ),
		'label'   => 'This is a super product',
		'desc_tip' => true,
		'description' => 'If it is not a regular WooCommerce product',
	) );
	echo '</div>';
}

add_action( 'woocommerce_process_product_meta', 'misha_save_fields', 10, 2 );
function misha_save_fields( $id, $post ){
	//if( !empty( $_POST['super_product'] ) ) {
		update_post_meta( $id, 'super_product', $_POST['super_product'] );
	//} else {
	//	delete_post_meta( $id, 'super_product' );
	//}
}

WP-CLI

examples

Search post with date and change status

#wp post list --after="2022-02-05T23:59:59" --post_status=publish --post_type=post --format=ids | xargs -d ' ' -I % wp post update % --post_status=future
wp post list --post__in=$(wp db query 'SELECT ID FROM `wp_posts` WHERE `post_date`>"2022-02-06";' --skip-column-names | paste -s -d ',' -) --format=ids | xargs -d ' ' -I % wp post update % --post_status=future
# https://salferrarello.com/how-to-set-older-wordpress-posts-to-draft-with-wp-cli/
# wp post update $(wp post list --post__in=$(wp db query 'SELECT ID FROM `is_posts` WHERE `post_date`<"2014-01-01";' --skip-column-names | paste -s -d ',' -) --format=ids) --post_status=draft

# First we are going to find all of the posts with an empty title.
wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_title=''" --allow-root
# Now we can look for posts with empty content
wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts where post_content=''" --allow-root
# We can count the posts with empty content
wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_content=''" --allow-root | wc -l
# Finally let’s check the posts with both empty titles and content
wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_content='' AND post_title=''" --allow-root
# Empty Post Title and Content for Custom Post Types
wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_type='product' AND post_content='' AND post_title=''" --allow-root
# delete Empty Post Title
wp post delete $(wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_title=''" --allow-root | tr '\r\n' ' ') --force --allow-root
# delete Empty Post Content
wp post delete $(wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_content=''" --allow-root | tr '\r\n' ' ') --force --allow-root
# delete Empty Post Title and Content
wp post delete $(wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_content='' AND post_title=''" --allow-root | tr '\r\n' ' ') --force --allow-root
wp db query "DELETE FROM $(wp db prefix --allow-root)posts WHERE ID IN '($(wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_content='' AND post_title=''" --allow-root | tr '\r\n' ','))'"
# delete Empty Custom Post Types
wp post delete $(wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_type='product' AND post_content=''" --allow-root | tr '\r\n' ' ') --force --allow-root




wp post list --post_type=post --format=ids --date_query='{"after":{"year":"2030"}}'
wp post list --post_type=post --format=ids --date_query='{year=2012&monthnum=12}'

Converting WordPress Database Tables from MyISAM to InnoDB with WP-CLI

https://studiok40.com/wp-cli/

# Check if any of your tables are using MyISAM instead of InnoDB
wp db query "SHOW TABLE STATUS WHERE Engine = 'MyISAM'" --allow-root
wp db query "SHOW TABLE STATUS WHERE Engine = 'InnoDB'" --allow-root
# You can easily back up the database with this command
wp db export before-engine-change.sql --all-tablespaces --add-drop-table --allow-root
# You can easily restore with this command
wp db import before-engine-change.sql --allow-root
# While you can convert each table through phpMyAdmin, it’s not very practical if you have lots of tables to convert. The following commands will batch convert all MyISAM tables to InnoDB over SSH with WP-CLI.
wp db query "SELECT CONCAT('ALTER TABLE ', TABLE_SCHEMA,'.', TABLE_NAME, ' ENGINE=InnoDB;') FROM information_schema.TABLES WHERE ENGINE = 'MyISAM'" --skip-column-names > db_optimize.sql
wp db query < db_optimize.sql
rm db_optimize.sql

Deleting All Files from Media Library

wp post delete --force $(wp post list --post_type='attachment' --format=ids)

# Install a specific version from WordPress.org using URL

wp plugin install https://downloads.wordpress.org/plugin/perfecto-portfolio.1.0.0.zip –activate

force reinstall of all plugins

wp plugin install $(wp plugin list --field=name) --force

Cron

wp cron event list
wp cron event delete cron_test

Profile

wp profile --help
## --spotlight filters out unnecessary load times that takes ~0s seconds
wp profile stage bootstrap --spotlight
wp profile hook plugins_loaded --spotlight
# Can drill down into each stage, here we drill down into the bootstrap stage
wp profile stage bootstrap --allow-root
wp profile stage --all --orderby=time --allow-root
wp profile stage --all --spotlight --orderby=time --allow-root
wp profile hook wp --allow-root
wp profile hook --all --spotlight
wp profile hook --all --spotlight --url=https://guides.wp-bullet.com --orderby=time --allow-root
wp profile hook --all --spotlight --url=https://guides.wp-bullet.com/contact/ --orderby=time --allow-root
wp profile hook --all --spotlight --skip-plugins=plugin-namet

Query debug

wp package install runcommand/query-debug --allow-root
wp query-debug --allow-root
wp query-debug --allow-root --url="https://guides.wp-bullet.com/fixing-wp_options-table-missing-unique-column-primary-key/"
wp query-debug --debug --allow-root
wp query-debug --format=table --url="https://guides.wp-bullet.com/fixing-wp_options-table-missing-unique-column-primary-key"
# You can see that scientific notation is used in the time column above but you can try to show the biggest queries
SHELL_PIPE=0 wp query-debug --allow-root --url="https://guides.wp-bullet.com/fixing-wp_options-table-missing-unique-column-primary-key/" --format=table | sort -n | tail -n 20

Doctor

wp package install wp-cli/doctor-command --allow-root
wp doctor list --allow-root
wp doctor check core-update --allow-root
wp doctor check --all --allow-root
wp doctor check --all --spotlight --allow-root
wp doctor check autoload-options-size --allow-root

Other

wp site list --field=url | xargs -n1 -I % wp --url=% option update my_option my_value
# Delete all products
wp post delete $(wp post list --post_type='product' --format=ids)
# Perform a search and replace operation on the database
wp search-replace 'http://example.test' 'http://example.com' --skip-columns=guid
wp core download --locale=en_GB
wp media regenerate --yes --only-missing
wp eval 'echo WP_CONTENT_DIR;'
# Flush Rewrite Rules
wp rewrite flush
wp package list
# Vulnerability Scanner
wp package install 10up/wp-vulnerability-scanner
wp vuln status
# Image Optimization
wp package install typisttech/image-optimize-command
wp media regenerate
wp image-optimize batch
# To get the count we can remove the column headers line from the table with sed and then count the lines with wc
wp cron event list --allow-root --skip-plugins --skip-themes | sed -n '1!p' | wc -l
wp cron event list --field=hook --allow-root | sort -u
wp cron event list --field=hook --allow-root | sort | uniq -d


wp db export backup-before-search-replace.sql --all-tables
wp db export /tmp/wordpress-dump.sql --all-tablespaces --single-transaction --quick --lock-tables=false

wp search-replace 'wp-bullet.com' 'wp-bulletnew.com' --dry-run --skip-columns=guid
wp search-replace 'wp-bullet.com' 'wp-bulletnew.com' ---skip-columns=guid -all-tables --dry-run
wp search-replace 'domain.com' 'newdomain.com' --skip-columns=guid --export=/tmp/staging.sql
wp search-replace '/public_html/wp-bullet.com' '/public_html/newfolder' --skip-columns=guid
wp core config --dbname=wordpress --dbuser=wordpressuser --dbpass=passw0rd --allow-root --dbprefix=wp_

wp option list --field=option_name | grep warfare
wp option get social_warfare_settings
# We can grab these items from the serialized array with the pluck command.
wp option pluck social_warfare_settings order_of_icons
wp option patch update social_warfare_settings force_new_shares true
wp option list --field=option_name --allow-root | grep addthis
# If you want to see all of the option_values for each option_name containing addthis, you can use this command which will loop through each of them
wp option list --field=option_name --allow-root | grep addthis | xargs --replace=% wp option get % --allow-root
# If they are serialized arrays this will put them in the json format by employing the --format flag.
wp option list --field=option_name --allow-root | grep addthis | xargs --replace=% wp option get % --format=json --allow-root
wp option list --field=option_value --allow-root | grep addthis

wp db search "addthis" $(wp db prefix --allow-root)options --allow-root
wp db search "addthis" --all-tables --allow-root

wp term list product_cat --field=term_id | xargs wp term delete product_cat
wp term list product_tag --field=term_id | xargs wp term delete product_tag

Webp express

wp webp-express --help
wp webp-express convert
wp webp-express convert --reconvert
wp webp-express convert themes
wp webp-express flushwebp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment