Categories
Servers Web WordPress WordPress Plugins

WordPress Gutenberg Blocks Using Server Side Rendering

To create a Gutenberg block to display all posts in WordPress, follow these steps:

  1. Create a new directory in your WordPress theme or plugin directory called “my-post-block”.
  2. Inside the “my-post-block” directory, create a new PHP file called “index.php”.
  3. Add the following code to the “index.php” file to register a new Gutenberg block:
<?php
/**
 * Plugin Name: My Post Block
 * Description: A Gutenberg block to display all posts.
 * Version: 1.0.0
 * Author: Your Name
 *
 * @package my-post-block
 */

defined( 'ABSPATH' ) || exit;

function my_post_block_register_block() {
    wp_register_script(
        'my-post-block',
        plugins_url( 'block.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element', 'wp-components' ),
        filemtime( plugin_dir_path( __FILE__ ) . 'block.js' )
    );

    register_block_type( 'my-post-block/my-post-block', array(
        'editor_script' => 'my-post-block',
    ) );
}
add_action( 'init', 'my_post_block_register_block' );

This code will register a new Gutenberg block with the name “My Post Block”.

  1. Next, create a new JavaScript file in the “my-post-block” directory called “block.js”.
  2. Add the following code to the “block.js” file to define the block:
( function( wp ) {
    var registerBlockType = wp.blocks.registerBlockType;
    var ServerSideRender = wp.components.ServerSideRender;

    registerBlockType( 'my-post-block/my-post-block', {
        title: 'My Post Block',
        icon: 'admin-post',
        category: 'common',
        edit: function( props ) {
            return wp.element.createElement(
                ServerSideRender,
                {
                    block: 'my-post-block/my-post-block',
                    attributes: props.attributes,
                }
            );
        },
        save: function() {
            return null;
        },
    } );
} )( window.wp );

This code will define the block and specify that it should use a server-side render function to generate the block’s output.

  1. Finally, create a new PHP file in the “my-post-block” directory called “render.php”.
  2. Add the following code to the “render.php” file to generate the output for the block:
<?php
/**
 * Server-side rendering for the My Post Block.
 *
 * @package my-post-block
 */

defined( 'ABSPATH' ) || exit;

function my_post_block_render() {
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1,
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        $output = '<ul>';

        while ( $query->have_posts() ) {
            $query->the_post();
            $output .= '<li><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></li>';
        }

        $output .= '</ul>';

        wp_reset_postdata();

        return $output;
    }

    return 'No posts found.';
}

register_block_type( 'my-post-block/my-post-block', array(
    'render_callback' => 'my_post_block_render',
) );

This code will define a render function that uses a WP_Query object to retrieve all posts and output them in an unordered list.

That’s it! You now have a Gutenberg block that displays all posts. You can customize the output by modifying the “render.php” file to suit your needs.

Categories
Servers Web WordPress

How does the web work?

The Web is a subset of the Internet.

While the Internet makes up all communication between computers within any application, port, or protocol — the Web generally refers to networks of computers communicating over Hyper Text Transfer Protocol (HTTP), serving Hyper Text Markup Language (HTML) and related assets, such as images, stylesheets, and scripts.

All these technologies work together to create web sites and web applications, parsed by the web browsers and various Application Programming Interfaces (APIs).

When a user requests a web page in a web browser, the process typically looks like this:

  • Search, Social, or Direct Access: If a user types in a search phrase, and the browser bar also acts as a search bar, the web site of the default search engine is queried.
  • DNS Lookup: If the user types in an exact web address, or clicks a link from a social web site or search engine, a Domain Name Server lookup determines which computer should respond to the request.
    • Domain name servers can be overridden with a hosts file.
    • Some domain name servers can intercept, modify, and optimize content. For example, Cloudflare, which can add SSL, optimize HTML, optimize images, etc.
  • Connection & Headers: Browser negotiates either an insecure HTTP connection on default port 80, or a secure HTTPS connection on default port 443. Request headers and response headers are sent. These are viewable in the Web Inspector.
    • A web server doesn’t have to be running on default ports. For example, many development servers might load websites at localhost:8080 or any other arbitrary port.
  • Initial HTML & AJAX: If a browser request is the first request, HTML is most likely returned. This HTML usually contains references to hundreds of other files, which are requested and processed by the browser.
    • Initial HTML and AJAX requests, in our case, are typically handled by a Content Management System such as WordPress.
      • Each request spins up a new PHP process. One page might involve hundreds of HTTP requests!
        • Content Management Systems, such as WordPress, will typically not only spin up a programming language process, but also a database instance for content. This might be MySQLSQLiteMongoDB (NoSQL), or many others.
      • If WordPress is not in use, PHP might still be in use with another PHP-based CMS such as Laravel.
      • If PHP is not in use, the web server could be using any number of server-side technologies, such as static assets (plain HTML or JavaScript), a NodeJS framework such as AdonisJS, or another language such as Ruby, Java, Python, or C# (Microsoft ASP.NET).
  • Static Assets: If the requested file is a static asset, such as CSS, JavaScript, or images, a PHP process is typically not spun up (though PHP can serve these things!) Instead, they are typically served directly by the web server (ApacheNginx, a combination of these, or another server, such as Lighttpd or ASP.NET’s Kestrel server).
    • Serving static assets without PHP is faster than spinning up a PHP process — often by an order of magnitude.
    • Nginx is usually faster than Apache. For this reason, they are sometimes used together, with Nginx as a front-end proxy.
    • Static assets are sometimes offloaded to another server entirely — for example, a CDN such as Cloudflare CDNJetpack, or JSDelivr.
    • Each static asset, JavaScript, CSS, and images, require processing by the browser.
  • Once a web page is loaded, the user starts to interact with the page. From here, simple web pages might link to other pages, re-initiating the entire cycle. If JavaScript is in use, as with Decoupled WordPressReactJS, or plugins like Flying Pages, JavaScript might be used to update page content without reloading initial HTML.

Caching: It’s important to note — caching may take effect at almost every step of the connection process. The browser has a cache. DNS may have a cache (Cloudflare), the CMS may have a cache, and there may be various application-level caches (WordPress wp_object_cache, WordPress Transients API, or plugins such as W3 Total Cache) or server-level caches, such as RedisVarnish, or Nginx.

Resources

Whether you believe it or not, there are great resources out there that have helped hundreds of people with no technical background become web/WordPress developers. If you would like to explore this more for yourself, or just learn more about web development in general, here are some useful links:

And if you have enjoyed this post, feel free to share it or subscribe to my newsletter below.