Blog

  • Startups going back to the old models

    Life comes full circle!

    Big EdTech startups who created so much hype about online education are returning to the offline coaching center model.

    Similarly, we are returning to the auto-rickshaws from the golden days of on-demand app-based cab services.

    Raising and spending investors’ money may be necessary for fast-paced growth, but it is equally important to focus on the quality and feasibility of the actual product.

    #startups
  • Beauty of randomness in life

    I do not mean to offend anyone but lately I have observed a peculiar trend in my LinkedIn feed.

    A lot of people are posting random stories about small instances from their daily life and trying to create analogies with something meaningful to bring out great learnings out of that.

    To be honest, sometimes these analogies make sense, but most of the time they seem too much forced trying to find meaning out of everything.

    Somethings in life are random and randomness has its own beauty.

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

    Reference:

    1. https://wordpress.stackexchange.com/questions/369343/put-post-id-on-the-custom-post-type-url
  • 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('https://example.com') ) {
            try {
                theURL = new URL(url);
                if ( theURL ) {
                    let params = new URLSearchParams(theURL.search);
                    params.set( 'key', 'value' );
                    theURL.search = 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.