Categories
WordPress

WordPress adding slashes in POST requests

WordPress adds slashes before quotes even if we do not want to use magic quotes.

To solve this problem, you can use either of the following two functions on the values returned from POST requests-

  • wp_unslash
  • stripslashes_deep

References:

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
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
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
WordPress

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.

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.