Author: Dusan Markovic

  • WordPress template files & loading

    The path which is used for processing user requests.

  • LAMP database import

    To import database using terminal in Linux use the following snippet:

    sudo /opt/lampp/bin/mysql -u root -p base_name_in_mysql < name_of_extracted_base

    Just remember to rename the database and extracted .sql file.

  • Git ignore already committed file updates

    There are situations when you need to escape from the regular Git workflow (committing all local changes, pulling all external changes). I’ll describe two such cases.

    Don’t commit locally modified files

    If, for some reason, you need to change file locally and don’t want to commit the file changes there is a git option –skip-worktree which you can use.

    E.g. you may want to update .htaccess file to pull website files from the production server (if they’re missing locally), but you don’t want to commit that change to git since it might cause issues on other environments. You’d just add cd into the root of your project (where your .htaccess file is located) and run something like this:

    git update-index –skip-worktree .htaccess

    Once you’re ready to let Git track your local changes for that file again – you can restore Git management by using the following command:

    git update-index –no-skip-worktree .htaccess

    Don’t update local files when externally modified

    When you want to keep a file as is and not pull the external changes (case with switching to other branches) you can use –assume-unchanged option.

    E.g. the other developer is constantly updating his npm/gulp settings and you don’t want to repeat that process locally. You could run something like this:

    git update-index –assume-unchanged gulpfile.js

    Once you’re ready to let those gulp changes flow into your local environment you can restore management to the git by using:

    git update-index –no-assume-unchanged gulpfile.js
  • WordPress image sizes

    Auto-generated thumbnails

    When you upload an image to your WordPress website, the platform creates 4 additional image sizes alongside your original image.

    Those automatically generated sizes are:

    • Thumbnail (‘thumbnail’): image with a maximum width of 150px and a maximum height of 150px
    • Medium (‘medium’): image with a maximum width of 300px or a maximum height of 300px
    • Medium-large (‘medium_large’): since wordpress 4.4,  image with a width of 768px and no max height
    • Large (‘large’): image with a maximum width of 1024px or a maximum height of 1024px

    These sizes can be changed inside the media settings page (/wp-admin/options-media.php), and you can also add custom sizes:

    // Must be included if your theme does not have it already.
    add_theme_support( ‘post-thumbnails’ );
    
    // Define new customs image sizes.
    add_action( ‘after_setup_theme’, ‘proultima_add_image_sizes’ );
    function proultima_add_image_sizes() {
      add_image_size( ‘portfolio’, 300, 9999 ); // 300px wide unlimited height
      add_image_size( ‘xl’, 1200, 9999 ); // 1200px wide unlimited height
    }
    
    // Add human-readable names to the newly added image sizes.
    add_filter( ‘image_size_names_choose’, ‘proultima_add_image_size_names’ );
    function proultima_add_image_size_names( $sizes ) {
      return array_merge( $sizes, array(
        ‘portfolio’ => __( ‘Portfolio’ ),
        ‘xl’ => __( ‘Extra Large’ ),
      ) );
    }

    Automatic image-size filters

    WordPress detects big images (big in their dimensions) which you uploaded and scales them down if their dimensions are larger than the threshold (e.g. 2560px threshold).

    The default width threshold can be overridden with max_srcset_image_width() function.

    The default dimensions threshold is filterable with big_image_size_threshold filter, and you can even disable it with:

    // completely disable image size threshold
    add_filter( ‘big_image_size_threshold’, ‘__return_false’ );

    Overriding image sizes

    Based on the breakpoints of your theme you can choose to customize the sizes attribute of the adaptive image tag. You can do that for the content images and for thumbnail sizes too:

    function proultima_content_image_sizes_attr($sizes, $size) {
        $width = $size[0];
        //Page without sidebar
        if (get_page_template_slug() === ‘template-full_width.php’) {
            if ($width > 910) {
                return ‘(max-width: 768px) 92vw, (max-width: 992px) 690px, (max-width: 1200px) 910px, 1110px’;
            }
            if ($width < 910 && $width > 690) {
                return ‘(max-width: 768px) 92vw, (max-width: 992px) 690px, 910px’;
            }
            return ‘(max-width: ‘ . $width . ‘px) 92vw, ‘ . $width . ‘px’;
        }
        //Page with sidebar
        if ($width > 597) {
            return ‘(max-width: 768px) 92vw, (max-width: 992px) 450px, (max-width: 1200px) 597px, 730px’;
        }
        if ($width < 597 && $width > 450) {
            return ‘(max-width: 768px) 92vw, (max-width: 992px) 450px, 597px’;
        }
        return ‘(max-width: ‘ . $width . ‘px) 92vw, ‘ . $width . ‘px’;
    }
    add_filter(‘wp_calculate_image_sizes’, ‘proultima_content_image_sizes_attr’, 10 , 2);
    function proultima_post_thumbnail_sizes_attr($attr, $attachment, $size) {
        //Calculate Image Sizes by type and breakpoint
        //Header Images
        if ($size === ‘header-thumb’) {
            $attr[‘sizes’] = ‘(max-width: 768px) 92vw, (max-width: 992px) 450px, (max-width: 1200px) 597px, 730px’;
        //Blog Thumbnails
        } else if ($size === ‘blog-thumb’) {
            $attr[‘sizes’] = ‘(max-width: 992px) 200px, (max-width: 1200px) 127px, 160px’;
        }
        return $attr;
    }
    add_filter(‘wp_get_attachment_image_attributes’, ‘proultima_post_thumbnail_sizes_attr’, 10 , 3);
  • Local environment GIT ignore file for WordPress websites

    # Ignore configuration and hidden files.
    .htaccess
    wp-config.php
    *.DS_Store
    *Thumbs.db
    .ftpquota
    
    # Ignore project files.
    /nbproject/
    
    # Ignore paths that contain user-generated content.
    /wp-content/uploads/
    /wp-content/upgrade/
    /wp-content/themes/twenty*
    /wp-content/cache
    /sitemap.*
    *.sql
    
    # Ignore log files
    error_log
    .log/
    
    # Ignore debug plugins and settings.
    /wp-content/plugins/fakerpress
    /wp-content/plugins/show-current-template/
  • Fix “Not enough free disk space” error in Ubuntu

    If you’re getting the “Not enough free disk space” error while trying to update Ubuntu – that doesn’t mean your hard drive is full, but rather one of Linux’s partitions (namely /boot). It’s getting clogged every time you update your software (it stores unneeded Linux headers, apt cache, thumbnail and Chrome’s cache). The best (graphical) way to fix this issue is to install “Ubuntu Cleaner” app. To do this open the terminal and run the following commands:

    sudo apt update -y && sudo apt upgrade -y && sudo apt install git software-properties-common -y
    sudo add-apt-repository ppa:gerardpuig/ppa
    sudo apt update -y
    sudo apt install ubuntu-cleaner

    After that search the dash for “Ubuntu tweak“.
    Once open, go to “Janitor” tab, select “Apps“, “Personal” and “System” check boxes and click “clean” button.

    That’s it! Now run “Software Updater” again.
    Note: you might have to repeat cleaning from time to time.

    You can also run the following commands:

    • To get rid of the no-longer required packages:
      • $ sudo apt-get autoremove
    • To check and clean up the APT cache:
      • $ sudo du -sh /var/cache/apt
      • $ sudo apt-get autoclean
    • To check and clear the systemd journal logs:
      • $ journalctl –disk-usage
      • $ sudo journalctl –vacuum-time=3d
    • To check and remove older versions of Snap applications:
      • $ du -h /var/lib/snapd/snaps
      • Create a shell script, give it execute permission and run it
        • #!/bin/bash # Removes old revisions of snaps # CLOSE ALL SNAPS BEFORE RUNNING THIS set -eu snap list --all | awk '/disabled/{print $1, $3}' | while read snapname revision; do snap remove "$snapname" --revision="$revision" done
    • To check and clean the thumbnail cache:
      • $ du -sh ~/.cache/thumbnails
      • $ sudo rm -rf ~/.cache/thumbnails
    • To remove old kernels
      • $ sudo apt-get autoremove –purge
  • Force HTTPS

    To force Drupal or WordPress sites to use secure https:// instead of http:// version of your site just add the following to the .htaccess file:

    Note: replace “www.example” with the appropriate site domain. Also, this rewrite rule should be the first rule in your .htaccess file, since otherwise in some situations rewrites might not ever get to this rule.

    # Force https access. 
    RewriteEngine On 
    RewriteCond %{SERVER_PORT} 80 
    RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
  • WordPress files & folders permissions

    To set up the correct WordPress files & folders permissions you need to run these two commands in your terminal/command prompt in the root folder for your WP project:

    find . -type d -exec chmod 755 {} \;  # Change directory permissions rwxr-xr-x
    find . -type f -exec chmod 644 {} \;  # Change file permissions rw-r–r–
  • Find an element which is adding a horizontal sliding bar to the page

    This is the cool article which explains how to troubleshoot: https://css-tricks.com/findingfixing-unintended-body-overflow/

    Or you may use the following code and add it to the Console (Developer Tools).

    var all = document.getElementsByTagName(“*”), i = 0, rect, docWidth = document.documentElement.offsetWidth;
    for (; i < all.length; i++) {
        rect = all[i].getBoundingClientRect();
        if (rect.right > docWidth || rect.left < 0){
            console.log(all[i]);
        }
    }
  • Free online Network tools

    If you need to check IP address, DNS settings and records, or your hosting neighbors here are few of the best free online network tools out there.

  • Free deobfuscate online tools

    For PHP

    UnPHP: A free online service to decode obfuscated PHP code. A good chance to solve your issue.

    PHP Decoder: The same as above and still useful (if UnPHP was not successful).

    Eval base64_decode: also useful for PHP code

    For JavaScript

    Script Asylum: A good tool for escaping/encoding text, HTML or JavaScript.

    Base64: HEX encode/decode

  • CSS optimization

    CSS resources are render-blocking. Here are the steps for optimizing your CSS:

    • Consider using not so deep CSS rules (e.g. this is deep rule: “.mydiv .second-layer > p > span.too-deep”),
    • If CSS is one-time-only and you’re sure you’ll not need it again on other pages you can inline it.
    • Minify files (removes all white-spaces and comments).
    • You can move all CSS styles with media queries from render-blocking CSS (e.g. style.css) into non-render-blocking CSS file (e.g. mobile.css) with setting media attribute to link tag:
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="mobile.css" media="(max-width: 768px)">
    <link rel="stylesheet" href="print.css" media="print">
    • Compress the CSS files,
    • Cache those files on the server side.
  • JavaScript Optimization

    JavaScript resources are parser-blocking so consider doing this to speed-up your JavaScript on your website:

    • If the script does not affect the DOM tree (does not add or modifies HTML) and is not affecting stylesheets then you can put it inside external file, call it inside <head> element and add an “async” attribute
    <head>
      ...
      <script src="analytics.js" async></script>
      ...
    </head>
    • defer Javascript execution (The script tag can also take a defer attribute, in the same way that it can take an async attribute. The difference is that with defer, the script waits to execute until after the document has been parsed, whereas async lets the script run in the background while the document is being parsed.)
    • Minify, compress and Cache JS.
  • WordPress optimization

    For page to be downloaded and processed faster we need to:

    • Minimize bytes (smaller code takes less time to dowload),
    • Reduce critical resources (minimize use of render-blocking CSS and parser-blocking JS files)
    • Shorten CRP (Critical Rendering Path) length.

    Page rendering path: https://developers.google.com/web/fundamentals/performance/critical-rendering-path

    • Begin DOM construction by parsing HTML,
    • Request CSS+JS resources,
    • Parse CSS and construct CSSOM
    • Execute JS (these are render-blocking JS files)
    • Merge DOM + CSSOM into the Render Tree,
    • Run layout on the render tree to compute geometry of each node and
    • Paint the individual nodes to the screen

    Place Any Non-CSSOM Querying JavaScript Before CSS; Place Any CSSOM-Querying JavaScript After CSS!!!

    All non-essential scripts that are not critical to constructing the visible content for the initial render should be deferred.

    WHY SO? If the files do not depend on one another, then you should place your blocking scripts above your blocking styles—there’s no point delaying the JavaScript execution with CSS upon which the JavaScript doesn’t actually depend.

    Broadly speaking, this is why CSS is so key to performance:

    1. A browser can’t render a page until it has built the Render Tree;
    2. the Render Tree is the combined result of the DOM and the CSSOM;
    3. the DOM is HTML plus any blocking JavaScript that needs to act upon it;
    4. the CSSOM is all CSS rules applied against the DOM;
    5. it’s easy to make JavaScript non-blocking with async and defer attributes;
    6. making CSS asynchronous is much more difficult;
    7. so a good rule of thumb to remember is that your page will only render as quickly as your slowest stylesheet.

    HTTP/2 has made obsolete:

    • Domain sharding
    • concatenation
    • image sprinting

    RESOURCES:

    • https://web.dev/fast/#prioritize-resources
    • https://developers.google.com/web/fundamentals/performance/critical-rendering-path
    • https://csswizardry.com/2018/11/css-and-network-performance/

    While open Google DevConsole click CTRL+SHIFT+P and search for:

    • Coverage (to see what portion of external resources is actually used and to see which part)
    • Lighthouse (to generate report on performance).

    Further optimize Bootstrap4 resources (remove CSS and JS which is not needed)

    Use imagemin webp package to convert all images to webp format. https://web.dev/serve-images-webp/

    for file in images/*; do cwebp "$file" -o "${file%.*}.webp"; done

    Use critical tool to detect the critical assets which should be preloaded.  https://github.com/addyosmani/critical/blob/master/README.md

    Use https://gtmetrix.com/ plugin to test web page speed.

    Create our plugin which would work as: https://perfmatters.io/features/

  • Debugging chrome on iOS

    For javaScript issues you need to open new tab in chrome ( chrome://inspect ) and you’ll get javascript console logs for all open windows.

    Or you can install: https://github.com/RemoteDebug/remotedebug-ios-webkit-adapter.

  • 3rd party software

    Third party providers can be divided into these categories:

    • Ad – display and measurement of advertisements
    • Analytics – tracking site visitor behavior
    • CDN – providers that host public shared utilities or private content of their users (bootstrapcdn.com, cdnjs.cloudflare.com, …)
    • Content – providers that facilitate publishers and host syndicated content
    • Customer Success – support and customer relationship management functionality
    • Hosting – providers that host the arbitrary content of their users
    • Marketing – sales, lead generation, and email marketing functionality
    • Social – social networks and their affiliated integrations
    • Tag Manager – provider whose sole role is to manage the inclusion of other third parties
    • Utility – code that aids the development objectives of the site owner
    • Video – providers that host the arbitrary video content of their users
    • Other – uncategorized or non-conforming activity

    The three primary usage patterns of third-party resources:

    • Generate and consume data (analytics, social providers,)
    • Monetize web traffic (marketing and ad networks)
    • Simplify development (analyze user behavior, video, image, font and library hosting …)

  • Web server optimization

    Weather your web server is apache or nginx you should:

    • disable image hotlinking: when other websites serve images directly from their website by using the URLs from your website, instead of uploading them to their own servers. In effect, they’re stealing your web hosting bandwidth, and you don’t get any traffic to show for it.
    • Use the latest PHP version (the fastest)
    • Limit post revisions:
      define(‘WP_POST_REVISIONS’, 4 );
    • Use DNS level website firewalls (block malicious requests even before they reach your website, blocks brute-force attacks, hacking attempts and malware) like Sucuri and Cloudflare.
    • Add page caching,
    • Minify & compress (gzip) your HTML, CSS and JS files
    • Use Object cache (cache database query results) Redis.
    • Use Page cache (no PHP or MySQL requests at all, static page served from the Page cache)
    • Compress your images.
    • Fix Crontab to use the UNIX system time events, not on the user hitting the server.
    • Best Tech stack to use
      • Nginx over Apache (Nginx can use PHP’s FastCGI process manager called PHP-FPM)
      • Varnish over FastCGI (Varnish is more flexible, but FastCGI Cache is easier to configure, uses less resources and performs better. Also FastCGI cache i easier to maintain because it comes included with Nginx)
      • Memcached vs Redis (Redis is a newer, more modern in-memory data store than Memcached. It has more features and seems to be a more popular choice in the WordPress community)
      • MariaDB over MySQL (MariaDB is faster and fully open-source)
    • Constant Application (Server) Monitoring (New Relic)(constantly pinging the server and making sure that it’s always up and running. Monitoring high resource usage (CPU or SQL). If Nginx or PHP appear at the top of the list for CPU usage we should check our access and error logs, if it’s MySQL then we need to enable the slow query log.
    • Ongoing Maintenance (keeping WordPress core and plugins up to date) Checking for newly discovered vulnerabilities and making sure the website can’t be attacked.