Categories
WordPress

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"';
}
Categories
WordPress

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.

Categories
WordPress

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.

Reference:

  1. https://wordpress.stackexchange.com/questions/369343/put-post-id-on-the-custom-post-type-url
Categories
WordPress

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() . '" />';
    }
}
Categories
WordPress

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.

Categories
Coding

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-

<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>

Categories
WordPress

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.

Categories
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.

Categories
WordPress

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.

Categories
Coding

How to count words in Unicode string using PHP

How to count words in Unicode string using PHP?

How to count words in Unicode string using PHP? This sounds too easy. After all, PHP has so many string manipulation functions. To count words, we can simply use str_word_count and we are good to go. But there is a problem.

While this function works fine for English strings, developers find this function unpredictable as sometimes it also counts some symbols. But the real problem is that this function doesn’t work accurately for Unicode strings.

I faced this problem while working on one of my websites which is entirely in Hindi. When I searched, I was surprised to find that there is no straight forward solution or function to do this. There should be a standard function which should work for all languages, but the variation in structure of languages does not allow this.

A new function to count words in Unicode string using PHP

So, I wrote a small function which can be used anywhere to count the words in a Unicode string and works for a large number of popular languages. It first removes all the punctuation marks & digits to ensure that we do not count them as words. Then it replaces all white space blocks, including tab, new line etc., by a single space character.

Now all words of the string are separated by a single space separator. We can simply split/explode them into an array and count its elements to find the word count.

You can see the code below.

Just copy this code to your PHP project and start using this function to count words in any Unicode string.

And this is equally good for English strings as well. I found it more accurate than str_word_count.

Remember, it will work accurately for all those strings where spaces are used for word separation. But it may not work accurately for languages like Mandarin, where words are not separated by spaces.

Please do let me know how you like this article "How to count words in Unicode string using PHP" through comments section below.