Reolved failed upload in WordPress post edit filter

When adding an upload form to the post edit screen in WordPress admin, I found the upload to fail. The $_FILES array was empty.
The reason was that by default, WordPress post edit form does not send files data.

To fix that, we need to add enctype attribute to the form.
Here is the code to do that-

add_action( 'post_edit_form_tag' , 'post_edit_form_tag');
function post_edit_form_tag( ) {
    echo ' enctype="multipart/form-data"';

How to customize PHP error message in WordPress

WordPress displays a default error message when it encounters a PHP error-

There has been a critical error on this website.

Learn more about troubleshooting WordPress.

Now this message is subtle, but still reveals 2 things-

  1. Your website has some error
  2. Your website is built on WordPress

Now second point is usually fine unless you specifically do not want WordPress name to appear anywhere on your website.

But the first point can become a security issue. Luckily there is a way to modify it.

This message is handled by WP_Fatal_Error_Handler class in wp-includes folder. Out of many methods, they give option of a drop-in file which can override the default php error message.

Just create a file with the name “php-error.php” and put it in the wp-content folder. Write the html code for PHP error message.

Now whenever WordPress will encounter a php error, it will execute this file and will display whatever you wrote in that file.


How to change custom post permalink in WordPress

I have struggled with this issue for years. I tried different ways but they always felt like hacks and gave inconsistent results most of the time. I also tried a popular plugin which broke my site.

Whenever you add a custom post type in WordPress through code, there is no way to select a permalink structure for it. By default, it’s permalink is of the format- post-type-slug/url-slug.

Though there are plugins to modify the permalink of a custom post type, surprisingly, I could not find solid way to do it through code. But finally, I found it.

In this post, I will show you that how you can modify the permalink of a custom post type with just a few lines of code.

For example, I have a custom post type named "event" and I want to add post id to the end of the permalink.

First, you need to change the rewrite rule for the custom post type. To do this, add following two lines just after the code where you registered your custom post type-

global $wp_rewrite;
$wp_rewrite->extra_permastructs['event']['struct'] = 'contest/%event%-%post_id%';

Now, use the filter hook to change the permalink like so-

add_filter( 'post_type_link', 'modify_permalink', 10, 2 );
function modify_permalink( $post_link, $post ) {
    if ( $post && 'event' === $post->post_type ) {
        return str_replace( '%post_id%', $post->ID, $post_link );
    return $post_link;

And that’s it. It was so simple. No need of any bloated plugin which may break your site and add needless overhead.

You can modify the above code to modify permalink based on your requirement.



WordPress: Missing canonical tags on archive pages

WordPress keeps surprising me even after more than a decade since I started using it.

Today I came to know that WordPress only generates canonical tags for singular pages (posts & pages). WordPress does not add canonical tags to archive pages including author page, post type archives, taxonomy archives etc.

So, how to add canonical tags to all archive pages? Use the wp_head action hook. Here is the script-

add_action( 'wp_head', 'add_canonical_url' );
function add_canonical_url() {
    if ( is_archive() ) {
        echo '<link rel="canonical" href="' . get_pagenum_link() . '" />';

404 pages getting redirected to home

Today, I wasted major part of my day trying to figure out why my subfolder based WordPress multisite install is redirecting all 404 errors to the site’s home page.

The problem turned out to be the constant “NOBLOGREDIRECT” which I defined in wp-config.php file. This constant ensures that in a multisite install, if anyone tries to access a non-existent site, they will be redirected to the signup page.

Now, this works great in case of subdomain based WordPress multisite setup. But, for subfolder based multisite setup, it actually starts redirecting all 404 pages to the signup page.

I recently converted my WordPress network from subdomain to subfolder structure and that’s why this setting started creating problem after that. If you have a subfolder based multisite install, you do not need NOBLOGREDIRECT.

Hope that helps.


Resolved: TWA App not working fullscreen when downloaded from Play Store

To hide the address bar in a TWA app, you must have setup and asset links file on our server with valid SHA certificate fingerprint. Sometimes the app works fine when we test it by directly installing through apk, but address bar is shown when we download the app from play store.

The reason for this is that when we upload an app to the play store, Google sign the APK with its own signing key which changes the SHA certificate fingerprint.

So, to solve this issue, we need to add both the SHA certificate fingerprints in the asset links file so that our app works fine whether we install it directly or through play store.


How to track if a web page is opened in TWA app

The Trusted Web Activity (TWA) in Chrome has made it so easy to package and publish any website as an app.

But the problem arises when we want to track when your website was opened inside the TWA app.

Usually we can easily do this in a webview app by appending a custom string to the user agent. But that option is not available in TWA.

However, we can easily track the entry into the app using a custom query string.

TWA apps allow us to set start_url of the app to include any custom query string. So, when the app will be launched, it will open the first page after appending the given query string. You can detect that to track the entry into the app.

But this does not work when app is directly opened because of the intent when user clicked on a link to the website. In that case, you can detect the HTTP referer which is in the format- android-app://<package name>/

So, to summarize, you just need to check both these conditions to identify if a user has opened a page in your app.

If you want to track each and every page view of the user inside the app, it is possible by persisting the state through the query string. I have written an article about persisting state through query string using Javascript- How to persist state through query string in url

But this query string method may or may not be reliable as TWA apps allows users to directly open links from inside the TWA app into the main Chrome app. So, query string will then be passed to the Chrome app and your analytics will be skewed. But in any case, you will get a fair idea about user activity inside your TWA app.


How to persist state through query string in url

In some cases when you do not have the option of cookies to manage state, query string can be a good option.

In this article, I am going to use some Javascript to persist state through a query string in the url. The Javascript code is added to head section of html when the desired query string is present in the url and then that Javascript will add that query string to all the internal urls on that page.

Here is the code-

const elements = document.querySelectorAll("a");
var url ='';
var theURL = '';
elements.forEach(function (element) {
    url = element.getAttribute('href');
    if ( url.startsWith('') ) {
        try {
            theURL = new URL(url);
            if ( theURL ) {
                let params = new URLSearchParams(;
                params.set( 'key', 'value' );
       = params;
                element.setAttribute('href', theURL);
        } catch(e) {

Now you can persist the query string throughout the user session. You can use the query string to identify the session details on the server.

Hope this helps.


Experience vs Manager

Being a manager is a huge responsibility. Even if only one employee is reporting to you, you have the responsibility to mentor them, guide them, support them and be vigilant if they are facing any work-related issue. I have seen many brilliant employees whose talents simply got wasted just because they had an incompetent manager.

Work experience does not mean that a person is automatically eligible to become a manager. There should be a serious process to identify the right people.

It is high time that the companies set some serious standards while hiring or promoting someone to the position of a manager. That would be a big differentiating factor between a good company and a GREAT company.


Rewrote Sahityapedia Android App in Flutter

Though I love coding, I am not a professional app developer. As an entrepreneur, I write code as means to an end. It saves cost which is essential for our bootstrapped startup.

After delaying for quite some time, I finally rewrote the entire Sahityapedia app in Flutter (the latest app framework by Google).

I wrote the earliest version of this app in Java (on Android Studio). Then Google moved from Java to Kotlin and I migrated the newer versions of this app to Kotlin. And then Google came up with a remarkable technology, Flutter.

Flutter made things easier, faster and most importantly, I could develop the app using the code editor of my choice, VS Code. Build times are shorter, hot reload is such a cool feature and development workflow feels much more logical.

So, with great excitement, presenting the latest version of Sahityapedia app. Download now

entrepreneur #technology #startup #coding #flutter #sahityapedia #android #google

Coding WordPress

Modify page title tag in WordPress

To change page title tag in WordPress, use the pre_get_document_title filter.

Most of the answers on web have mentioned the filter wp_title, but do not use it as wp_title function will be deprecated in future and wp_title hook will not work.

At present, wp_title filter does not work when modifying the title tag.


Prevent Form Resubmission on Page Refresh

We face a common issue on many websites that whenever a form submits to the same page, and then we refresh the page, the form data is submitted again. Sometimes the browser asks for confirmation, sometimes it does not. It becomes really frustrating if it causes an operation to happen twice.

To prevent this on our website, all we need to do is add a small Javascript code snippet, and the form resubmission issue will be gone.

Here is the code-

if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );


Prevent Memory Leak in WordPress

Recently I faced an issue of memory leak in one of my WordPress projects. I was running a function that was reading post meta and user metadata of thousands of objects. I thought reading data from MySQL is cheap in terms of processing power and memory, but it turned out it was causing my function to crash giving an out-of-memory error.

I made sure that there was no update being done to either post meta or user meta. It was only reading data through get_user_meta() and get_post_meta() functions. Then what was the reason for the memory leak?

It turned out that WordPress caches all the results when we read or write to post and user meta. That’s why, on iterating through thousands of posts and users, the result of each was being cached in memory, thus resulting in out-of-memory error.

To fix this issue, we need to prevent WordPress from caching this data. This can be done through wp_suspend_cache_addition(). This function disables the cache addition for the current page execution. This is how we need to call this function at the start of our script.

wp_suspend_cache_addition( true );

And that’s it. Memory usage dropped to less than 6 MB with peak memory usage coming down to mere 13 MB.

If you are facing a similar issue in WordPress, do remember this function. Also, while writing cron scripts or scripts to bulk update data like import/export scripts, it is better to call this function to ensure there is no out-of-memory issue.

Visual Studio Code

Fix Indentation Issue in Visual Studio Code

In Visual Studio Code, there is a setting to fix tab size to 4 spaces thus making it uniform for all files. It can be set to any value as per the user’s choice. This setting can be modified in settings-> editor.tabSize.

But whenever VS Code opens a file, it also checks for the default indentation in that file, and tab size can be overridden for that particular file. Many times this results in different tab sizes in different files thus making the code non-uniform.

Visual Studio Code Tab Size Settings

To fix this issue, there is another setting to override this per file indentation. It is editor.detectIndentation (Editor: Detect Indentation). Just turn it off and VS Code will start using universal tab size value instead of file-wise tab size assumptions.


Correct Way to Manage Title Tags in WordPress

The title tag is a very important feature of any website. It is displayed at the top of browser tabs and also read by search engines. So, it should be clear to read as well as SEO friendly.

WordPress is so powerful that it has customization options for almost anything in its structure. The title tag is no exception to this. However, while creating a WordPress theme, what is the best way to generate or modify title tags?

The earlier method was to include title tag in WordPress head using wp_title() function. But this method was supposed to be deprecated in WordPress version 4.4, but was kept for backward compatibility.

So, you should not use wp_title() as sooner or later it will be deprecated and removed.

Starting WordPress version 4.1, the recommended way to add title tag is to declare ‘title-tag’ compatibility in the theme itself. You can do this using the following code snippet.

add_theme_support( 'title-tag' );

This code will ensure that title tags are automatically added to the head of all HTML pages (posts, pages, archives, etc.). The format of the title tag is also automatically decided by WordPress. Here is the default structure of the title tags based on the current page-

Home Page- <Site Name><Separator><Site Tagline>

Posts- <Post Title><Separator><Site Name>

Pages- <Page Title><Separator><Site Name>

Archives- <Archive Title><Separator><Site Name>

And similarly all other WordPress generated pages will get automatic title tags.

The values of Site Name and Site Tagline are those which we define in Settings > General.

You can add theme support directly in the theme if you are creating one. Or, you can create a child theme and add this code in its functions.php file.

If you are declaring theme support in a plugin, then use the action hook after_setup_theme to ensure that theme support is added once all the plugins and themes are loaded.

If you are undecided about where to add your code, I have a very good article about where to add custom code in WordPress.

Now, this structure is perfect for most websites and good for SEO. However, in certain scenarios, we may need to modify the title tag.

To do that, WordPress has a filter hook document_title_parts using which we can hook into the title tag generating function and modify it dynamically.

Following is an example snippet of code to do that-

add_filter( 'document_title_parts', 'modify_title_on_home_page' );
function modify_title_on_home_page( $title_array ) {
    $title_array ['title'] = 'Modified Page Title';

This code modifies the page title on the home page of a WordPress website.

The document_title_parts filter passes an array containing the title of the current page, page number (in case of paginated pages), site tagline, and site title/name which we can modify and return back.

And that’s it. You are now ready to utilize the power of WordPress to manage the title tags efficiently.


Resolved: Graphics Processor Not Detected in Photoshop

I installed a new version of Photoshop and, suddenly, it was chaos all around. Photoshop started getting crashed even if there was a small graphic-intensive operation and closed automatically without even giving me a chance to save my work.

On restarting the application, it was throwing an error message that it disabled enhancements which use the graphics hardware due to some issue with the graphic driver. In Preference>Performance settings, I could see that the Graphics card was not detected and it was turned off, but the software would keep crashing again and again.

I checked the Windows device manager to update the driver software, and it showed that I already had the latest driver installed.

On some user forums, I found that it was a known issue in the latest update of Photoshop, and installing a previous release would solve the issue. I uninstalled the current version and installed an earlier release. But it was futile, the problem persisted.

Then I thought of checking with the graphics card support. I have a decent 2 GB AMD Radeon card which is good enough for moderate Photoshop usage. AMD has a very simple driver update system where their tool will automatically identify the graphics card installed on your system and will update it.

Once the update was done, it asked for a restart. And, problem solved.

Photoshop was now able to detect my graphics card and there were no more crashes.

If you are facing a similar issue, try updating the graphics card drivers from the manufacturer’s website and it should solve the problem.


Why some recipients are not getting your emails?

If you are using email on your custom domain using some email service like Google Workplace or Zoho Mail, you have to do certain configurations to ensure that your emails reach the inboxes of their recipients. Missing emails can be disastrous for a business.

The most important configurations are SPF and DKIM in your DNS, which authenticate your outgoing emails so that recipient servers do not mark them as phishing or spam emails.

All email providers provide the settings for SPF and DKIM authentication. You have to add their provided records to your DNS settings.

Please note that there can be only one SPF record. In case you are configuring your domain to send emails through multiple providers, add their data in the same SPF record.


Decode a PHP encoded string url in Javascript

Sometimes you may face a problem when you have to decode a string with Javascript which was originally url encoded with PHP. This can be an API response or cookie set by PHP setcookie function.

A simple way to do this is through decodeURIComponent function in Javascript. But it leaves the "+" signs in the string. For that we can use replace function to replace all the "+" signs with space. Remember, simply using replace function sign will only replace the first occurrence in the string. To replace all the occurrences, use the regex version with g flag.

Here is the code for your reference-

var decodedString = decodeURIComponent( encodedString ).replace( /+/g, ' ' );

Here encodedString is the url encoded string received from PHP.

Its that simple!

If you have any other method, do share in comments.

Happy coding!


How to change Post Type in WordPress

While working with custom post types in WordPress, many times we come across the need to change the post type of a particular post.

It can be done either directly through code or using a plugin.

Without Plugin

This can be done using WordPress functions- wp_update_post or set_post_type.

wp_update_post can be used when updating multiple fields of a post.

In case, only post type has to be changed, then set_post_type is sufficient.

Just use set_post_type along with the post id and you are done.

If you are unsure about where to add this code, take a look at Where to add custom code in WordPress.

Using Plugin

If you occasionally want to switch posts and do not want to fiddle with the code, there is a good plugin for this which easily performs this task- Post Type Switcher.

Simply install and activate a plugin. It will add the option to change post types in the admin menu.

A good thing about this plugin is that it allows to change the post type of multiple posts in bulk by utilizing the "bulk edit" feature in WordPress.

So, now you know how to change post type with or without a plugin. Which one do you like better? Do let me know in comments section.


How to view and modify WordPress rewrite rules

If you encounter a sudden unexpected delay in page load which was previously working fine, a good place to check is the rewrite rules.

In my case, it seems there was some issue in the currently generated rules which was causing this delay.

A simple visit to Settings->Permalink automatically flushed and regenerated all the rewrite rules and it resolved the issue for me. The page is again loading as fast as it did earlier.

However, if you want to check the current rewrite rules, there is a simple code to check that.

Add the below code to your plugin or theme.

// Filter to display rewrite rules on permalink settings page when debugging 
add_filter( 'rewrite_rules_array', 'show_all_the_rewrite_rules' );
function show_all_the_rewrite_rules( $rules ) {
    echo nl2br( var_export( $rules, true ) );

Now this hook is only called on Permalink Settings page. So, visit that page and you will be able to see all the current rewrite rules of your website.

You can also remove rules if they are not required, based on regex as shown in the following code.

// Filter hook to remove unwanted rewrite rules, will only run when **setting->permalink** page is opened
function remove_rewrite_rules( $rules ) {
    foreach ( $rules as $rule => $rewrite ) {
        if ( preg_match( '/(feed|rss|atom|embed|attachment|trackback|year|date|search/)/', $rule ) ) {
            unset( $rules[$rule] );
return $rules;


You can define any pattern in the preg_match function to remove the unwanted rewrite rules.

Hope this helps.