Rename Order Status Messages in WooCommerce

https://www.tychesoftwares.com/how-to-rename-order-status-messages-in-woocommerce/

add_filter( 'wc_order_statuses', 'ts_rename_order_status_msg', 20, 1 );
function ts_rename_order_status_msg( $order_statuses ) {
    $order_statuses['wc-completed']  = _x( 'Order Received', 'Order status', 'woocommerce' );
    $order_statuses['wc-processing'] = _x( 'Your Order is being processed', 'Order status', 'woocommerce' );
    $order_statuses['wc-on-hold']    = _x( 'Your Order is on hold', 'Order status', 'woocommerce' );
    $order_statuses['wc-pending']    = _x( 'Your Order is pending', 'Order status', 'woocommerce' );
    return $order_statuses;
}
Rename Order Status Messages in WooCommerce - Order Status Messages changed

You will see that the order status has changed. We used the hook wc_order_statuses here and attached our function ts_rename_order_status_msg to it. The $order_statuses array that we passed as the argument contains the status messages as its first value.

The status messages also change in the front-end, where you check your order status under My account->Orders:

Rename Order Status Messages in WooCommerce - Order Status Messages changed in the front end

There are two other places though where the Woocommerce order status message gets displayed i.e. in the top menu inside the Admin Dashboard, and also in the dropdown for Bulk Actions:

Rename Order Status Messages in WooCommerce - Order Status Messages in the Top Menu and Bulk Actions in the Admin Dashboard

These status messages can be changed too using two other hooks to which we will attach two other functions.

Add the below code to the functions.php file of your child theme to change the status message in the top menu:

foreach( array( 'post', 'shop_order' ) as $hook )
    add_filter( "views_edit-shop_order", 'ts_order_status_top_changed' );
function ts_order_status_top_changed( $views ){
    if( isset( $views['wc-completed'] ) )
        $views['wc-completed'] = str_replace( 'Completed', __( 'Order Received', 'woocommerce'), $views['wc-completed'] );
    if( isset( $views['wc-processing'] ) )
        $views['wc-processing'] = str_replace( 'Processing', __( 'In Process', 'woocommerce'), $views['wc-processing'] );
    if( isset( $views['wc-on-hold'] ) )
        $views['wc-on-hold'] = str_replace( 'On hold', __( 'Order on Hold', 'woocommerce'), $views['wc-on-hold'] );
    if( isset( $views['wc-pending'] ) )
        $views['wc-pending'] = str_replace( 'Pending payment', __( 'Payment Pending', 'woocommerce'), $views['wc-pending'] );
        return $views;
}

You can see that we have used views_edit-shop_order hook here to simply replace the String values that each array key (for different order status messages) contains.

Rename Order Status Messages in WooCommerce - Order Status Message changed in Admin Top Menu

Now, the last place that we have to change the order status messages (if necessary) is the Bulk Actions dropdown that we highlighted above. For this, we will use yet another code snippet and add it to the same functions.php file:

add_filter( 'bulk_actions-edit-shop_order', 'ts_bulk_actions_order_status', 20, 1 );
function ts_bulk_actions_order_status( $actions ) {
    $actions['mark_processing'] = __( 'Mark as In Process', 'woocommerce' );
    $actions['mark_on-hold']    = __( 'Mark as Order on Hold', 'woocommerce' );
    $actions['mark_completed']  = __( 'Mark as Order Received', 'woocommerce' );
    return $actions;
}

Here, the bulk_actions-edit-shop_order hook is being used to change the values of the different actions that are applied to orders.

You can see that the order status messages will have changed in this dropdown:

Rename Order Status Messages in WooCommerce - Bulk Actions Order Status Message changed

Minimum and maximum allowable product quantities to be added in WooCommerce Cart

woocommerce_quantity_input_min : Allows to change the minimum value for the quantity. Default value is 0.
woocommerce_quantity_input_max : Allows to change maximum value for the quantity. Default value is -1.

/*
* Changing the minimum quantity to 2 for all the WooCommerce products
*/

function woocommerce_quantity_input_min_callback( $min, $product ) {
	$min = 2;  
	return $min;
}
add_filter( 'woocommerce_quantity_input_min', 'woocommerce_quantity_input_min_callback', 10, 2 );

/*
* Changing the maximum quantity to 5 for all the WooCommerce products
*/

function woocommerce_quantity_input_max_callback( $max, $product ) {
	$max = 5;  
	return $max;
}
add_filter( 'woocommerce_quantity_input_max', 'woocommerce_quantity_input_max_callback', 10, 2 );

With backend fields:

https://www.tychesoftwares.com/how-to-set-minimum-and-maximum-allowable-product-quantities-to-be-added-in-woocommerce-cart/

Add to Cart Quantity Plus & Minus Buttons

PHP Snippet: Display Plus & Minus Quantity Buttons @ WooCommerce Single Product Page And Cart Page:
https://www.businessbloomer.com/woocommerce-add-plus-minus-buttons-to-add-to-cart-quantity-input

/**
 * @snippet       Plus Minus Quantity Buttons @ WooCommerce Product Page & Cart
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 5
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
  
// -------------
// 1. Show plus minus buttons
  
add_action( 'woocommerce_after_quantity_input_field', 'bbloomer_display_quantity_plus' );
  
function bbloomer_display_quantity_plus() {
   echo '<button type="button" class="plus">+</button>';
}
  
add_action( 'woocommerce_before_quantity_input_field', 'bbloomer_display_quantity_minus' );
  
function bbloomer_display_quantity_minus() {
   echo '<button type="button" class="minus">-</button>';
}
  
// -------------
// 2. Trigger update quantity script
  
add_action( 'wp_footer', 'bbloomer_add_cart_quantity_plus_minus' );
  
function bbloomer_add_cart_quantity_plus_minus() {
 
   if ( ! is_product() && ! is_cart() ) return;
    
   wc_enqueue_js( "   
           
      $(document).on( 'click', 'button.plus, button.minus', function() {
  
         var qty = $( this ).parent( '.quantity' ).find( '.qty' );
         var val = parseFloat(qty.val());
         var max = parseFloat(qty.attr( 'max' ));
         var min = parseFloat(qty.attr( 'min' ));
         var step = parseFloat(qty.attr( 'step' ));
 
         if ( $( this ).is( '.plus' ) ) {
            if ( max && ( max <= val ) ) {
               qty.val( max ).change();
            } else {
               qty.val( val + step ).change();
            }
         } else {
            if ( min && ( min >= val ) ) {
               qty.val( min ).change();
            } else if ( val > 1 ) {
               qty.val( val - step ).change();
            }
         }
 
      });
        
   " );
}

Disable WordPress Auto-Update Email Notifications

Disable Auto Update Plugin and Theme Emails:

//Disable plugin auto-update email notification
add_filter('auto_plugin_update_send_email', '__return_false');
 
//Disable theme auto-update email notification
add_filter('auto_theme_update_send_email', '__return_false');

Disable Auto Update Core Emails:

//Disable automatic "Your Site Has Been Updated..." emails
add_filter( 'auto_core_update_send_email', 'smartwp_disable_core_update_emails', 10, 4 );
function smartwp_disable_core_update_emails( $send, $type, $core_update, $result ) {
  if ( !empty($type) && $type == 'success' ) {
    return false;
  }
  
  return true;
}

URL parameter value with js / javascript

Get URL parameter using JavaScript?

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};

And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');

Convert hex color to rgb or rgba using PHP

Convert hexdec color string to rgb(a) string:

function hex2rgba($color, $opacity = false) {
 
 $default = 'rgb(0,0,0)';
 
 //Return default if no color provided
 if(empty($color))
          return $default; 
 
 //Sanitize $color if "#" is provided 
        if ($color[0] == '#' ) {
         $color = substr( $color, 1 );
        }
 
        //Check if color has 6 or 3 characters and get values
        if (strlen($color) == 6) {
                $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
        } elseif ( strlen( $color ) == 3 ) {
                $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
        } else {
                return $default;
        }
 
        //Convert hexadec to rgb
        $rgb =  array_map('hexdec', $hex);
 
        //Check if opacity is set(rgba or rgb)
        if($opacity){
         if(abs($opacity) > 1)
         $opacity = 1.0;
         $output = 'rgba('.implode(",",$rgb).','.$opacity.')';
        } else {
         $output = 'rgb('.implode(",",$rgb).')';
        }
 
        //Return rgb(a) color string
        return $output;
}

Here’s a usage example how to use this function for dynamicaly created CSS:

$color = '#ffa226';
$rgb = hex2rgba($color);
$rgba = hex2rgba($color, 0.7);
 
/* CSS output */
 
echo ' 
 div.example{
  background: '.$rgb.';
  color: '.$rgba.';
 }
';

Upload field

Styling & Customizing File Inputs the Smart Way

.inputfile {
    width: 0.1px;
    height: 0.1px;
    opacity: 0;
    overflow: hidden;
    position: absolute;
    z-index: -1;

    + label {
        font-size: $fontSizeBody;
        line-height: $lineHeightBody;
        color: white;
        display: inline-block;
        cursor: pointer;
    }

    &:focus {
        + label {
            outline: 1px dotted $cBlack;
            outline: -webkit-focus-ring-color auto 5px;
        }
    }
}

/* style 6 */
.inputfile-6 {
    + label {
        color: $cBlue;
        border: 1px solid $cGray;
        padding: 0;

        strong {
            padding: 7px 15px;
            font-weight: 300;
            height: 100%;
            color: $cFont;
            display: inline-block;
            background-color:$cBlueLight;

            @media screen and (max-width: 576px) {
                display: block;
            }
        }

        span {
            padding: 7px 15px;
            font-weight: 300;
            min-width: 150px;
            max-width: 250px;
            min-height: 2em;
            display: inline-block;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            vertical-align: top;

            svg path {
                fill: $cBlue;
            }
        }

        &:hover {
            border-color: $cBlack;

            strong {
                background-color:$cBlue;
                color: $cWhite;
            }

            svg path {
                fill: $cWhite;
            }
        }
    }

    &:focus,
    &.has-focus {
        + label {
            border-color: $cBlack;

            strong {
                background-color:$cBlue;
                color: $cWhite;
            }
        }
        svg path {
            fill: $cWhite;
        }
    }
} 

JavaScript:

/*************************************************************
 *************  Custom File Upload Button  ****************
 *************************************************************/

function fileUploadButton() {

    $('.inputfile').each(function () {
        let $input = $(this),
            $label = $input.next('label'),
            labelVal = $label.html();

        $input.on('change', function (e) {
            let fileName = '';

            if (this.files && this.files.length > 1) {
                fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
            } else if (e.target.value) {
                fileName = e.target.value.split('\\').pop();
            }

            if (fileName) {
                $label.find('span').html(fileName);
            } else {
                $label.html(labelVal);
            }
        });

        // Firefox bug fix
        $input
            .on('focus', function () {
                $input.addClass('has-focus');
            })
            .on('blur', function () {
                $input.removeClass('has-focus');
            });
    });

}

Emails with the attachments

JS script

/*************************************************************
 *************  AJAX - Form sending  ****************
 *************************************************************/

function formSubmitTrigger() {

    $('#job-form').on('submit', function (e) {
        e.preventDefault();

        let submit_button = $(this).find('input[type=submit]');

        var data = new FormData(this);

        $.ajax({
            type: "POST",
            dataType: "json",
            url: ajaxurl,
            data: data,
            contentType: false,
            processData: false,
            beforeSend: function () {
                submit_button.attr("disabled", true);
                $(".spinner").show();
            },
            success: function (data) {
                $('.alert-notice').toggle().text(data['data']);
                $('#job-form')[0].reset();
                $(".spinner").hide();
                submit_button.attr("disabled", false);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $('.alert-notice').toggle().text(data['data']);
                console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
            }
        });
    })
}

Ajax function:


function contact_form_ajax(){

    $to = strip_tags($_POST['sendto']);

    $attachments = [];

        //upload file
        if (! function_exists('wp_handle_upload')) {
            require_once(ABSPATH . 'wp-admin/includes/file.php');
        }

        if($_FILES['file']) {
            foreach ($_FILES['file']['name'] as $n => $name) {
                $upload_overrides = ['test_form' => false ];
                $temp_file = $_FILES['file']['tmp_name'][$n];
                $file_name = $_FILES['file']['name'][$n];
                $file_path = WP_CONTENT_DIR . '/uploads/formattachments/' . $file_name;
                
                wp_handle_upload($temp_file, $upload_overrides);
                move_uploaded_file($temp_file, $file_path);
                
                $attachments[] .= $file_path;
            } 
        }


    $subject = "Neue Anfrage!";
    $headers = "From: Hochegger <". $to . ">\r\n";
    $headers .= "Reply-To: ". strip_tags($_POST['Email']) . "\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

    $message = '<html><body>';
    $message .= '<h2>Neue Anfrage:</h2>';
    foreach ($_POST as $key => $value) {
        if(
            $key != 'action' && 
            $key != 'datenschutz' && 
            $key != 'sendto'
        ) {
         
            $message .= "<strong>" . strip_tags($key) . ": </strong>" . strip_tags($value);
            $message .= "<br/>";
        }
    }
    $message .= "<br/>";
    $message .= "--";
    $message .= "<br/>";
    $message .= "Hochegger Website";
    $message .= "</body></html>";


        //Confirmation email
        $to_confirm = $_POST['Email'];
        $subject_confirm = "Ihre Hochegger Anfrage";
        $headers_confirm = "From: Hochegger <". $to . ">\r\n";
        $headers_confirm .= "MIME-Version: 1.0" . "\r\n";
        $headers_confirm .= "Content-type: text/html; charset=UTF-8" . "\r\n";

        $message_user = '<html><body>';
        $message_user .= '<h2>Ihre Anfrage:</h2>';
        foreach ($_POST as $key => $value) {
            if(
                $key != 'action' && 
                $key != 'datenschutz' && 
                $key != 'sendto'
            ) {
             
                $message_user .= "<strong>" . strip_tags($key) . ": </strong>" . strip_tags($value);
                $message_user .= "<br/>";
            }
        }
        $message_user .= "<br/>";
        $message_user .= "--";
        $message_user .= "<br/>";
        $message_user .= "Hochegger Website";
        $message_user .= "</body></html>";

        wp_mail($to_confirm, $subject_confirm, $message_user, $headers_confirm, $attachments);


    // Here put your Validation and send mail
    $sent = wp_mail($to, $subject, $message, $headers, $attachments);

    if($sent) {
        wp_send_json_success();
        return true;
    }
    else  {
        $message = "Error!";
        $return = array(
            'message' => $message
        );
        wp_send_json_error($return);
    }

    die();
}

add_action('wp_ajax_nopriv_contact_form_ajax', 'contact_form_ajax');
add_action('wp_ajax_contact_form_ajax', 'contact_form_ajax');

SMTP

This function will connect wp_mail to your authenticated SMTP server

/**
 * This function will connect wp_mail to your authenticated
 * SMTP server. This improves reliability of wp_mail, and 
 * avoids many potential problems.
 *
 * 
 * Values for constants are set in wp-config.php
 */
function send_smtp_email( $phpmailer ) {
    $phpmailer->isSMTP();
    $phpmailer->Host       = SMTP_HOST;
    $phpmailer->SMTPAuth   = SMTP_AUTH;
    $phpmailer->Port       = SMTP_PORT;
    $phpmailer->Username   = SMTP_USER;
    $phpmailer->Password   = SMTP_PASS;
    $phpmailer->SMTPSecure = SMTP_SECURE;
    $phpmailer->From       = SMTP_FROM;
    $phpmailer->FromName   = SMTP_NAME;
}
add_action( 'phpmailer_init', 'send_smtp_email' );
/**
 * SMTP setting for wp_mail -> wp-config.php
 * 
 */
define( 'SMTP_USER',   'email@email.com' );    // Username to use for SMTP authentication
define( 'SMTP_PASS',   'password' );       // Password to use for SMTP authentication
define( 'SMTP_HOST',   'mail.host.com' );    // The hostname of the mail server
define( 'SMTP_FROM',   'email@email.com' ); // SMTP From email address
define( 'SMTP_NAME',   'Reprazent.me' );    // SMTP From name
define( 'SMTP_PORT',   '465' );                  // SMTP port number - likely to be 25, 465 or 587
define( 'SMTP_SECURE', 'ssl' );                 // Encryption system to use - ssl or tls
define( 'SMTP_AUTH',    true );                 // Use SMTP authentication (true|false)
define( 'SMTP_DEBUG',   0 );                    // for debugging purposes only set to 1 or 2


Remove JQuery migrate

Remove JQuery migrate from WordPress frontend:

function remove_jquery_migrate( $scripts ) {
    if ( ! is_admin() && isset( $scripts->registered['jquery'] ) ) {
        $script = $scripts->registered['jquery'];
        if ( $script->deps ) {
            // Check whether the script has any dependencies
            $script->deps = array_diff( $script->deps, array( 'jquery-migrate' ) );
        }
    }
}
add_action( 'wp_default_scripts', 'remove_jquery_migrate' );

Import Posts from CSV Data

Import Posts from Custom CSV Data:

https://www.sitepoint.com/programmatically-creating-wordpress-posts-from-csv-data/

Example for CPT and ACF fields:


/**
 * Show 'insert posts' button on backend
 */
add_action( "admin_notices", function() {
    echo "<div class='updated'>";
    echo "<p>";
    echo "To insert or overwrite the posts into the CSV files, click the button to the right.";
    echo "<a class='button button-primary' style='margin:0.25em 1em' href='{$_SERVER["REQUEST_URI"]}&insert_km_products'>Import products from CSV</a>";
    echo "</p>";
    echo "</div>";
});

/**
 * Create and insert posts from CSV files
 */
add_action( "admin_init", function() {

    //  the post creation _only_ happens when you want it to.
    if ( ! isset( $_GET["insert_km_products"] ) ) {
        return;
    }

    // Change these to whatever you set
    $custom_names = array(
        "custom-post-type" => "produkte"
    );

    // Get the data from all those CSVs!
    $posts = function() {
        $data = array();
        $errors = array();
        $uploads = wp_upload_dir();
        $upload_path = $uploads['basedir'];

        // Get array of CSV files
        $files = glob( $upload_path."/km_csv/*.csv" );

        foreach ( $files as $file ) {

            // Attempt to change permissions if not readable
            if ( ! is_readable( $file ) ) {
                chmod( $file, 0744 );
            }

            // Check if file is writable, then open it in 'read only' mode
            if ( is_readable( $file ) && $_file = fopen( $file, "r" ) ) {
                $path_parts = pathinfo($file);

                // To sum this part up, all it really does is go row by row, column by column, saving all the data
                $post = array();

                // Get first row in CSV, which is of course the headers
                $header = fgetcsv( $_file, 0, "\t" );

                while ( $row = fgetcsv( $_file, 0, "\t" ) ) {

                    foreach ( $header as $i => $key ) {
                        $post[$key] = $row[$i];
                    }
                    
                    $post['filename'] = $path_parts['filename'];
                    $data[] = $post;
                    
                    // break; // only 1
                }

                fclose( $_file );

            } else {
                $errors[] = "File '$file' could not be opened. Check the file's permissions to make sure it's readable by your server.";
            }
        }

        if ( ! empty( $errors ) ) {
            // ... do stuff with the errors
        }

        return $data;
    };


    //  Check to see if the current post exists within the    
    $post_exists = function( $shop, $id, $import_post_type ) use ( $custom_names ) {
        $product_post = new WP_Query(
            array(
                'post_type'         => $import_post_type,
                'post_status '      => 'publish',
                'meta_query' => array(
                    array(
                        'key'     => 'shop',
                        'value'   => $shop,
                        // 'value'   => 'test',
                    ),
                    array(
                        'key'     => 'id',
                        'value'   => $id,
                    ),
                ),
            )
        );

        return $product_post->post->ID;
    };


    /**
     * IMPORT into post type
     */
    foreach ( $posts() as $post ) {

        $import_post_type = 'produkte';
        $import_taxonomy = 'kategorie';

        switch ($post['filename']) {
            case 'hubmann':
                $product_link = 'http://shop.hubmann-leibnitz.at/';
                break;
            case 'groebner':
                $product_link = 'https://shop.groebner.eu/';
                break;
            case 'blumenversand':
                $product_link = 'https://www.blumenversand.at/';
                break;
            case 'ma-chic':
                $product_link = 'https://shop.ma-chic.at/';
                break;
            default:
                $product_link = $post['Link'];
                break;
        }


        // If the post exists, skip this post and go to the next one
        if ( $existing_post_id = $post_exists( $post["filename"], $post['Id'], $import_post_type ) ) {

            wp_insert_post( array(
                'ID' => $existing_post_id,
                'post_title' => $post['Title'],
                'post_type' => $import_post_type,
                'post_status' => 'publish'
            ));

            $post['post_id'] = $existing_post_id;

        } else {
            // Insert the post into the database
            $post['post_id'] = wp_insert_post( array(
                'post_title' => $post['Title'],
                'post_type' => $import_post_type,
                'post_status' => 'publish'
            ));
        }

        update_field( 'condition', $post['Condition'], $post['post_id'] );
        update_field( 'price', $post['Price'], $post['post_id'] );
        update_field( 'availability', $post['Availability'], $post['post_id'] );
        update_field( 'image_link', $post['Image_Link'], $post['post_id'] );
        update_field( 'category', $post['Category'], $post['post_id'] );
        update_field( 'id', $post['Id'], $post['post_id'] );
        update_field( 'link', $product_link, $post['post_id'] );
        update_field( 'description', $post['Description'], $post['post_id'] );
        update_field( 'gtin', $post['GTIN'], $post['post_id'] );
        update_field( 'brand', $post['Brand'], $post['post_id'] );
        update_field( 'shipping_weight', $post['Shipping_weight'], $post['post_id'] );
        update_field( 'shop', $post['filename'], $post['post_id'] );


        //Assign 'Kategorie' taxonomy
        $args = array(
            'hide_empty' => false,
            'taxonomy'  => $import_taxonomy,
            'meta_query' => array(
                array(
                   'key'       => 'km_id',
                   'value'     => $post['Category'],
                   'compare'   => '='
                )
            ),
            );
        $terms = get_terms( $args );
    
        wp_delete_object_term_relationships( $post['post_id'], $import_taxonomy ); // remove all terms 
        
        if($terms) {
            wp_set_object_terms( $post['post_id'], $terms[0]->term_id, $import_taxonomy ); // assign new terms
        }
    }

});

Speed test

Page load speed:

function tr_head() {
    $GLOBALS['tr_time_start'] = microtime( true );
}
add_action( 'wp_head', 'tr_head' );

function tr_footer() {
    $start = $GLOBALS['tr_time_start'];
    $end   = microtime( true );
    
    echo sprintf( '<p>Page generated in %0.2f seconds.</p>',
        $end - $start
    );
}
add_action( 'wp_footer', 'tr_footer' );

Editor capabilities

Add editor the privilege to edit theme & menu:

// get the the role object
$role_object = get_role( 'editor' );

// add $cap capability to this role object

// Design menu point
$role_object->add_cap( 'edit_theme_options' );

//theme settings
$role_object->add_cap( 'manage_options' );

Coupon column – used in orders

Coupon column – with list of orders coupon was used:

function woo_customer_coupon_column_for_orders( $columns ) {
    $new_columns = array();
    
    foreach ( $columns as $column_key => $column_label ) {
        if ( 'expiry_date' === $column_key ) {
            $new_columns['order_coupons'] = __('Orders', 'woocommerce');
        }
        
        $new_columns[$column_key] = $column_label;
    }
    return $new_columns;
}
add_filter( 'manage_edit-shop_coupon_columns', 'woo_customer_coupon_column_for_orders' );


function woo_display_customer_coupon_in_column_for_orders( $column ) {
    global $the_order, $post;
    if( $column  == 'order_coupons' ) {

        $orders_with_coupon = wh_getOrderbyCouponCode($post->post_title);
        foreach ($orders_with_coupon as $order) {

            echo '- <a href="'.get_admin_url().'/post.php?post='.$order.'&action=edit"><small><em>#' . $order . '</em></small></a>';
            echo '<br/>';
        }
    }
}
add_action( 'manage_shop_coupon_posts_custom_column' , 'woo_display_customer_coupon_in_column_for_orders' );



function wh_getOrderbyCouponCode($coupon_code) {
    global $wpdb;
    $return_array = [];

    $query = "SELECT
        p.ID AS order_id
        FROM
        {$wpdb->prefix}posts AS p
        INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
        WHERE
        p.post_type = 'shop_order' AND
        p.post_status IN ('" . implode("','", array_keys(wc_get_order_statuses())) . "') AND
        woi.order_item_type = 'coupon' AND
        woi.order_item_name = '" . $coupon_code . "';";

    $orders = $wpdb->get_results($query);

    if (!empty($orders)) {
        $dp = ( isset($filter['dp']) ? intval($filter['dp']) : 2 );
        //looping throught all the order_id
        foreach ($orders as $key => $order) {
            $order_id = $order->order_id;
            $return_array[$key] = $order_id;
        }

    }
    return $return_array;
}

Coupons used column – Orders

Add a column with coupons used on admin Orders list in Woocommerce:

function woo_customer_order_coupon_column_for_orders( $columns ) {
    $new_columns = array();
    
    foreach ( $columns as $column_key => $column_label ) {
        if ( 'order_total' === $column_key ) {
            $new_columns['order_coupons'] = __('Coupons', 'woocommerce');
        }
        
        $new_columns[$column_key] = $column_label;
    }
    return $new_columns;
}
add_filter( 'manage_edit-shop_order_columns', 'woo_customer_order_coupon_column_for_orders' );

function woo_display_customer_order_coupon_in_column_for_orders( $column ) {
    global $the_order, $post;
    if( $column  == 'order_coupons' ) {
        if( $coupons = $the_order->get_coupon_codes() ) {
            echo implode(', ', $coupons) . ' ('.count($coupons).')';
        } else {
            echo '<small><em>'. __('No coupons') . '</em></small>';
        }
    }
}
add_action( 'manage_shop_order_posts_custom_column' , 'woo_display_customer_order_coupon_in_column_for_orders' );

Disable WordPress Updates

Disable WordPress Updates for Specific Users (Not admin user):

function disable_updates() {
    global $wp_version;
    return (object) array( 'last_checked' => time(), 'version_checked' => $wp_version, );
}

add_action( 'init', function () {
    if ( ! current_user_can( 'administrator' ) ) {
        add_filter( 'pre_site_transient_update_core', 'disable_updates' );     // Disable WordPress core updates
        add_filter( 'pre_site_transient_update_plugins', 'disable_updates' );  // Disable WordPress plugin updates
        add_filter( 'pre_site_transient_update_themes', 'disable_updates' );   // Disable WordPress theme updates
    }
} );

WooCommerce: Order Info

WooCommerce: Easily Get Order Info (total, items, etc) from $order Object

1. You have access to $order

Hooks (do_action and apply_filters) use additional arguments which are passed on to the function. If they allow you to use the “$order” object you’re in business. Here’s how to get all the order information:

// Get Order ID
$order->get_id();
 
// Get Order Totals $0.00
$order->get_formatted_order_total();
$order->get_cart_tax();
$order->get_currency();
$order->get_discount_tax();
$order->get_discount_to_display();
$order->get_discount_total();
$order->get_fees();
$order->get_formatted_line_subtotal();
$order->get_shipping_tax();
$order->get_shipping_total();
$order->get_subtotal();
$order->get_subtotal_to_display();
$order->get_tax_location();
$order->get_tax_totals();
$order->get_taxes();
$order->get_total();
$order->get_total_discount();
$order->get_total_tax();
$order->get_total_refunded();
$order->get_total_tax_refunded();
$order->get_total_shipping_refunded();
$order->get_item_count_refunded();
$order->get_total_qty_refunded();
$order->get_qty_refunded_for_item();
$order->get_total_refunded_for_item();
$order->get_tax_refunded_for_item();
$order->get_total_tax_refunded_by_rate_id();
$order->get_remaining_refund_amount();
 
// Get Order Items
$order->get_items();
$order->get_items_key();
$order->get_items_tax_classes();
$order->get_item();
$order->get_item_count();
$order->get_item_subtotal();
$order->get_item_tax();
$order->get_item_total();
$order->get_downloadable_items();
 
// Get Order Lines
$order->get_line_subtotal();
$order->get_line_tax();
$order->get_line_total();
 
// Get Order Shipping
$order->get_shipping_method();
$order->get_shipping_methods();
$order->get_shipping_to_display();
 
// Get Order Dates
$order->get_date_created();
$order->get_date_modified();
$order->get_date_completed();
$order->get_date_paid();
 
// Get Order User, Billing & Shipping Addresses
$order->get_customer_id();
$order->get_user_id();
$order->get_user();
$order->get_customer_ip_address();
$order->get_customer_user_agent();
$order->get_created_via();
$order->get_customer_note();
$order->get_address_prop();
$order->get_billing_first_name();
$order->get_billing_last_name();
$order->get_billing_company();
$order->get_billing_address_1();
$order->get_billing_address_2();
$order->get_billing_city();
$order->get_billing_state();
$order->get_billing_postcode();
$order->get_billing_country();
$order->get_billing_email();
$order->get_billing_phone();
$order->get_shipping_first_name();
$order->get_shipping_last_name();
$order->get_shipping_company();
$order->get_shipping_address_1();
$order->get_shipping_address_2();
$order->get_shipping_city();
$order->get_shipping_state();
$order->get_shipping_postcode();
$order->get_shipping_country();
$order->get_address();
$order->get_shipping_address_map_url();
$order->get_formatted_billing_full_name();
$order->get_formatted_shipping_full_name();
$order->get_formatted_billing_address();
$order->get_formatted_shipping_address();
 
// Get Order Payment Details
$order->get_payment_method();
$order->get_payment_method_title();
$order->get_transaction_id();
 
// Get Order URLs
$order->get_checkout_payment_url();
$order->get_checkout_order_received_url();
$order->get_cancel_order_url();
$order->get_cancel_order_url_raw();
$order->get_cancel_endpoint();
$order->get_view_order_url();
$order->get_edit_order_url();
 
// Get Order Status
$order->get_status();
 
// source: https://docs.woocommerce.com/wc-apidocs/class-WC_Order.html

2. You have access to $order_id

If you have access to the order ID (once again, usually the do_action or apply_filters might give you this), you have to get the order object first. Then do the exact same things as above.

// Get $order object from order ID
 
$order = wc_get_order( $order_id );
 
// Now you have access to (see above)...
 
$order->get_id()
$order->get_formatted_order_total( )
// etc.
// etc.

Woocommerce email

This script will allow you to send a custom email from anywhere within wordpress but using the woocommerce template so that your emails look the same.
https://gist.github.com/craigedmonds/b65c65e02fd40bd381bf023ffef2c80e

function get_custom_email_html( $order, $heading = false, $mailer ) {

	$template = 'emails/my-custom-email-i-want-to-send.php';

	return wc_get_template_html( $template, array(
		'order'         => $order,
		'email_heading' => $heading,
		'sent_to_admin' => false,
		'plain_text'    => false,
		'email'         => $mailer
	) );

}

// load the mailer class
$mailer = WC()->mailer();

//format the email
$recipient = "someone@somewhere.com";
$subject = __("Hi! Here is a custom notification from us!", 'theme_name');
$content = get_custom_email_html( $order, $subject, $mailer );
$headers = "Content-Type: text/html\r\n";

//send the email through wordpress
$mailer->send( $recipient, $subject, $content, $headers );

Cute Hide (show/hide element)

Smooth hiddinig elements with js:

    function cuteHide(el) {
        el.animate({opacity: '0'}, 130, function(){
            el.animate({height: '0px'}, 130, function(){
            });
        });
    }

    function cuteUnhide(el) {
        el.animate({height: '100%'}, 130, function(){
            el.animate({opacity: '1'}, 130, function() {
            });
        });
    }
    function cuteRemove(el) {
        el.animate({opacity: '0'}, 150, function(){
            el.animate({height: '0px'}, 150, function(){
                el.remove();
            });
        });
    }

How To Track Post Views Without a Plugin Using Post Meta

https://www.isitwp.com/track-post-views-without-a-plugin-using-post-meta/

Are you looking for a way to track post views without a plugin using post meta? While there’s probably a plugin for this, we have created a quick code snippet that you can use to track post views without a plugin using post meta in WordPress.

Instructions:

Add this code to your theme’s functions.php file:

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
 
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); 

Optionally add this code as well to a column in the WordPress admin that displays the post views:

// Add to a column in WP-Admin
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
    $defaults['post_views'] = __('Views');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
    if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

This part of the tracking views code will set the post views. Just place this code below within the single.php file inside the WordPress Loop.

<?php setPostViews(get_the_ID()); ?>

Note about fragment caching: If you are using a caching plugin like W3 Total Cache, the method above to set views will not work as the setPostViews() function would never run. However, W3 Total Cache has a feature called fragment caching. Instead of the above, use the following so the setPostViews() will run just fine and will track all your post views even when you have caching enabled.

<!-- mfunc setPostViews(get_the_ID()); --><!-- /mfunc -->

The code below is optional. Use this code if you would like to display the number of views within your posts. Place this code within the Loop.

<?php echo getPostViews(get_the_ID());?>

Convert hex color to rgb or rgba using PHP

/* Convert hexdec color string to rgb(a) string */
 
function hex2rgba($color, $opacity = false) {
 
	$default = 'rgb(0,0,0)';
 
	//Return default if no color provided
	if(empty($color))
          return $default; 
 
	//Sanitize $color if "#" is provided 
        if ($color[0] == '#' ) {
        	$color = substr( $color, 1 );
        }
 
        //Check if color has 6 or 3 characters and get values
        if (strlen($color) == 6) {
                $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
        } elseif ( strlen( $color ) == 3 ) {
                $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
        } else {
                return $default;
        }
 
        //Convert hexadec to rgb
        $rgb =  array_map('hexdec', $hex);
 
        //Check if opacity is set(rgba or rgb)
        if($opacity){
        	if(abs($opacity) > 1)
        		$opacity = 1.0;
        	$output = 'rgba('.implode(",",$rgb).','.$opacity.')';
        } else {
        	$output = 'rgb('.implode(",",$rgb).')';
        }
 
        //Return rgb(a) color string
        return $output;
}

Usage example:

/* Here's a usage example how to use this function for dynamicaly created CSS */
 
$color = '#ffa226';
$rgb = hex2rgba($color);
$rgba = hex2rgba($color, 0.7);
 
/* CSS output */
 
echo '	
	div.example{
	 background: '.$rgb.';
	 color: '.$rgba.';
	}
';

VC – Disable row

Make disable row working in WPBakery – Visual Composer:

// Disable row
if ( 'yes' === $disable_element ) {
    if ( vc_is_page_editable() ) {
        $css_classes[] = 'vc_hidden-lg vc_hidden-xs vc_hidden-sm vc_hidden-md';
    } else {
        return '';
    }
}

SEO Friendly URL

Creating SEO friendly URL
https://blog.ueffing.net/post/2016/03/14/creating-seo-friendly-url/

/**
 * prepares a string optimized for SEO
 * @param string $sString 
 * @return string $sString SEO optimized string
 */
function seofy ($sString = '')
{
    $sString = preg_replace ('/[^\pL\d_]+/u', '-', $sString);
    $sString = trim ($sString, "-");
    $sString = iconv ('utf-8', "us-ascii//TRANSLIT", $sString);
    $sString = strtolower ($sString);
    $sString = preg_replace ('/[^-a-z0-9_]+/', '', $sString);

    return $sString;
}

_____

echo seofy('Straßenfest in München');          // => strassenfest-in-muenchen
echo seofy('José Ignacio López de Arriortúa'); // => jose-ignacio-lopez-de-arriortua

Cookie JS

Custom Cookie banner JS

function cookieBanner() {

	var dropCookie = true;                      // false disables the Cookie, allowing you to style the banner
	var cookieDuration = 14;                    // Number of days before the cookie expires, and the banner reappears
	var cookieName = 'complianceCookie';        // Name of our cookie
	var cookieValue = 'on';                     // Value of cookie

	function showBanner(){
		$('#cookie-banner').show('slow');
		
		$('#cookie-banner .cookie-banner_close').on('click', function() {
			$('#cookie-banner').hide('slow');
			createCookie(cookieName,cookieValue, cookieDuration); // Create the cookie
		})
	}
	
	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000)); 
			var expires = "; expires="+date.toGMTString(); 
		}
		else var expires = "";
		if(dropCookie) { 
			document.cookie = name+"="+value+expires+"; path=/"; 
		}
	}
	
	function checkCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	window.onload = function(){
		if(checkCookie(cookieName) != cookieValue){
			showBanner(); 
		}
	}
}

Anchor link – Header offset

Anchor Link Offset to Other Pages with Fixed Header Size:

jQuery(document).ready(function($) {

  // set a variable for the anchor link which is the location.hash
  var anchorLink = $(window.location.hash);
    // test to see if the link is a anchor link, if not the length will have no value, this is done to avoid js errors on non anchor links
		if ( anchorLink.length ) {
      // set an element as the fixed entity, header in this case and get its height
			var offsetSize = $("header").innerHeight();
      // fire the animation from the top of the page to the anchor link offsetting by the fixed elements height, the number is the speed of the animation
			$("html, body").animate({scrollTop: anchorLink.offset().top - offsetSize }, 500);
    }

});

CSS Browser target

Targeting browsers to style with CSS:

@supports (-ms-ime-align: auto) {
  /* Microsoft EdgeV13&14 CSS styles go here */
  .edge1314 {
    background: green;
  }
  .edge1314::before {
    content: "Active: ";
  }
}
@supports (-ms-accelerator: true) {
  /* Microsoft EdgeV13 CSS styles go here */
  .edge13 {
    background: green;
  }
  .edge13::before {
    content: "Active: ";
  }
}
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
  /* IE10 & IE11 CSS styles go here */
  .ie1011 {
    background: green;
  }
  .ie1011::before {
    content: "Active: ";
  }
}

Google Analytics – GDPR

Adding Google Anyltics code and adding option to disable it:

   <!-- Google Analytics -->
    <script async src='//www.google-analytics.com/analytics.js'></script>
    <script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-xxxxxx-x', 'auto');
    ga('set', 'anonymizeIp', true);
    ga('send', 'pageview');
    </script>
    <!-- End Google Analytics -->


    //HTML LINK
    <a class="ga-disable" href="#">Link</a>
    <a href="javascript:gaOptout()">Link</a>


    // Set to the same value as the web property used on the site
    var gaProperty = 'UA-xxxxxx-x';
    // Disable tracking if the opt-out cookie exists.
    var disableStr = 'ga-disable-' + gaProperty;
    if (document.cookie.indexOf(disableStr + '=true') > -1) {
        window[disableStr] = true;
    }
    // Opt-out function
    function gaOptout() {
        document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
        window[disableStr] = true;
        alert('Das Tracking durch Google Analytics wurde in Ihrem Browser für diese Website deaktiviert.');
    }




    jQuery(document).ready(function($) {
        $(".ga-disable").click(function(event) {
            event.preventDefault();
            gaOptout();
        });
    });

Explode text to repeater (ACF)

Explode text by “,” and add to fields (ACF repeater) -> VIVI.si recepti:

    $('#explode_recepti').click(function(){

        var items = $('#explode_recepti_textarea').val().split(',').length;
        var itemsArray = $('#explode_recepti_textarea').val().split(',');

        for(i=0;i<items;i++){
            $('.acf-field-54dbe3014c9ae .acf-actions .acf-button ').click();
        }

        $('.acf-field-54dbe3014c9ae .acf-table .acf-field-text input').each(function( index , element) {
            
            $(this).val(itemsArray[index]);
        });

    });

Internal anchor smooth scroll

Internal URL smooth scroll from menu – anchor link:

        $("a[href*=#]:not([href=#])").click(function() {
            var kliknjeno = $(this);

            var calapse_mobile = kliknjeno.parent().parent().parent().parent();

            if (calapse_mobile.hasClass('collapse')) {
                calapse_mobile.collapse('hide');
            }

            if (!kliknjeno.hasClass( "nohref" )) {
                if (location.pathname.replace(/^\//, "") == this.pathname.replace(/^\//, "") && location.hostname == this.hostname) {
                    var a = $(this.hash);
                    if (a = a.length ? a : $("[name=" + this.hash.slice(1) + "]"), a.length) return $("html,body").animate({
                        scrollTop: a.offset().top - 30
                    }, 1000), !1
                }
            }

        })

Menu Dropdown / Submenu

Open Submenu:

    $('ul.desktop_menu li.menu-item-has-children').hover(function() {
        $(this).find('.sub-menu').stop(true, true).delay(100).fadeIn(200);
    }, function() {
        $(this).find('.sub-menu').stop(true, true).delay(100).fadeOut(200);
    });


    //WPML switcher
    $('ul.wpml_switch li.dropdown').hover(function() {
        $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeIn(200);
    }, function() {
        $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeOut(200);
    });

Sticky Header Scroll

Sticky Header on Scroll

    var showHeaderAt = 300;

    var win = $(window);
    var body = $('body');

    var sticky_visible = false;

    win.on('scroll', function(){

        if(win.scrollTop() > showHeaderAt) {

            if (sticky_visible == false) {
                body.addClass('header-stuck');
                setTimeout(function() {
                    body.addClass('fixed_active');
                }, 100);
                sticky_visible = true;
            }
        }
        else if (sticky_visible == true) {
            body.removeClass('fixed_active');
            body.removeClass('header-stuck');
            sticky_visible = false;
        }

    });

To Top Button

Scroll to top Button

    if ($('#back-to-top').length) {
        var scrollTrigger = 300, // px
            backToTop = function () {
                var scrollTop = $(window).scrollTop();
                if (scrollTop > scrollTrigger) {
                    $('#back-to-top').addClass('show');
                } else {
                    $('#back-to-top').removeClass('show');
                }
            };
        backToTop();
        $(window).on('scroll', function () {
            backToTop();
        });
        $('#back-to-top').on('click', function (e) {
            e.preventDefault();
            $('html,body').animate({
                scrollTop: 0
            }, 700);
        });
    }

Check if is Internet Explorer

Checking if is Internet Explorer and run some function:

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    var logo_img = $('.logoslider .single-clients img');

    if (navigator.appName == 'Microsoft Internet Explorer' ||  !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie == 1)) {

        set_height_ie();

        $(window).resize(function() {
            set_height_ie();
        });

        function set_height_ie() {
            logo_img_sirina = logo_img.width();
            logo_img.height(logo_img_sirina);
        }
    } 

Replace SVG to inline

Replace image SVG to inline SVG

    $('img.svg').each(function(){
        var $img = jQuery(this);
        var imgID = $img.attr('id');
        var imgClass = $img.attr('class');
        var imgURL = $img.attr('src');

        jQuery.get(imgURL, function(data) {
            // Get the SVG tag, ignore the rest
            var $svg = jQuery(data).find('svg');

            // Add replaced image's ID to the new SVG
            if(typeof imgID !== 'undefined') {
                $svg = $svg.attr('id', imgID);
            }
            // Add replaced image's classes to the new SVG
            if(typeof imgClass !== 'undefined') {
                $svg = $svg.attr('class', imgClass+' replaced-svg');
            }

            // Remove any invalid XML tags as per http://validator.w3.org
            $svg = $svg.removeAttr('xmlns:a');

            // Check if the viewport is set, if the viewport is not set the SVG wont't scale.
            if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
                $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
            }

            // Replace image with new SVG
            $img.replaceWith($svg);

        }, 'xml');
    });

Google Analytics – tracking

Include the Google Analytics Tracking Code – WP Functions

add_action('wp_head', 'wpb_add_googleanalytics');
function wpb_add_googleanalytics() { ?>
    <script type="text/javascript">
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-166254-45', 'auto');
        ga('send', 'pageview');
    </script>
<?php }

Google analytics – tracking

Include the Google Analytics Tracking Code (ga.js) – HEADER

<script async src='https://www.googletagmanager.com/gtag/js?id=UA-40742215-1'></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){
        dataLayer.push(arguments);
    }
    gtag('js', new Date());
    gtag('config', 'UA-000000-1', { 'anonymize_ip': true });
</script>

Lightbox attribute

Adds lightbox attribute for image popup:

function add_lightbox_rel($content) {
    global $post;
    $pattern = "/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
    $replacement = '<a$1href=$2$3.$4$5 rel="lightbox" $6>';
    $content = preg_replace($pattern, $replacement, $content);
    return $content;
}
add_filter("the_content", "add_lightbox_rel");
add_filter("acf_the_content", "add_lightbox_rel");

function add_gallery_rel($attachment_link) {
    global $post;
    $attachment_link = str_replace("<a", "<a rel=\"lightbox\"", $attachment_link);
    return $attachment_link;
}
add_filter("wp_get_attachment_link", "add_gallery_rel");

Unregister post type

Unregister standard post type and taxonomies:

function ryanbenhase_unregister_tags() {
    unregister_taxonomy_for_object_type( 'post_tag', 'post' );
    unregister_taxonomy_for_object_type( 'category', 'post' );
    unregister_post_type( 'post' );
}
add_action( 'init', 'ryanbenhase_unregister_tags' );

Woocommerce – Checkbox checkout

Add privacy policy checkbox checkout:

add_action( 'woocommerce_review_order_before_payment', 'woo_add_checkout_privacy_policy', 9 );
   
function woo_add_checkout_privacy_policy() {
  
    woocommerce_form_field( 'privacy_policy', array(
        'type'          => 'checkbox',
        'class'         => array('form-row terms wc-terms-and-conditions'),
        'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
        'input_class'   => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
        'required'      => true,
        'label'         => __( 'Mit deiner Bestellung erklärst du dich mit unseren Allgemeinen <a href="/agb/" target="_blank">Geschäftsbedingungen Widerrufsbestimmungen</a> sowie <a href="/datenschutz/" target="_blank">Datenschutzbestimmungen</a> einverstanden.', 'error' )
    )); 
      
}
// Show notice if customer does not tick
add_action( 'woocommerce_checkout_process', 'woo_not_approved_privacy' );
  
function woo_not_approved_privacy() {
    if ( ! (int) isset( $_POST['privacy_policy'] ) ) {
        wc_add_notice( __( 'Die Zustimmung zu unseren Datenschutz und Geschäftsbedingungen (AGB) ist erforderlich.' ), 'error' );
    }
}

MCE editor

Adding sub/sup to standard MCE editor:

function my_mce_buttons_2($buttons) {   
    /**
     * Add in a core button that's disabled by default
     */
    $buttons[] = 'superscript';
    $buttons[] = 'subscript';

    return $buttons;
}
add_filter('mce_buttons_2', 'my_mce_buttons_2');

WP-AJAX JS VARIABLE

Make wp-ajax url variable global:

function myplugin_ajaxurl() {
    echo '<script>
            var ajaxurl = "' . admin_url('admin-ajax.php') . '";
            var homeurl = "' . get_site_url() . '";
        </script>';
}
add_action('wp_head', 'myplugin_ajaxurl');

Slow Yoast

If Yoast SEO is slow add this to kill the shortcode parsing

add_action( 'wp_ajax_wpseo_filter_shortcodes', function(){
    wp_die( wp_json_encode( array() ) );
}, 1 );

Heder error

get_header() Fatal error PHP (boti dostopajo do index.php).
Dodamo v index.php namesto get_header():

if (function_exists('get_header')) {
    get_header();
} else {
    die();
}

ACF admin columns

Custom admin column from ACF field:

function my_page_columns($columns) {
    $columns = array(
        'cb'        => '<input type="checkbox" />',
        'title'     => 'Title',
        'datum'      =>  'Datum dogodka',
        'date'      =>  'Datum objave',
    );
    return $columns;
}

function my_custom_columns($column) {
    global $post;

    if ($column == 'datum') {
        echo get_field( "datum", $post->ID );
    } else {
         echo '';
    }

}
add_action("manage_dogodki_posts_custom_column", "my_custom_columns");
add_filter("manage_dogodki_posts_columns", "my_page_columns");

Dashboard box

Custom info box to WP dashboard:

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');
 
function my_custom_dashboard_widgets() {
    global $wp_meta_boxes;

    wp_add_dashboard_widget('custom_help_widget', 'AM Creative Agency', 'custom_dashboard_help');
}

function custom_dashboard_help() {
    echo '<div style="border:2px solid #ac8d54; background-color: rgba(172, 141, 84, 0.1); padding: 20px 20px 10px 20px; text-align: center;">';
    echo '<a href="http://creativeagency.am" target="_blank">';
    echo '<img src="http://creativeagency.am/wp-content/uploads/2016/05/am_logo_512.png" width="200px;" style="">';
    echo '</a>';
    echo '<p>Lepo pozdravljeni v sistemu za urejanje vaše spletne strani.</p>';
    echo '<p>Za pomoč pri upravljanju z vsebino nas lahko kontaktirate na <a href="mailto:info@creativeagency.am">info@creativeagency.am</a></p>';
    echo '<p>Ekipa ';
    echo '<a href="http://creativeagency.am" target="_blank">';
    echo 'AM Creative Agency</a>';
    echo '</p>';
    echo '</div>';
}

Video Container

Add responsive container to embeds. Add this to your theme’s functions.php:

function alx_embed_html( $html ) {
    return '<div class="video-container">' . $html . '</div>';
}
add_filter( 'embed_oembed_html', 'alx_embed_html', 10, 3 );
add_filter( 'video_embed_html', 'alx_embed_html' ); // Jetpack

And next up, we need to add the CSS that makes it responsive to our style.css:

.video-container { 
  position: relative; 
  padding-bottom: 56.25%; 
  height: 0; 
  overflow: hidden; 
}

.video-container iframe, 
.video-container object, 
.video-container embed, 
.video-container video { 
  position: absolute; 
  top: 0; 
  left: 0; 
  width: 100%; 
  height: 100%; 
}

Default Avatar

Add default user Avatar:

function customgravatar ($avatar_defaults) {
    $myavatar = get_home_url('Template_directory') . '/images/mycustomgravatar.jpg';
    $avatar_defaults[$myavatar] = "My Custom Logo";
    return $avatar_defaults;
}
add_filter( 'avatar_defaults', 'customgravatar' );

Rev. Slider Meta box

Remove meta boxes for revolution slider:

if ( is_admin() ) {

    function remove_revolution_slider_meta_boxes() {
        remove_meta_box( 'mymetabox_revslider_0', 'page', 'normal' );
        remove_meta_box( 'mymetabox_revslider_0', 'post', 'normal' );
        remove_meta_box( 'mymetabox_revslider_0', 'YOUR_CUSTOM_POST_TYPE', 'normal' );
    }

    add_action( 'do_meta_boxes', 'remove_revolution_slider_meta_boxes' );
}

Redirect cookie

Redirect if cookie is set

function my_cookie_redirect() {

  if(isset($_POST['confirm'])){
    $cookie_value = "true";
    setcookie( "AgeAgreed", $cookie_value, 30 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );

    $confirmano = true;
    wp_redirect(get_bloginfo('url'));
    exit;
  }

  if (!isset($_COOKIE['AgeAgreed']) || $confirmano == true)  {
    global $post;
    $enter_id = icl_object_id(3954, 'page', false);

    if ($post->ID != $enter_id) {
      wp_redirect( get_permalink($enter_id));
      exit;
    }
  }

}
add_action('template_redirect','my_cookie_redirect',0);

Redirect post type

Redirects 301 if post type:

function post_redirect() {
    global $wp_query;

    if ( is_archive('member') || is_singular('member') ) :
        $url   = get_bloginfo('url');

        wp_redirect( esc_url_raw( $url.'/about-ebla/' ), 301 );
        exit();
    endif;
}
add_action ( 'template_redirect', 'post_redirect', 1);

SVG support

Adding SVG format:

function svg_mime_types( $mimes ) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}
add_filter( 'upload_mimes', 'svg_mime_types' );

Additional fix:

function fix_mime_type_svg( $data = null, $file = null, $filename = null, $mimes = null ) {
    $ext = isset( $data['ext'] ) ? $data['ext'] : '';
    if ( strlen( $ext ) < 1 ) {
        $exploded = explode( '.', $filename );
        $ext      = strtolower( end( $exploded ) );
    }
    if ( $ext === 'svg' ) {
        $data['type'] = 'image/svg+xml';
        $data['ext']  = 'svg';
    } elseif ( $ext === 'svgz' ) {
        $data['type'] = 'image/svg+xml';
        $data['ext']  = 'svgz';
    }

    return $data;
}

add_filter( 'wp_check_filetype_and_ext', 'fix_mime_type_svg', 75, 4 );

Renaming category

Renaming standard post category:

function revcon_change_cat_object() {
    global $wp_taxonomies;
    $labels = &$wp_taxonomies['category']->labels;
    $labels->name = 'Kategorie';
    $labels->singular_name = 'Kategorie';
    $labels->add_new = 'Add Kategorie';
    $labels->add_new_item = 'Add Kategorie';
    $labels->edit_item = 'Edit Kategorie';
    $labels->new_item = 'Kategorie';
    $labels->view_item = 'View Kategorie';
    $labels->search_items = 'Search Kategorien';
    $labels->not_found = 'No Kategorie found';
    $labels->not_found_in_trash = 'No Kategorie found in Trash';
    $labels->all_items = 'Alle Kategorien';
    $labels->menu_name = 'Kategorie';
    $labels->name_admin_bar = 'Kategorie';
}
add_action( 'init', 'revcon_change_cat_object' );

Renaming Post

Renamin standart post post_type:


function revcon_change_post_label() {
    global $menu;
    global $submenu;
    $menu[5][0] = 'Novice';
    $submenu['edit.php'][5][0] = 'Novice';
    $submenu['edit.php'][10][0] = 'Dodaj novico';
}
function revcon_change_post_object() {
    global $wp_post_types;
    $labels = &$wp_post_types['post']->labels;
    $labels->name = 'Novice';
    $labels->singular_name = 'Novice';
    $labels->add_new = 'Dodaj Novico';
    $labels->add_new_item = 'Dodaj Novico';
    $labels->edit_item = 'Uredi novico';
    $labels->new_item = 'Novica';
    $labels->view_item = 'Poglej novico';
    $labels->search_items = 'Išči novice';
    $labels->not_found = 'Ni najdenih novic';
    $labels->not_found_in_trash = 'Ni novic v smeteh';
    $labels->all_items = 'Vse novice';
    $labels->menu_name = 'Novice';
    $labels->name_admin_bar = 'Novice';
}
 
add_action( 'admin_menu', 'revcon_change_post_label' );
add_action( 'init', 'revcon_change_post_object' );

//EN NEWS
function revcon_change_post_label() {
    global $menu;
    global $submenu;
    $menu[5][0] = 'News';
    $submenu['edit.php'][5][0] = 'News';
    $submenu['edit.php'][10][0] = 'Add News';
}
function revcon_change_post_object() {
    global $wp_post_types;
    $labels = &$wp_post_types['post']->labels;
    $labels->name = 'News';
    $labels->singular_name = 'News';
    $labels->add_new = 'Add News';
    $labels->add_new_item = 'Add News';
    $labels->edit_item = 'Edit News';
    $labels->new_item = 'News';
    $labels->view_item = 'View News';
    $labels->search_items = 'Search News';
    $labels->not_found = 'No found News';
    $labels->not_found_in_trash = 'No News in trash';
    $labels->all_items = 'All News';
    $labels->menu_name = 'News';
    $labels->name_admin_bar = 'News';
}
 
add_action( 'admin_menu', 'revcon_change_post_label' );
add_action( 'init', 'revcon_change_post_object' );

Disable Admin bar

Disabling admin bar on frontend

/* Disable Admin Bar for All Users Except Administrators Using Code */
function remove_admin_bar() {
    if (!current_user_can('administrator') && !is_admin()) {
        show_admin_bar(false);
    }
}
add_action('after_setup_theme', 'remove_admin_bar');


/* Disable WordPress Admin Bar for all users */
add_filter( 'show_admin_bar', '__return_false' );

Search – Only post types

Enable search only with post types:

function mySearchFilter($query) {
    $post_type = 'page';
    if($query->is_main_query()){
        if ($query->is_search) {
        $query->set('post_type', $post_type);
        }
    }
};
add_action('pre_get_posts','mySearchFilter');

Disable search

function disable_search( $query, $error = true ) {
  if ( is_search() ) {
    $query->is_search = false;
    $query->query_vars[s] = false;
    $query->query[s] = false;
    // to error
    if ( $error == true )
    $query->is_404 = true;
  }
}

add_action( 'parse_query', 'disable_search' );
// add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

// Check deprecated create_function

ACF choices dynamic (revolution slider)

Get ACF choices dynamic – Revolution slider:

function acf_load_color_field_choices( $field ) {
    // reset choices
    $field['choices'] = array();
    // get a list of all available sliders
	$my_sliders = new RevSlider();
	// grab the "alias" names of the sliders
	$my_slider_array = $my_sliders->getAllSliderAliases();
	foreach ($my_slider_array as &$value) {
	    $field['choices'][ $value ] = $value;
	}

    return $field;
}

add_filter('acf/load_field/name=revolution_slider_potep', 'acf_load_color_field_choices');

ACF settings page

Adding ACF option admin page

if( function_exists('acf_add_options_page') ) {
    acf_add_options_page(array(
        'page_title'    => 'Page Settings',
        'menu_title'    => 'Page Settings',
        'menu_slug'     => 'theme-general-settings',
        'capability'    => 'edit_posts',
        'redirect'      => false, //true redirects to the first child!!!
        'position' => 35,
    ));
    
    acf_add_options_sub_page(array(
        'page_title'    => 'Footer',
        'menu_title'    => 'Footer',
        'parent_slug'   => 'theme-general-settings',
    ));     
}

Disable mail notification

Stop sending admin emails for WP update

function wpb_stop_update_emails( $send, $type, $core_update, $result ) {
	if ( ! empty( $type ) && $type == 'success' ) {
		return false;
	}
	return true;
}
add_filter( 'auto_core_update_send_email', 'wpb_stop_auto_update_emails', 10, 4 );

Enqueue scripts/styles

Initial enqueue theme scripts/styles:

function enqueue_scripts() {   

    wp_enqueue_style( 'flexslider-css', get_stylesheet_directory_uri().'/js/flexslider/flexslider.css' );
    wp_enqueue_script('parodontologija_script', get_stylesheet_directory_uri() . '/js/scripts.js', '1.0.0', true);

}
add_action('wp_enqueue_scripts', 'enqueue_scripts');

Image Sizes

Register image thumbnails:

function images_setup() {    
    add_image_size( 'gallery-thumb', 805, 434, true);
}    
add_action('after_setup_theme', 'images_setup');

Backend editor dropdown thumbnail select:

function my_custom_sizes( $sizes ) {
    return array_merge( $sizes, array(
        'gallery-thumb' => __('Gallery Main'),
        ) );
    }
add_filter( 'image_size_names_choose', 'my_custom_sizes' );

Admin Menu – Edit

Admin menu elements:

function remove_menus(){
  // remove_menu_page( 'index.php' );                  //Dashboard
  remove_menu_page( 'edit.php' );                   //Posts
  // remove_menu_page( 'upload.php' );                 //Media
  // remove_menu_page( 'edit.php?post_type=page' );    //Pages
  remove_menu_page( 'edit-comments.php' );          //Comments
  // remove_menu_page( 'themes.php' );                 //Appearance
  // remove_menu_page( 'plugins.php' );                //Plugins
  // remove_menu_page( 'users.php' );                  //Users
  // remove_menu_page( 'tools.php' );                  //Tools
  // remove_menu_page( 'options-general.php' );        //Settings
}
add_action( 'admin_menu', 'remove_menus' );

//WP Welcome Panel dashboard
remove_action('welcome_panel', 'wp_welcome_panel');

//ACF DISABLE
add_filter('acf/settings/show_admin', '__return_false');

Hide submenu elements

function my_remove_sub_menus() {
    remove_submenu_page('edit.php', 'edit-tags.php?taxonomy=category');
    remove_submenu_page('edit.php', 'edit-tags.php?taxonomy=post_tag');
}
add_action('admin_menu', 'my_remove_sub_menus');