Tag: PHP

  • How to detect English/ASCII string in PHP

    There is no direct function for this in my knowledge. But it can be done easily like so.

    “`php
    if ( mb_strlen( $string, ‘ASCII’ ) === mb_strlen( $string, ‘utf-8’ ) ) {
    return true;
    }
    “`

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

  • 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 ) );
        die;
    }

    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.

  • 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?

    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.