Category: WordPress

  • WordPress Heading Anchors: Automatically Create Link Targets

    WordPress Heading Anchors: Automatically Create Link Targets

    Ever struggled with creating easy navigation within your long WordPress posts? Or wished you could link directly to specific sections of your content? Creating WordPress heading anchors automatically can dramatically improve your content’s navigation. In this guide, I’ll show you how to transform your WordPress headings into clickable link targets, making it easier for readers to navigate through your posts and share specific sections.

    How to enable WordPress heading anchors generation?

    The easiest way to enable this functionality would be the theme’s functions.php. Simply head to your WordPress backend:

    1. In the sidebar, hover on ‘Tools’
    2. Click on ‘Theme File Editor’
    3. In the file explorer, click on functions.php
    4. Paste the code
    add_filter( 'block_editor_settings_all', function( $editor_settings, $editor_context ) {
    	$editor_settings['generateAnchors'] = true;
    	return $editor_settings;
    }, 10, 2 );

    The theme’s functions.php is overwritten after theme updates so it is ill-advised to add code there.

    To ensure your custom code survives theme updates, you should create a child theme . A child theme inherits all the features of your main theme while allowing you to make safe customizations.

    Alternatively, you can create a simple site-specific plugin – just create a new PHP file in the wp-content/plugins directory with the following code:

    <?php
    /*
    Plugin Name: Auto Heading Anchors
    Description: Enable automatic heading anchors in the block editor
    Version: 1.0
    */
    
    add_filter( 'block_editor_settings_all', function( $editor_settings, $editor_context ) {
       $editor_settings['generateAnchors'] = true;
       return $editor_settings;
    }, 10, 2 );

    Both methods will preserve your code during theme updates. If you already have a custom plugin for your site’s functionality, that’s the perfect place to add this code.

    How does anchor generation work?

    Jump directly to the results

    The feature to make automatic anchor generation opt-in was introduced in this pull request after WordPress 5.9. I find this feature super useful and would have wanted it to be opt-out or at least wish that there was a UI to enable/disable this.

    The core/heading block is where the magic happens. In the autogenerate-anchors.js file. The heading edit function detects content but no anchor, It calls generateAnchor(clientId, content) which uses getSlug() to transform the content:

    • Removes accents
    • Replaces non-alphanumeric chars with hyphens
    • Converts to lowercase
    • Trims leading/trailing hyphens

    The anchor becomes the slug unless there’s a duplicate, in which case it would add -1, -2, etc.

    Results

    After enabling autogenerated anchors, you can observe that WordPress automatically adds an ID to the headings. This can be used for various purposes.

    You can link to your heading anywhere in your content by using the anchor feature of blocks like paragraph, heading, and button.

    Adding link to heading in WordPress

    You can create also create table of contents for long posts.

    If you’re interested in learning more about the WordPress Block Editor, I shared some helpful tips at WordPress Meetup Saarland recently. Feel free to check out my notes from the talk here!

  • Block Editor Best Practices: WordPress Meetup Saarland

    Block Editor Best Practices: WordPress Meetup Saarland

    WordPress Meetups are always one of the best ways to meet like-minded people, teach people about WordPress, have amazing discussions, and bring more people to the wonderful community. I participated in the 3rd WordPress Meetup in Saarland on 5th September, this time as a speaker. I talked about probably the most controversial feature of WordPress, the Block Editor (also known as Gutenberg). The topic was mainly about Block Editor Best Practices – for users, designers, and developers.

    Recently, we revamped rtCamp‘s website. It was a mammoth task – custom blocks, patterns, templates, and what not. During the process, we discovered some pain points with the block editor and also figured out some best practices. This talk focused on the outcomes of the project.

    During the talk, I realized how much context-switching I needed to do. One of the members in the audience was an artist and had just installed WordPress. They wanted to know the powers of Gutenberg. On the other hand, one of the members of the audience, Fredric Döll has founded Digitenser Consulting, wanted to learn more about how to efficiently create for and with the block editor for their clients.

    Gutenberg is a very powerful tool but it is often misunderstood. It is also important to understand that for some sites, Gutenberg may not make sense. But for the sites where editorial experience is key, it is imperative that the website is planned really well. A robust plan helps with feasible designs which lead to a better overall developer experience.

    The next WordPress Meetup in Saarland will happen on 23.01.2025. If you’re around Saarbrücken at that time, feel free to drop your emails in the comment.

    Note: In the presentation, we discussed negative margins. Gutenberg does have support for negative margins; however, our discussion was more oriented towards user experience. Currrently, negative margins in Gutenberg, have a little UX situation.

    Block Editor Best Practices – Deck

    You can access the presentation slides (Google Slides) this link.

  • New Relic with WordPress using Event API for better monitoring

    New Relic with WordPress using Event API for better monitoring

    New Relic is a leading application performance monitoring (APM) platform that offers developers invaluable insights into the performance of their applications. APM tools provide us with real-time monitoring, diagnostics, and analytics capabilities that enable us to gain deep visibility into our applications, track down performance issues, and make informed decisions to improve the overall user experience. If you wish to add monitoring to your server, here is how you can use Grafana Loki to monitor your server logs. WordPress is the most popular CMS in the world. Integrating New Relic with WordPress can help developers optimize their code and identify bottlenecks. It also helps ensure that the WordPress applications perform well under different loads and usage scenarios.

    Recently, we shipped a WordPress solution that relies heavily on third-party API. To obfuscate the keys and other confidential data, we used WP REST API as a relay which acts like a proxy (sort of). On the client side, we hit the WP REST API endpoints, which call the third-party API. We use Transients to cache the response on the server side. We also use a caching layer on the client side (using Axios and LocalStorage). The transients (server-side cache) mitigate redundant requests from different users to the third-party API, whereas the client-side cache reduces redundant requests from the same user to the site’s backend.

    In this post, we will learn how to integrate New Relic with WordPress using the Event API.

    Overview

    We could not install and configure New Relic’s PHP Agent to instrument external API calls (because the hosting platform did not allow that). Therefore, we decided to use the Event API. It is a powerful tool that allows us to send custom event data to New Relic Insights, their real-time analytics platform. Using Event API, we can capture and analyze specific events or metrics that are important to our application’s performance and operations.

    Flowchart of how Event API is triggered.

    Event API

    Using the Event API, we can programmatically send structured JSON data to New Relic Insights. The data can then be visualized and queried to gain deeper insights into our application’s behavior. This can include information such as user interactions, system events, errors, custom metrics, or any other relevant data points.

    To use Event API, we need to follow these steps:

    1. Obtain your New Relic Ingest - License API key.
    2. Obtain your Account ID.

    We have to use the following endpoint to POST to the Event API: https://insights-collector.newrelic.com/v1/accounts/{{ ACCOUNT_ID }}/events.

    The API Key needs to be set in the Headers. The JSON payload looks like this:

    {
      "eventType": "myEvent",
      "timestamp": 1652455543000,
      "applicationId": "myApp",
      "data": {
        "key1": "value1",
        "key2": "value2"
      }
    }

    The eventType is what we will use to query the data.

    $access_id = EXTERNAL_API_KEY;
    $response = wp_safe_remote_get( $endpoint );
    
    if ( is_wp_error( $response ) || 200 !== $response['response']['code'] ) {
    			$incident = send_external_api_incident( $endpoint, (string) $response['response']['code'], $response );
    			return new WP_Error(
    				(int) $response['response']['code'],
    				array(
    					'actual_response'    => $response,
    					'new_relic_incident' => $incident,
    				) 
    			);
    		}

    The send_external_api_incident() logic:

    /**
     * Sends API Incident event to New Relic.
     *
     * @param  string          $endpoint
     * @param  string          $response_code
     * @param  array|\WP_Error $response
     * @return array|\WP_Error
     */
    function send_external_api_incident( string $endpoint, string $response_code, array|\WP_Error $response ) {
    	$base_url = 'https://insights-collector.newrelic.com/v1/accounts/' . NEW_RELIC_ACCOUNT_ID . '/events';
    	$body     = [
    		array(
    			'eventType'    => 'ExternalApiIncident',
    			'endpoint'     => $endpoint,
    			'responseCode' => $response_code,
    			'response'     => wp_json_encode( $response ),
    		),
    	];
    	$response = wp_safe_remote_post(
    		$base_url,
    		array(
    			'headers' => array(
    				'Content-Type' => 'application/json',
    				'Api-Key'      => NEW_RELIC_INGEST_KEY,
    			),
    			'body'    => wp_json_encode( $body ),
    		)
    	);
    
    	return $response;
    }

    Checking the results

    Head over to the your New Relic account and click on your application. You can use NRQL queries to query data.

    SELECT * FROM `ExternalApiIncident` since 1 day ago


    In conclusion, integrating New Relic with WordPress application offers a robust solution for monitoring and optimizing application performance. This approach not only enhances the visibility of your application’s internal workings but also ensures a seamless user experience by efficiently tracking and analyzing critical data points. By following the outlined steps and best practices, you can successfully implement this powerful tool, even in environments with certain restrictions. The ability to customize event tracking and gain insights through real-time analytics is invaluable for developers aiming to maintain high-performance standards. Remember, continuous monitoring and improvement are key to staying ahead in the fast-paced digital world. Utilize these insights to keep your application running smoothly, and always be proactive in seeking ways to refine and enhance your system’s performance.

  • DevWP Day 2

    DevWP Day 2

    WordPress is a pretty powerful CMS but it is often misunderstood and its power is underestimated. People need to learn WordPress, not only because it drives almost half of the web but also because it is powerful, versatile, and open source.

    Hackoverflow Technical Society organized ‘DevWP’, a four-day-long WordPress contest in collaboration with rtCamp, a WordPress VIP Gold Agency Partner.

    Our goal is to introduce students, particularly college freshers and juniors, to WordPress. The participants will create a website on different topics, ranging from personal blogs to e-commerce websites, using WordPress. We want students to understand that WordPress is not just another CMS, but they can build really amazing applications using it.

    In this session, we had Muhammad Muhsin, Sourav Roy, and Paul David Clark with us. We covered three topics – Career Opportunities in WordPress, Journey as a WordPress Engineer, and Career Roadmaps. Muhsin is a Senior React Engineer at rtCamp, Sourav Roy is a WordPress Engineer, and Paul Clark is the Director of Engineer at rtCamp.

  • DevWP Day 1

    DevWP Day 1

    We are off to a great start ?

    Today was the Day 1 of #DevWP, a 4-day-long #WordPress#contest in collaboration with rtCamp. We are organizing this contest under the banner of #Genesis, our marquee #event for #freshers and #college#juniors.

    In this #edition, we thought of including a contest about #WordPress since people often underestimate its power. #WordPress is at the core of most of the #websites that we see today, so it is imperative for freshers to at least know about #WordPress.

    Today’s session was an orientation regarding the event and #WordPress. We discussed why #WordPress is important, installing #WordPress on #Windows#Linux, and #Mac, and some basic things about #WordPress.

    In tomorrow’s session, we have Paul David ClarkMuhammad Muhsin, and Sourav Roy from rtCamp with us. They’ll speak about #Career opportunities in WordPress, their #journey, and #Career#Roadmap.

    It is going to be a fun ride!

    Special mention to – Aditya KaneNicol FernandesRahul Bansal for helping Hackoverflow Technical Society and hundreds of #students from CHANDIGARH UNIVERSITY with this #collaboration.

  • Wildcard SSL Certificate on Linode using Certbot

    Wildcard SSL Certificate on Linode using Certbot

    I recently migrated to Linode for my personal portfolio and project (proof of concept) websites. I am running Ubuntu Server 20.04 LTS on a 1GB Nanode. Most of my websites use WordPress and I use Nginx, MariaDB, PHP (LEMP) as my stack. I use a Multisite Network since it let’s me manage all my websites from a single dashboard.

    Initially, I was using a single site, so I used Certbot to install a Let’s Encrypt SSL Certificate. If you plan to host only one site on your server then you should be good to go with a single Certbot command; however, if you’ve, or plan, to run more than one site on your server, the process is different. Let’s learn how we can install wildcard SSL certificates on Linode.

    Generating a Token

    To let Certbot manage your DNS Records, we first need to generate an API token or Personal Access Token (PAT). To generate an API token:

    1. Log in to your Linode account
    2. Click on your Profile & Account settings
    3. Choose API Tokens
    API Tokens - Profile & Accounts Linode
    API Tokens – Profile & Accounts – Linode

    Once you’re in, click on ‘Create a Personal Access Token’ option.

    Create a new token that can read/write your Domain Records. Since you’ll most likely be using this token just for Certbot, you can disable all the other privileges.

    Add a Personal Access Token - Linode Wildcard SSL
    Adding a Personal Access Token – Linode

    Click on ‘Create Token’, copy the generated token and save it somewhere safe. The tokens cannot be viewed again, so if you lose it, you’ll have to regenerate it.

    Now, create an .ini file to store your token. Your .ini file should look like this:

    # Linode API Credentials .ini file
    dns_linode_key = <YOUR_API_KEY>
    dns_linode_version = 4

    Installing Certbot

    Certbot is a free, open source software tool for automatically using Let’s Encrypt certificates on manually-administrated websites to enable HTTPS. We’ll use certbot package and python3-certbot-dns-linode plugin.

    Now, we can install the Certbot.

    sudo apt install certbot python3-certbot-dns-linode

    Generating Certificate

    We’ll not use Certbot’s automatic Nginx configuration, we’ll use Certbot to generate a certificate and then manually edit our Nginx files.

    To generate a certificate:

    certbot certonly --dns-linode --dns-linode-propagation-seconds <TIME_IN_SEC> -d <YOUR_DOMAIN> -d "*.<YOUR_DOMAIN>"

    For my website, the command will look like this:

    certbot certonly --dns-linode --dns-linode-propagation-seconds 180 -d danishshakeel.me -d "*.danishshakeel.me"

    We are using ‘*’ to let Certbot know that all the subdomains, such as blog.danishshakeel.me, hire.danishshakeel.me, or www.danishshakeel.me should be able to use the certificate. –dns-linode-propagation-seconds is the time (in seconds) for which we wait for the changes to propagate to the server before asking the ACME servers to verify.

    Certbot will ask you to input the path of the .ini file which we created.

    Input the path to your Linode credentials INI file (Enter 'c' to cancel): <PATH_TO_INI_FILE>
    Waiting 180 seconds for DNS changes to propagate
    Waiting for verification...
    Cleaning up challenges

    Congratulations, we have successfully generated our certificate and chain. Note down the path to the fullchain.pem and privkey.pem.

    Configuring Nginx

    Now, we can configure Nginx to use our certificate.

    options-ssl-nginx.conf

    Before we can edit our Nginx configurations, we need to ensure that options-ssl-nginx.conf exists in /etc/letsencrypt directory. In case it does not, we can simply create one and copy-paste this content into it.

    # This file contains important security parameters. If you modify this file
    # manually, Certbot will be unable to automatically provide future security
    # updates. Instead, Certbot will print and log an error message with a path to
    # the up-to-date file that you will need to refer to when manually updating
    # this file.
    
    ssl_session_cache shared:le_nginx_SSL:10m;
    ssl_session_timeout 1440m;
    ssl_session_tickets off;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    
    ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384";

    Configuring Nginx Server

    Now, let’s cd into our Nginx sites-available directory

    cd /etc/nginx/sites-available

    Now, we need to open our configuration file. I am using the default server block as my configuration.

    sudo vi /etc/nginx/sites-available/default

    Inside the server block, we need to add a few lines:

    server {
    ...
    
    listen [::]:443 ssl ipv6only=on;
    listen 443 ssl;
    ssl_certificate <FULLCHAIN_PEM_PATH>;
    ssl_certificate_key <PRIVKEY_PEM_PATH>;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    }

    Voila! You have successfully configured Let’s Encrypt Wildcard SSL Certificate on Nginx using Certbot.

    Footnotes:

    The process is similar for other providers, provided the provider is supported by Certbot. Here is the list of supported providers.