Categories
Knowledge Base

PHP Environment Variables

If your curious like me you will now this post explains how this works.

POST URL: https://mattallan.me/posts/how-php-environment-variables-actually-work/

Categories
Wordpress Code

How to create a Gutenberg Block Easily

Blocks are the new thing in the wordpress world, and for a good reason! they are super performant and the enable the possibility to do anything you can imagine.

Now imagine that you want to create a plugin that register a new block, and you also want to use ESNext.

In the official documentation of wordpress you can find this post.

Show me the code:

npx @wordpress/create-block todo-list
cd todo-list
npm start

I hope this helps someone :).

Categories
Linux

How to install PHP 7.4 in Ubuntu 18.04

sudo apt-get update
sudo apt -y install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

sudo apt -y install php7.4

# install the packages you want
sudo apt-get install -y php7.4-{intl,mbstring,gd,zip,pgsql,xsl,curl,fpm}

sudo apt-get install -y php-{amqp,redis}

# Disable apache
sudo systemctl disable --now apache2 

Categories
Wordpress Code

How to setup a wordpress site with Woocommerce using docker compose and xdebug in minutes

Follow this steps except for the commands section:

How to setup a wordpress multisite with docker compose and xdebug in minutes

Instead run this commands:

# create a templates directory
mkdir templates

# create a wp directory
mkdir wp

# move .htaccess file to template dir
mv .htaccess templates

# start docker containers
docker-compose up -d

docker-compose run --rm cli core install \
  --url=http://localhost \
  --title="test site" \
  --admin_user="admin" \
  --admin_password="admin" \
  --admin_email="example@example.com" \
  --skip-email

# to be able to update core we need write permissions
sudo mkdir -p wp/wp-content/uploads && sudo chmod -R 777 wp/wp-content/uploads
sudo mkdir -p wp/wp-content/upgrade && sudo chmod -R 777 wp/wp-content/upgrade

# install last version
docker-compose run --rm cli core update

# Only if you want to install specific version
docker-compose run --rm cli core update --version=5.4.2

Add woocommerce

# install woocommerce
docker-compose run --rm cli plugin install woocommerce --activate

# update woocommerce
docker-compose run --rm cli plugin update woocommerce

Install Storefront Theme

# install theme
docker-compose run --rm cli theme install storefront --activate

# update theme
docker-compose run --rm cli theme update storefront

Setup Woocommerce

Since last versions you can setup your store by using the GUI.

If you want to do it manually

# setup Woo
docker-compose run --rm cli post create --post_title='Home' \
    --post_type=page \
    --post_status=publish \
    | awk '{ print $NF }' | grep -Eo '[0-9]+' | read page_id

docker-compose run --rm cli option update page_on_front $(echo "$page_id")
docker-compose run --rm cli option update show_on_front page # or posts

docker-compose run --rm cli post create --post_title='Webshop' \
    --post_type=page \
    --post_status=publish \
    | awk '{ print $NF }' | grep -Eo '[0-9]+' | read webshop_id

docker-compose run --rm cli option update woocommerce_shop_page_id $(echo "$webshop_id")

Add some dummy data:

sudo chmod -R 777 wp/wp-content/plugins/woocommerce/sample-data

Then follow this:

https://docs.woocommerce.com/document/importing-woocommerce-sample-data/

Categories
Wordpress Code

How to setup a wordpress multisite with docker compose and xdebug in minutes

How to set up a wp site fast with xdebug.

This is the end result:

Prerequisites.

  • Docker

Instalation:

Create a Dockerfile like this one:

FROM wordpress:latest

ENV XDEBUG_PORT 9001
ENV XDEBUG_IDEKEY PHPSTORM

RUN pecl install "xdebug" \
    && docker-php-ext-enable xdebug

RUN echo "xdebug.remote_enable=1" >> /usr/local/etc/php/conf.d/xdebug.ini && \
    echo "xdebug.remote_autostart=1" >> /usr/local/etc/php/conf.d/xdebug.ini && \
    echo "xdebug.remote_port=${XDEBUG_PORT}" >> /usr/local/etc/php/conf.d/xdebug.ini && \
    echo "xdebug.idekey=${XDEBUG_IDEKEY}" >> /usr/local/etc/php/conf.d/xdebug.ini

Create docker-compose.yml file like this one:

version: '3.1'

services:

  wordpress:
    build: .
    ports:
      - 80:80
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: exampleuser
      WORDPRESS_DB_PASSWORD: examplepass
      WORDPRESS_DB_NAME: exampledb
      XDEBUG_CONFIG: >-
        remote_enable=1
        remote_mode=req
        remote_port=9001
        remote_host=172.17.0.1 # also could be host.docker.internal
        idekey=PHPSTORM
      PHP_IDE_CONFIG: serverName=php-docker

    volumes:
      - ./wp:/var/www/html
      - ./templates/.htaccess:/var/www/html/.htaccess

  db:
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: exampledb
      MYSQL_USER: exampleuser
      MYSQL_PASSWORD: examplepass
      MYSQL_RANDOM_ROOT_PASSWORD: '1'

  cli:
    image: wordpress:cli
    user: '33'
    environment:
      HOME: /tmp
    volumes:
      - ./wp:/var/www/html

  adminer:
    image: adminer
    ports:
      - 9999:8080

Create an .htaccess file like this one:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

Now run the followin commands:

# create a templates directory
mkdir templates

# create a wp directory
mkdir wp

# move .htaccess file to template dir
mv .htaccess templates

# start docker containers
docker-compose up -d

# wait 5 seconds
# install wordpress multisite
docker-compose run --rm cli core multisite-install \
  --url=http://localhost \
  --title="test site" \
  --admin_user="admin" \
  --admin_password="admin" \
  --admin_email="example@example.com" \
  --skip-email

We will end with an structure like:

Now visit http://localhost

Congratulations!

Categories
Wordpress Code

A tale about polyfills

What is babel polyfill?

babel-polyfill is a lib that you can import into your code. By doing so it will emulate a full ES6 environment.

The following code will not run in any browser without the necessary fixes that babel-polyfill provides.

<script>
    var nodes = document.querySelectorAll('.my-wanted-elements');
    // here we have a NodeList, but we want an Array of elements.
    var els = Array.from(nodes);
    // els is an array
</script>

Ok, so can I use it in every script in my plugins?

NO, you shouldnt use it in that way.

In wordpress there is a polyfill provided by the wp-polyfill.

It is bad practice to include the babel-polyfill several times.

Let’s imagine the following scenario

We have Plugin A and Plugin B, both enqueue a JS file via wp_enqueue_script().

If we use Gulp or Webpack to build our assets we may be tented to inject the babel-polyfill in both scripts.

YOU SHOULDNT DO THAT.

Ok, so what is the proposed solution?

WordPress official documentation states the following:

It is recommended to use the main wp-polyfill script handle which takes care of loading all the below mentioned polyfills.

https://developer.wordpress.org/block-editor/contributors/develop/scripts/#polyfill-scripts

It also says:

When using a JavaScript bundler like webpack, the scripts mentioned here can be excluded from the bundle and provided by WordPress in the form of script dependencies.

The

@wordpress/dependency-extraction-webpack-plugin

provides a webpack plugin to help extract WordPress dependencies from bundles. @wordpress/scripts

build script includes

the plugin by default.

https://developer.wordpress.org/block-editor/contributors/develop/scripts/#bundling-and-code-sharing

So you can use a webpack setup and add the plugin mentioned above and it will remove the dependencies from wordpress.

This way you let WP inject the polyfills independently from your scripts. You will still need to add wp-polyfill as dependency.

Another solution can be to write in ES6 and use wp-polifyll as dependencies.

Categories
Wordpress Code

A tip on wordpress add_rewrite_rule()

When you use add_rewrite_rule() function keep in mind the following:

  • Use it inside some hook, normally inside init hook.
  • It wont work unless you have custom permalinks activated.
  • Flush your permalinks

Show me some snippet

// register a custom parameter
add_filter( 'query_vars', function( $query_vars ) {
     $query_vars[] = 'myparamname';
     return $query_vars;
}, 30, 1 );

// do some action based on the custom param
add_action( 'template_include', function ($template) {

    if (get_query_var('myparamname') === 'someval') {
        return 'some other template';   
    }
        
    return $template;
        
}, 10, 1 );

// apply the rule
add_action( 'init',  function() {

    add_rewrite_rule( 'patata', 'index.php?myparamname=someval', 'top' );

}, 1, 0 );