How to debug your wordpress function to the browser console

At time, it might be useful to debug some plugin or theme function directly in your browser console. It comes handy specially if you are sending some data live with jquery to a php function when you input something here and click some button there.

Add the following function to your theme functions.php:

//Send message to the web console

function debug_to_console( $data ) {
    $consoleLog = $data;
    if ( is_array( $consoleLog ) )
          $consoleLog = implode( ',', $consoleLog);
    echo '<script>console.log( "Debug Objects: ' . $consoleLog . '" );</script>';
 } 

Now you can add debug_to_console($data ) in your theme and plugins to check what value your variable take. Replace $data with whatever value you need to monitor.

Display wp plugins script and style handle

If you are serious about your site optimization, there will be a point where you want to control all these additional scripts and stylesheets your plugins are loading on your site.

To do so you will need to know the handle that is used to identified the said stylesheets and and scripts.

One easy way is to have it displayed front end in your test environment.

Add the following code to your theme function.php:

function get_enqueued_scripts () {

    $scripts = wp_scripts();

    echo 'Enqueued scripts:
';

    foreach( $scripts->queue as $handle ) :

        echo $handle.' | ';

    endforeach;

    echo '
';

}
 add_action( 'wp_head', 'get_enqueued_scripts', 9999 ); 

And to get the handles of the enqueued style sheets:

function get_enqueued_styles () {

    $styles = wp_styles();

    echo 'Enqueued styles:
';

    foreach( $styles->queue as $handle ) :

        echo $handle.' | ';

    endforeach;

}
 add_action( 'wp_head', 'get_enqueued_styles', 9999); 

In case you don’t have a test environment (really?) you can display this info in the console, don’t forget to disable that after you are done optimizing your site.

Defer the execution of javascript and load js files in the footer

In a previous article we have seen how to manually concatenate scripts in your main theme to avoid loading multiple files.

In case you can’t concatenate some scripts here are two options to defer the exectution of the script until after the page has fully loaded or simply load a php script in the footer rather than in the header of your page.

Defer the execution of a script:

For your inline scripts:

<script defer> your script</script>

And it is exactly the same when the scripts are in an external file:

<script src="/path/to/your/script" defer></script>

Execute a function in the footer instead of the header.

In one of my plugn I had the case where I needed to fetch all the categories and product variation in jquery plugin that allow live display and filtering for a given search string. As such, the jquery is prepared in a php file that I then included in my theme header with and include function. Until I realize I can as easily load the script in the footer and avoid to overload my header.

In the index.php file of the plugin:

add_action('wp_header', 'PluginName::functionName);

simply becomes:

add_action('wp_footer', 'PluginName::functionName);

functionName is your plugin function that contains the include statement that should be loaded in the footer.

Control what javascript and css files your wordpress plugins load.

Javascript and css can heavily impact your page load time and the ability of google bots to render your page. The consequence on your ranking might be heavy in case the page to be marked as not mobile friendly due to this rendering issue.

A solution is to reduce the number of css and js files your wordpress site loading.

As you have noticed, many plugins load their own css and js in order to perform their function and nicely display the output, which is perfectly legitimate, although it might not be desirable for a web designer concern with performance, as you ought to be ;)

I am pretty sure I don’t need to make the matter clear, as you are reading this article but just in case, let’s recall here that on top of impacting your SEO as stated above, there is a 5% drop in sales for each 0.1 sec of load time (I am not sure I state that correctly but you got the idea).

So, what the solution you may ask, rightfully, so let’s dig into that without any further delay.

The strategy we will explore here is to dequeue the plugin css and js and concatenate it to your theme js and cs

Dequeue a plugins javascript file or css stylesheet:

To dequeue the script you want to concatenate add the following code
in your theme functions.php :


add_action('wp_print_styles', 'deregister_styles', 100);

function deregister_styles() {
  wp_deregister_style('name-of-style');
}

Merge Javascript and styling with your existing files

Locate the style or js you have deregistered and copy and paste it’s content in your theme css or js.

Test your site thoroughly to make sure there is no conflict. Paste the code in your stylesheet in the order they are loaded on your page. Once you are sure everything is displaying properly, you might merge the style rules and remove the duplicated one in case there are.

There are more advance technique to load css such as css preprocessing. which we will cover in further articles.

More info on this excellent article:
https://davidwalsh.name/remove-stylesheets

Tips:

In order to make sure you are removing the right css files from the queue, use the developper tool of your browser and inspect the element related to your plugin, you will which css rules affect them and from what file they come from. Once you have noted the name of the css file you know which one you need to copy to your own css rules and remove from the queue.

WP Plugins or Themes Update error: “Destination directory for file streaming does not exist or is not writable “

Check in wp-config.php which folder is assigned as the temporary directory. the line will start with

  
define('WP_TEMP_DIR', ABSPATH . '/path/to/temp');

Through ftp check the permission on the folder. It should be 755.

Even if all seems alright the update might still failed. In my case my wp-config.php is placed outside the public directory altogether. I decided to go with a temp folder also place outside of the public directoy, those I had to modify my wp-config.php (which is placed in its dedicated directory) as follow:

. I decided to go with a temp folder also place outside of the public directoy, those I had to modify my wp-config.php (which is placed in its dedicated directory) as follow:

define('WP_TEMP_DIR', ABSPATH . '/../temp/');

The path that was causing the error was as follow:

define('WP_TEMP_DIR',dirname(FILE).'/wp-content/uploads');

Placing the wp-config.php outside the public directory allow for an extra layer of security in case the php settings of the apache server get messed up and the php files are exposed instead of being executed. Even though this situation SHOULD NOT happen, there is a possibility that it does and that’s what security is about afterall: being prepared for the unlikely events.

Find woocommerce and wordpress hook

Source: http://hookr.io/filters/

Source: https://docs.woocommerce.com/wc-apidocs/hook-docs.html

Source: https://codex.wordpress.org/Plugin_API/Filter_Reference

Function reference: https://codex.wordpress.org/Plugin_API

Woocommerce hooks: https://docs.woocommerce.com/wc-apidocs/hook-docs.html

Visual guide: https://businessbloomer.com/woocommerce-visual-hook-guide-account-pages/

Securing wp-config.php

There is a clear case for moving the file out of the public directory: see the following stackexchange thread https://wordpress.stackexchange.com/questions/58391/is-moving-wp-config-outside-the-web-root-really-beneficial

Just move wp-config.php one level up outside the public directory and wordpress will be able to look for it on its own automatically and you’re all set.

If you have installed several wordpress site in different subdomain, the option might not work for you. In that case, follow the instruction below taken directly from the aforementionned stackexchange thread:

How to move wp-config.php to any location on your server

WordPress will automatically look one directory above your WordPress installation for your wp-config.php file, so if that’s where you’ve moved it, you’re done!

But what if you’ve moved it somewhere else? Easy. Create a new wp-config.php in the WordPress directory with the following code:

<?php

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');

/** Location of your WordPress configuration. */
require_once(ABSPATH . '../phpdocs/wp-config.php');

(Be sure to change the above path to the actual path of your relocated wp-config.php file.)

If you run into a problem with open_basedir, just add the new path to the open_basedir directive in your PHP configuration:

open_basedir = "/var/www/vhosts/example.com/httpdocs/;/var/www/vhosts/example.com/phpdocs/;/tmp/"

That’s it!

How to set wordpress admin in a different language than the front end language

It may happen that you work with a woocommerce site that is set in a different language than your native tongue which can make navigating the wordpress admin panel very confusing depending on your level of command of the said language.

Solution: Fortunately enough the solution is realyy simple. 

Go to users

click on your user name.

under language, select the language that fit your need

Save and you’re done! WordPress is now the desired language only for you. All other user see the language as set as in Settings -> General -> Site language

Use JCH optimize with woocommerce

Issue:

JCH optimize might cause issue with the checkout page with certain payment plugin. A loading circle appear and don’t seem to go away anytime soon.

Solution:

To sort that out simply exclude some files related to the checkout page from optimization in jch optimization dashboard. I have excluded …/assets/css/frontend.css from Exclude these CSS files and our payment plugin css: 
checkout-maksukavat.css in  Exclude CSS files from these plugins

Batch convert images in webp

In case your server doesn’t allow Webp Express to auto generate webp images, or for any other reason, you might want to bulk convert images in webp.

On windows the best solution I found was to use https://www.imagemagick.org/script/convert.php

I needed to add some batch scripting to allow for bulk conversion 

I tested this code with the inconvenience that the file name retains .jpg and get appended with the webp extension, which is not suitable for my case use. I corrected that with a python script that I had ready at hand for batch renaming files. Here is the batch script:

cd C:\Users\Admin\Documents\webptest\2018\09
dir /B /A-D > list.txt
FOR /F “tokens=* delims=” %%x in (list.txt) DO magick convert %%x %%x.webp

While looking for a solution to remove the file extension, I found this nice code from stackoverflow that I modified to suit my needs:

@echo off
for /R “C:\Users\Admin\Documents\webptest\2018\10” %%f in (*.jpg) do (
magick convert %%f %%~nf.webp
)
pause

Tested and working. The file are saved in the directory containing the batch script.