Author: Abhineet Mittal

  • WP_Query by URL for Infinite Scroll in WordPress

    I was trying to create an infinite scroll in WordPress. All I wanted was to parse the next page url without making any changes to the code so that the code becomes interoperable with the pagination templates.

    To achieve that, instead of passing custom query parameters to the API, I decided to parse the next page url to run WP_Query without mentioning any additional parameters.

    Steps were:

    1. Get the next page url
    2. Parse it to get query parameters of next page
    3. Run WP_Query on that and get the posts of next page

    Though I spent hours on this, it turned out to be rather simple.

    // Get the url of the next page
    $next_page_url = $args[ 'next_page_url' ] ?? $_SERVER['REQUEST_URI'];
    
    // Save the next page url in the current global server variable array
    $_SERVER['REQUEST_URI'] = $current_page_url;
    
    // Rebuild the global $_GET variable to include the new query string parameters
    parse_str( parse_url( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ?? '', PHP_URL_QUERY ), $_GET );
    
    // Run the wp_query to get the posts of next page
    $wp->parse_request();
    $wp->query_posts();
    $all_posts = $wp_query->posts;

    Just replace your pagination links with an element which passes the next page url to the API when it becomes visible. And you can get the posts HTML from the API.

    And that’s it. Your infinite scroll is ready.

    References:

    1. https://medium.com/@harryhorton/query-wp-rest-api-using-any-permalink-url-f5e4e4dd36b7
  • MySQL Disk Size Issue

    I was facing a strange issue on one of my servers. Storage was getting full even when I did not upload any extra files.

    Turned out it was a MySQL logging issue and got resolved only when I disabled logging.

    References:

    1. https://www.christophe-casalegno.com/mysql-how-to-purge-binary-logs-when-you-have-no-space-left-on-device/

    2. https://www.alittleofboth.com/2020/04/droplet-out-of-disk-space/

    3. https://www.digitalocean.com/community/questions/where-did-my-disc-space-go

  • JPG Image Compression

    When you upload images to Facebook or Whatsapp, you must have noticed a reduction in size and quality of the image. Though the image looks fine on most devices, its size get reduced by over 95%. The reason is compression.

    It is recommended to compress the images before uploading them to your blog or website. This helps in reducing the bandwidth usage and increase in site speed.

    For JPG, my recommended compression settings are 60%.

    I noticed that it is best for images being hosted on websites and there is no visible image degradation.

    There is a good JPG compression website- https://compressjpeg.com/.

    Though this site is good and easy to use, by default it compresses images at different compression ratios for every image. Though you can customize it by clicking the thumbnail of each image, it is not so convenient.

    My recommended image compression website is https://bulkresizephotos.com

    You can compress images in bulk with the same settings.

    Here is the url with predefined setting of 60% compression ratio- https://bulkresizephotos.com/en?preset=true&quality=0.6&value=100

  • Why click event not working on SVG

    I created a simple menu with SVG icons and to my surprise, clicking on the icon was not taking me to the linked url.

    It turned out that as SVGs are independent HTML objects, the target element is actually nested path. So, it does not match with the clicked element and thus click event listeners does not work on it.

    Similarly, if you add others event listeners to the parent element of the SVG’s, it does not work.

    There are multiple ways to fix this-

    1. Disable click on SVG elements by adding the CSS- pointer-events: none;

    2. Add event listener to the path element of SVG.

    Problem solved.

    References:

    1. https://gomakethings.com/detecting-click-events-on-svgs-with-vanilla-js-event-delegation/
  • Add event listener on SVG element

    I was facing problem while adding event listener to an svg element.

    Then I added event listeners to both svg and path tags, and it worked.

  • When my boss told me not to prepare for CAT

    "Don’t prepare for CAT if you want to succeed here."

    Those were the words of the manager of my first project.

    I was a fresher B. Tech graduate in my first job and had joined my first project along with a few others. Our manager called us into his cabin for a casual introduction session.

    His first words were, "Do not prepare for CAT or any government job exam if you want to succeed here. Stay here for a long time, and only then you will grow in your career." He also individually asked everyone if we were preparing for some exam and made sure we all said no.

    That was his way of imposing employee retention by forcing people not to pursue better career opportunities. It was clear that if I shared my MBA plans with him, I was not getting any promotion no matter how well I did my job.

    But did it stop me from pursuing my dream of getting into an IIM? No. But it did stop me from sharing about my CAT preparation with him.

    I was committed to my work and did the best I could. At the same time, I spent my weekends preparing for CAT. It was very hectic, but somehow I managed.

    After a year and a half, I got a promotion in my job and, at the same time, secured admission offers from multiple IIMs and other top MBA colleges in India.

    I did not want to hide my preparation, but If I had told him, I could not get that promotion, even though I deserved that. That promotion was crucial for my career, in case, I could not pursue MBA.

    You cannot retain employees by forcing them. Why not give them such a great environment that leaving becomes impossible.

    And even if they leave, they would be willing to come back whenever possible. Wouldn’t it be great!

    #work #career #mba #iim
  • Will electric cars ever succeed?

    Many people think that electric cars cannot replace petrol cars due to high charging time and low battery capacity. Range anxiety is a big issue with electric cars today.

    This reminds me of the range anxiety of smartphone batteries we had just a few years ago. While traveling, we were always worried about whether our smartphone battery would discharge before we reached home or if we would find a charging slot on the way.

    Even the highest-priced smartphones did not have the battery capacity offered by the lowest-priced smartphones of today. But everything changed as it became a differentiating factor for the mobile phone manufacturers.

    Suddenly the technology started to evolve. High-capacity batteries became financially viable. And the massive scale achieved due to high demand reinforced the innovation.

    It started with the emergence of power banks which proved very useful for some time. But they were a part of the evolution soon replaced by even better technology.

    As a result of that demand-led innovation, today, in just a few years, we have 120-watt mobile chargers compared to 5-watt chargers just a few years back. This has drastically reduced the charging time.

    And the battery capacity has increased enough to ensure that our mobile phones work for days on a single charge, even with heavy usage.

    We do not worry about battery capacity of mobile phones anymore. The range anxiety is gone as if it was never an issue.

    I know it is not exactly an apples-to-apples comparison, but it does give us a good perspective on the possible future of electric cars. It may seem far-fetched and improbable today, but we never know if it is just the beginning of another era of demand-led innovation.

    #innovation #electriccars #technology
  • 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.

  • 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

    www.sahityapedia.com

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

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