17 June 2023

WordPress - Some useful snippets

This is a collection of useful Git scripts and snippets that I have collected over time.

Generate wp-config.php salts

This is used to generate a unique set of salts. Simply copy the output and paste in your wp-config.php

function generate_key() {
  echo -n "${1}: '"
  tr -dc 'A-Za-z0-9!"#$%&()*+,-./:;<=>?@[\]^_`{|}~' </dev/urandom | head -c 64  ; echo -n
  echo "'"
}

generate_key "auth_key"
generate_key "secure_auth_key"
generate_key "logged_in_key"
generate_key "nonce_key"
generate_key "auth_salt"
generate_key "secure_auth_salt"
generate_key "logged_in_salt"
generate_key "nonce_salt"

When you have a drop down menu, on phones, the top level is a link which will never allow mobile users to access the sub menu. To fix this, add the following to the functions.php file in your theme directory.

add_filter( 'wp_nav_menu_items', function ( $menu ) {
    return str_replace( '<a href="#"', '<a', $menu );
} );
add_action( 'wp_footer', function(){
    ?>
    <script>
    (function( $ ) {
        var itemm = $('#primary-menu .menu-item-has-children > a');
        itemm.click(function(e){
            e.preventDefault();
            document.activeElement && document.activeElement.blur();
            $(e.target).parent('li').find('.subnav-toggle').click();
            return false;
        });
    })(jQuery);
    </script>
<?php
 }, 1, 0 );

Generate a Maintenance file to turn off website while doing updates

This can be handy if you’re replacing the database or doing some other destructive work where you would like to temporarily bring down the site.

Create a .maintenace file in the root of your WordPress directory with the following contents

<?php $upgrading = time(); ?>
tags: wordpress