How to find and replace, incrementing the output by one each time

Recently had to fix a WordPress database with entries having a duplicate key.

They were 1974 entries with the same key.

And to fix that, as suggested by every resource online, you need to increment each key by one.

Good luck doing that manually.

Instead, in Ubuntu that can be done in a matter of seconds with Perl.

Use the following command:

perl -pi.bak -pe 'BEGIN{$A=STARTING_VALUE_INTEGER;} s/KEY_TO_REPLACE/$A++/ge' yourFile.sql

That’s it.

-p processes and prints <> line by line.

-i activates in-place editing. Files are backed up using the .bak extension.

Today I pushed the first version of my plugin to WordPress.org

Yesterday, May 5th, 2023, I got an email from the WordPress Plugin Review Team notifying me that my plugin submission to the WordPress plugin repository was approved.

It was no easy thing, and not on the first try (by a silly mistake from me).

I submitted it on April 7th. Almost a month later, I received an email that I needed to make corrections before the plugin could be approved.

Silly me, in the readme.txt file, I put the version of WordPress core in the Stable tag instead of my current plugin version. ** facepalm **

That was it.

I rushed to make the correction, ready to wait another 25+ days. The WordPress Plugin Review Team has been working harder than ever reviewing plugins because one of the leading team members recently left the team.

I was surprised with the approval email one hour later from submitting the changes.

I’m hugely grateful for that faster response.

I hope for the best for the WordPress Plugin Review Team and thank them for their titanic effort in reviewing all plugin submissions.

Today May 6th, I pushed my changes through SVN. Not that different from Git. Still, some stuff I need to integrate into my workflow. With practice, I’ll get the hang of it.

This experience has just made me want to submit more plugins to WordPress.org. I’ll be shipping more for sure.

Here is my plugin if you are curious: https://wordpress.org/plugins/obi-learndash-redirect.

Get up to speed with Git in your project

Do you remember writing an essay on your computer and then, on each “major” change to the document, saving the same file like geography-essay.docx, geography-essay_edited.docx, geography-essay_almost-ready.docx?

That is the reason you need Git in your software project. Git helps you keep track of your changes and, if something goes not as expected, go back to a previous version of what you were doing.

A WordPress plugin is an interesting example of that.

If you are on Linux, it is most likely Git is already installed on your device. You can check it simply with this command:

git --version

The output should be something like this:

If you get an error, then Git is not installed on your system. You can check here for step-by-step instructions on how to install Git https://git-scm.com/.

If you are on Ubuntu, like me, you can use sudo apt-get install git.

After you ensure Git is running on your computer device, let’s create a directory for your project.

mkdir cool-plugin && cd cool-plugin

Once you are inside the project directory, run the command:

git init

That’s it. Git will be initialized, and the directory you have just created is the repository of your project. As simple as that.

Now, feel free to create a cool-plugin.php file, which is the main plugin file.

<?php
/**
* Plugin Name: Cool Plugin
* Description: A very cool plugin for WordPress.
* Version: 0.0.1
* Author: Obi Juan
* Author URI: https://obijuan.dev/
* Plugin URI: https://obijuan.dev/
* License: GPL2 or later.
* Textdomain: cool-plugin
*/

add_action('plugins_loaded', 'cool_init');

function cool_init(){

  return true;

}

Ok, now that you have made some progress building the initial phase of your main plugin file, it’s time to “register” the changes in Git.

Before anything, let’s check the status. Use:

git status

This command will return the current status of your git repository. Whether there are changes or not, it will specify the current status. In this case, the output should tell you that the cool-plugin.php file was created and that it received some changes, but those changes are not registered yet.

So, to register those changes, we need to add the file to the staging and commit the changes.

First, add the cool-plugin.php to the staging.

git add cool-plugin.php

Then, register the changes with:

git commit -m "Initial commit. Add starting code to the main plugin file"

Hit enter, and the changes will be registered (committed).

The -m flag means message. And then, you can add any message you want in double-quotes.

I suggest you add a short description of what the changes are about. If it is only changing the version, then you can use something like “Update version”.

To make sure that the changes were committed, use again:

git status

Then it will say two important things: the current branch you are on and ‘nothing to commit, working tree clean’, which means there are no new changes to be registered.

Congratulations. You are now using git on your project.

In all honesty, there is more to it. You can create separate branches to conduct the development of a new feature, then merge them later with your main/master branch.

When you are ready to show your work to the world, you can send your project to a remote repository. That action is called pushing.

But that’s content for another post.

So for now, see you next time!

How to enqueue scripts or styles only if a shortcode exists on a page

In general, it is a best practice to only enqueue a script or style on your website, only where you need it.

Specifically, this helps with performance.

And in any case, why would you need yourSocialLogin.css file in every page of your website anyway, right?

So, let’s say you are adding a custom shortcode that relies on custom scripts and styles to be rendered correctly on your site’s frontend.

To enqueue the scripts and styles only on pages where the shortcode is implemented, you need to first check if the current is a page and if the page’s content has the shortcode.

For this, WordPress provides the functions is_page() and has_shortcode.

Also, remember to invoke the global $post variable so you can access the post object.

Something like this:

function check_if_page_has_my_shortcode(){

global $post; // To access the current post object.

  if(is_page() && has_shortcode($post->post_content, 'my_shortcode_tag')){
  
       return true; // The shortcode is in the page's content.
  
  } else {
  
       return false;
  
  }

}

That’s it!

Until next time.

Add a custom button to CheckoutWC’s side cart

CheckoutWC side cart by default allows you to display a ‘Proceed to Checkout’ button and a Continue Shopping button. Sweet.

But what if you want to add a custom button that does something different, or more interesting that just redirecting the user to the checkout page or back to the shop?

You can add a custom button with the cfw_after_side_cart_proceed_to_checkout_button action in CheckoutWC.

Simply, create a function that outputs the button HTML structure, then hook it into the action above mentioned.

Something as follows:

add_action('cfw_after_side_cart_proceed_to_checkout_button', 'obi_custom_side_cart_button');

function obi_custom_side_cart_button(){
	
	echo '<a id="custom_side_cart_button" href="#" style="background:#FF7500" class="cfw-primary-btn cfw-side-cart-checkout-btn"> My Side Cart Custom Button </a>';
	
}

The end result:

How to add a custom icon to each shipping method in WooCommerce

Shipping methods define how the purchase will be delivered to your customer.

Commonly, the shipping service is taken care of by a company. Some of the shipping companies are larger than others.

You can identify the Shipping Method with a label in the shipping method settings in WooCommerce.

But if you feel the shipping label is not enough, you can add an icon to it.

It can be the company’s logo or any other indication that the user can better familiarize themself with.

WooCommerce provides a filter woocommerce_cart_shipping_method_full_label that allows you to retrieve the label of a specific shipping method, make changes, then return the result you have created.

A basic implementation of the filter would be to detect if the shipping method is ‘Free Shipping’ and add a specific custom icon:

add_filter( 'woocommerce_cart_shipping_method_full_label', 'filter_woocommerce_cart_shipping_method_full_label', 10, 2 ); 

function filter_woocommerce_cart_shipping_method_full_label( $label, $method ) { 
   // Use the condition here with $method to apply the image to a specific method.      
	
	if($method->method_id == 'free_shipping'){
                $label = $label . '<img src='methodIcon.png'/>
        }
	
	
   return $label; 
}

Now, if you want to detect multiple shipping methods, instead of an if conditional, you can use a switch statement, better suited for multiple cases. The function then will return $label as many times as cases are processed from the switch statement.

Change the PDF certificate filename in LearnDash

The beauty of WordPress and open source is that virtually anything is customizable.

And premium plugins like LearnDash are not an exception to the rule.

In LearnDash, you can create certificates to reward your students after completing a quiz or finishing a course.

These certificates are generated as a PDF file on the fly. After earning the certificate, you can download the PDF file.

By default, LearnDash generates a file with the username, course name, certificate name and the website name.

Let’s say you are not interested in presenting this name format to your users, and you want something different instead.

For example, make the certificate name a combination of the website name, course and user ID.

You can do that with the following filter: learndash_certificate_builder_pdf_name

The filter admits three parameters, which we will use, filename, certificate ID, and course ID.

Then, you can use it as follows:

add_filter('learndash_certificate_builder_pdf_name', 'obi_custom_certificate_name', 10 , 3);

function obi_custom_certificate_name(){
     
     $course = get_post( $course_id ); // Instantiate the 'course' post object.
     $user   = wp_get_current_user(); // Instantiate the user object.
     $websiteName = get_bloginfo( 'name' ); // Retrieve the website name.

     $filename = $websiteName . ' - ' . $course->post_title . ' - ' . $user->ID . '.pdf'; // Build the filename structure.

     return $filename; // Always return the filename.
}

Add the code to your theme’s functions.php file, or create a custom plugin for it.

In WordPress I’d change…

Sometimes I see people get asked what would you change about WordPress CMS?

I have not been asked this yet, but if I were asked, first, I’d change how notifications are displayed to admins.

This is a problem that has existed for years, and nowadays, notifications have lost their real purpose.

Notifications in the core are useful when there is a major update of a plugin, and you need to update the database structure.

Or you purchased a theme and need to finish the setup.

In recent years, more plugins have abused the WordPress admin notifications to make a sale.

There are examples that come to mind, but I don’t want to point to anyone specifically.

You see long-form notifications asking for a review or to purchase a paid version of the plugin.

And they keep nagging you through the WordPress Dashboard, some even making it difficult to permanently dismiss the notification.

So, the change would consists in 1) Penalize plugins/themes that blatantly abuse the admin notifications and 2) Set a new place for notifications to show. Instead to be displayed at the top of the main content body in the WordPress admin area, add a drop-down to the WordPress Admin Bar and display the notifications in an auto-hiding div element. If the drop-down is not hovered, then no notifications are displayed.

The plugins page needs a change too. I’ll talk about that in another post.

Change the Billing fields position in CheckoutWC

In the WooCommerce standard checkout form, you are first asked for personal details like First Name, Last Name, Email Address, etc. Then, immediately you are asked to fill up the Billing Address. That’s nice in some cases, but it can be improved.

CheckoutWC, by design, changes this behavior by switching priorities between the Billing Address and Shipping Address, being the Shipping Address the first option right after the customer’s personal details.

The not-so-good thing is that, by default, it sends the Billing Address option right to the last step.

And there aren’t any options in the CheckoutWC settings to customize the field position.

However, it can still be changed with a bit of code.

So first things first, you need to identify where the Billing Address fields are on the checkout page.

Then, decide on a place to move it.

For this example, let’s move the Billing Address fields to the first step in the checkout page, which is the Information tab.

The destination place will be right below the Shipping Address.

Let’s lay out the steps you need to make the change.

First, “unhook” the Billing Address fields from the Payment tab.

remove_action( 'cfw_checkout_payment_method_tab', 'cfw_payment_tab_content_billing_address', 20 ); 

Second, hook it after the Shipping Address.

add_action( 'cfw_checkout_after_shipping_address', 'cfw_payment_tab_content_billing_address' );

That’s all! It’s that simple.

Determining the WordPress active theme when you can’t access the dashboard.

There are times that you cannot access a WordPress website at all. White Screen, Fatal Errors, you name it.

You can access via FTP and disable plugins by renaming the plugins folder. The same with the themes.

However, from outside of the WordPress Dashboard you cannot really tell what is the active theme.

If you have hosting access, go to the databases, and enter phpMyAdmin. Locate the site’s database.

Go to the wp_options table.

Navigate through the registries until you find a row with the option name set as ‘template’.

In the option_value column, you’ll see the name of the theme in question.