<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ahmad Tahir on Medium]]></title>
        <description><![CDATA[Stories by Ahmad Tahir on Medium]]></description>
        <link>https://medium.com/@ahmadthedev?source=rss-3506429a0f05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zrvzjfM2Kj-DIf_UdDKzHg.jpeg</url>
            <title>Stories by Ahmad Tahir on Medium</title>
            <link>https://medium.com/@ahmadthedev?source=rss-3506429a0f05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:36:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmadthedev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Enhance Drag-and-Drop Sortable Rows in WordPress: A Comprehensive Guide]]></title>
            <link>https://ahmadthedev.medium.com/enhance-drag-and-drop-sortable-rows-in-wordpress-a-comprehensive-guide-0dab584e75a3?source=rss-3506429a0f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dab584e75a3</guid>
            <category><![CDATA[wordpress-development]]></category>
            <category><![CDATA[sortablejs]]></category>
            <category><![CDATA[jquery-ui]]></category>
            <category><![CDATA[tech-tutorials]]></category>
            <category><![CDATA[drag-and-drop]]></category>
            <dc:creator><![CDATA[Ahmad Tahir]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 12:04:44 GMT</pubDate>
            <atom:updated>2023-11-25T12:58:48.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TMf2fweo406UbO0G.png" /></figure><h3>Introduction:</h3><p>As WordPress developers, we often find ourselves in situations where we need to create custom plugins to cater to the unique requirements of our clients. Recently, I encountered a challenge while developing a WordPress plugin for a client who required a user-friendly way to manage data through sortable rows with drag-and-drop functionality. Surprisingly, the resources available on this topic were limited, and I faced difficulties finding a comprehensive guide.</p><p>In an effort to bridge this gap and assist fellow developers facing similar challenges, I’ve decided to share my insights and the solution I crafted for implementing sortable rows with drag-and-drop in WordPress. This article serves as a guide for those seeking a clear and detailed explanation of the process. So, whether you’re developing a custom plugin or simply interested in enhancing your WordPress skills, this article is tailored for you. Let’s dive into the world of sortable tables and make the data management experience smoother for both developers and end-users.</p><h3>Step 1: Enqueue jQuery UI Sortable Script</h3><p>Before we dive into the implementation, make sure to enqueue the jQuery UI Sortable script. This script provides the functionality needed for sorting elements with drag-and-drop.</p><pre>// Enqueue Script<br>function enqueue_sortable_script() {<br>    wp_enqueue_script(&#39;jquery-ui-sortable&#39;);<br>}<br><br>// Hook to admin_enqueue_scripts<br>add_action(&#39;admin_enqueue_scripts&#39;, &#39;enqueue_sortable_script&#39;);</pre><h3>Step 2: HTML Structure</h3><p>The HTML structure consists of a table with sortable rows. Each row contains input fields and a draggable handle.</p><pre>&lt;table cellspacing=&quot;0&quot;&gt;<br>    &lt;tbody class=&quot;sortable-table-body&quot;&gt;<br>        &lt;!-- Row 1 --&gt;<br>        &lt;tr class=&quot;custom-fields-row draggable-row&quot; data-order=&quot;1&quot;&gt;<br>            &lt;!-- ... (input fields) --&gt;<br>            &lt;td class=&quot;draggable-handle&quot;&gt;<br>                &lt;!-- Drag Handle Icon --&gt;<br>            &lt;/td&gt;<br>        &lt;/tr&gt;<br>        &lt;!-- Row 2 --&gt;<br>        &lt;tr class=&quot;custom-fields-row draggable-row&quot; data-order=&quot;2&quot;&gt;<br>            &lt;!-- ... (input fields) --&gt;<br>            &lt;td class=&quot;draggable-handle&quot;&gt;<br>                &lt;!-- Drag Handle Icon --&gt;<br>            &lt;/td&gt;<br>        &lt;/tr&gt;<br>    &lt;/tbody&gt;<br>&lt;/table&gt;</pre><h3>Step 3: jQuery Implementation</h3><p>Now, let’s implement the jQuery code to make the rows sortable with drag-and-drop functionality.</p><pre>jQuery(document).ready(function ($) {<br>    // Sortable Table Rows<br>    $(&#39;.sortable-table-body&#39;).each(function () {<br>        $(this).sortable({<br>            items: &#39;.draggable-row&#39;,<br>            connectWith: &#39;.sortable-table-body&#39;,<br>            handle: &#39;.draggable-handle&#39;,<br>            update: function (event, ui) {<br>                updateOrder($(this));<br>            }<br>        });<br>    });<br><br>    // Set cursor style when dragging starts<br>    $(&quot;.draggable-row&quot;).mousedown(function () {<br>        $(this).css(&quot;cursor&quot;, &quot;grabbing&quot;);<br>    });<br><br>    // Set cursor style back to default when dragging stops<br>    $(&quot;.draggable-row&quot;).mouseup(function () {<br>        $(this).css(&quot;cursor&quot;, &quot;grab&quot;);<br>    });<br><br>    // Function to update the data-order attribute based on the new order<br>    function updateOrder($table) {<br>        $table.find(&quot;.draggable-row&quot;).each(function (index) {<br>            $(this).attr(&quot;data-order&quot;, index + 1);<br>        });<br>    }<br>});</pre><p>This jQuery code initializes the sortable functionality on the specified elements and updates the data-order attribute of each row based on the new order.</p><h3>Conclusion:</h3><p>With this implementation, you’ve successfully added drag-and-drop functionality to sortable rows in a WordPress table. This feature can be especially useful for managing custom data in a user-friendly way within your plugin. Feel free to customize the HTML structure and styling to match your specific requirements.</p><p><a href="https://www.ahmadthedev.com/resume/">Click here</a> to read about me.</p><p><em>Originally published at </em><a href="https://www.ahmadthedev.com/wordpress/drag-and-drop-rows-in-wordpress-using-jquery/"><em>https://www.ahmadthedev.com</em></a><em> on November 25, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dab584e75a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost SEO and User Experience with a Custom RankMath Sitemap Pagination]]></title>
            <link>https://ahmadthedev.medium.com/boost-seo-and-user-experience-with-a-custom-rankmath-sitemap-pagination-6220c33cef8d?source=rss-3506429a0f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/6220c33cef8d</guid>
            <category><![CDATA[sitemap]]></category>
            <category><![CDATA[wordpress-development]]></category>
            <category><![CDATA[rank-math]]></category>
            <dc:creator><![CDATA[Ahmad Tahir]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 15:04:15 GMT</pubDate>
            <atom:updated>2023-11-25T12:53:21.304Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a custom sitemap with pagination for <a href="https://wordpress.org/plugins/seo-by-rank-math/">Rank Math SEO plugin</a> is a powerful feature for SEO optimization. With a custom sitemap, you can control how your content is organized and indexed by search engines. In this article, we will explore how to create a custom sitemap using Rank Math SEO and add pagination to it.</p><h3>History: The Need for a Custom Sitemap</h3><p>As you may already know, search engines like Google, Bing, and others rely on sitemaps to understand the structure and content of a website. These sitemaps serve as a roadmap, guiding search engine bots through the intricate web of your site’s pages and content. Typically, sitemaps are automatically generated by SEO plugins like Rank Math. However, here’s where our journey takes an interesting turn.</p><p>The default Rank Math sitemap, while a valuable tool for most websites, faced a monumental challenge when dealing with a directory site of this magnitude. You see, there’s a limitation when it comes to sitemaps: they are limited to 50,000 URLs per sitemap. While this is usually more than enough for most websites, it’s a mere fraction of what was needed for a directory site with 90 million records.</p><p>In practice, this limitation meant that the default Rank Math sitemap encountered significant roadblocks. It struggled to handle the long list of URLs that needed to be included, and this struggle resulted in white screen errors, effectively rendering the sitemap unusable. A solution was urgently needed to overcome this obstacle and make it possible for the directory website to effectively communicate with search engines. And so, the solution was born out of necessity. The strategy involved bypassing the default sitemap generation process and devising a direct SQL query to fetch the results from the database. But the journey didn’t end there. To work within the confines of the 50,000 URL limitation, a custom sitemap had to be created with pagination, ensuring that the directory’s vast database of information could be neatly organized into digestible portions for search engines to consume.</p><p>The creation of this custom sitemap marked a pivotal moment in optimizing the indexing of the directory website’s content. It not only solved the technical challenges posed by the site’s immense size but also showcased the adaptability and innovation of SEO experts in navigating the ever-changing landscape of digital marketing.</p><h3>Introduction</h3><p>Before we dive into the code, let’s briefly understand what we’re trying to achieve. We want to create a custom sitemap for a custom post type called “publicdevs.” This sitemap will be divided into multiple pages with pagination, allowing search engines to index all the content efficiently.</p><h3>Step 1: Register the Sitemap Provider</h3><p>The first step is to register your custom sitemap provider. You will do this in your theme’s functions.php file. This provider will be responsible for generating the sitemap for your &quot;publicdevs&quot; post type.</p><pre>// functions.php<br>add_filter(&#39;rank_math/sitemap/providers&#39;, function($external_providers) { <br>    $external_providers[&#39;publicdevs&#39;] = new \RankMath\Sitemap\Providers\PD_Sitemap();<br>    return $external_providers;<br>});</pre><p>In the code above, we are using the add_filter function to hook into the rank_math/sitemap/providers filter and add our custom sitemap provider, which is an instance of the PD_Sitemap class.</p><p>As, we have create separate file, you also need to include this in your theme:</p><pre>require_once &quot;inc/pd-sitemap.php&quot;;</pre><h3>Step 2: Create the Sitemap Provider</h3><p>Next, you need to create the PD_Sitemap class, which implements the Provider interface. This class will handle the generation of the sitemap.</p><pre>namespace RankMath\Sitemap\Providers;<br><br>use RankMath\Sitemap\Router;<br><br>class PD_Sitemap implements Provider {<br><br>    // Your code here...<br><br>}</pre><p>In the PD_Sitemap class, you will implement several methods that define how your custom sitemap will work. Let&#39;s break down the key methods:</p><h3>1. total_ps_count():</h3><p>This method calculates the total number of “publicdevs” posts that need to be included in the sitemap.</p><pre>public function total_ps_count() {<br>    global $wpdb;<br>    return (int) $wpdb-&gt;get_var(&quot;SELECT COUNT({$wpdb-&gt;posts}.ID) FROM {$wpdb-&gt;posts} WHERE post_type = &#39;publicdevs&#39; AND post_status = &#39;publish&#39;&quot;);<br>}</pre><h3>2. handles_type($type):</h3><p>This method checks if the sitemap provider should handle a particular post type. In this case, it checks if the post type is “publicdevs.”</p><pre>public function handles_type( $type ) {<br>    return &#39;publicdevs&#39; === $type;<br>}</pre><h3>3. get_index_links($max_entries):</h3><p>This method generates the index links for your sitemap, including pagination. It calculates the number of pages needed and creates links to those pages. The last modified date is set for all index links.</p><pre>public function get_index_links( $max_entries ) {<br>    $index = [];<br>    $total_count = $this-&gt;total_ps_count();<br><br>    $max_pages = 1;<br>    if ( $total_count &gt; $max_entries ) {<br>        $max_pages = (int) ceil( $total_count / $max_entries );<br>    }<br><br>    for ( $page_counter = 0; $page_counter &lt; $max_pages; $page_counter++ ) {<br>        $current_page = ( $max_pages &gt; 1 ) ? ( $page_counter + 1 ) : &#39;&#39;;<br>        $index[] = [<br>            &#39;loc&#39;     =&gt; Router::get_base_url(https://medium.com/&#39;pd-sitemap&#39;%20.%20$current_page%20.%20&#39;.xml&#39;),<br>            &#39;lastmod&#39; =&gt; &#39;2023-05-03 05:33 +00:00&#39;<br>        ];<br>    }<br><br>    return $index;<br>}</pre><h3>4. get_sitemap_links($type, $max_entries, $current_page):</h3><p>This method generates the actual sitemap links. It retrieves the necessary data for your “publicdevs” posts and formats the links accordingly. Pagination is applied here, limiting the number of links on each page.</p><pre>public function get_sitemap_links( $type, $max_entries, $current_page ) {<br>    global $wpdb;<br><br>    $links     = [];<br><br>    $results = $wpdb-&gt;get_results(<br>        &quot;SELECT P.post_name, P.post_date, P.post_modified, T.slug FROM `wp_posts` AS P INNER JOIN `wp_term_relationships` AS TR ON P.ID = TR.object_id INNER JOIN `wp_term_taxonomy` AS TT ON TT.term_taxonomy_id = TR.term_taxonomy_id INNER JOIN `wp_terms` AS T ON T.term_id = TT.term_id WHERE P.post_type = &#39;publicdevs&#39; AND P.post_status = &#39;publish&#39; AND TT.taxonomy = &#39;state&#39; ORDER BY P.ID DESC&quot;,<br>        ARRAY_A<br>    );<br><br>    foreach($results as $single_res) {<br>        $link = sprintf(<br>            &#39;https://yourwebsite.com/%s/%s/&#39;,<br>            $single_res[&#39;slug&#39;],<br>            $single_res[&#39;post_name&#39;]<br>        );<br>        $datetime = isset($single_res[&#39;post_modified&#39;]) ? $single_res[&#39;post_modified&#39;] : $single_res[&#39;post_date&#39;];<br>        $links[] = [<br>            &#39;loc&#39; =&gt; $link,<br>            &#39;mod&#39; =&gt; sprintf(&#39;%s&#39;, $datetime)<br>        ];<br>    }<br><br>    $links = array_slice(<br>        $links,<br>        (($current_page - 1) * $max_entries),<br>        $max_entries<br>    );<br><br>    return $links;<br>}</pre><h3>Step 3: Configure Your Sitemap in Rank Math</h3><p>After creating the custom sitemap provider, you need to configure it in the Rank Math plugin settings.</p><ol><li>In your WordPress dashboard, go to “Rank Math” and click on “Sitemap Settings.”</li><li>You should see a section for “publicdevs” (or your custom post type). Make sure it’s enabled.</li><li>Save your settings.</li></ol><h3>Step 4: Verify Your Sitemap</h3><p>To make sure everything is working as expected, you can view your custom sitemap in a web browser by navigating to the following URL:</p><pre>https://yourwebsite.com/sitemap_index.xml</pre><p>Replace “yourwebsite.com” with your actual website domain. You should see your custom sitemap with pagination links.</p><h3>Conclusion</h3><p>Creating a <a href="https://www.ahmadthedev.com/tag/sitemap/">custom sitemap</a> with pagination in Rank Math SEO is a valuable tool for optimizing the indexing of your content. By implementing a custom sitemap provider and configuring it in Rank Math, you can have better control over how your “publicdevs” posts are indexed and organized. This can lead to improved SEO and better visibility in search engine results.</p><p><a href="https://www.ahmadthedev.com/resume/">Click here</a> to read about me.</p><p><em>Originally published at </em><a href="https://www.ahmadthedev.com/wordpress/custom-rankmath-sitemap-with-pagination/"><em>https://www.ahmadthedev.com</em></a><em> on November 23, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6220c33cef8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make Images Retina-Ready for your WordPress Theme without any plugin?]]></title>
            <link>https://ahmadthedev.medium.com/how-to-make-images-retina-ready-for-your-wordpress-theme-without-any-plugin-dbf9b063b3e4?source=rss-3506429a0f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbf9b063b3e4</guid>
            <category><![CDATA[website-performance]]></category>
            <category><![CDATA[code-snippet]]></category>
            <category><![CDATA[retina-images]]></category>
            <category><![CDATA[wordpress]]></category>
            <dc:creator><![CDATA[Ahmad Tahir]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 16:11:42 GMT</pubDate>
            <atom:updated>2023-01-12T11:56:04.998Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s first understand why its important for your website to retina-ready nowadays. With the rise of very high density “super retina” displays in the newest high-end devices, capping image fidelity to 2x leads to a big improvement in terms of rendering speed, and no perceivable quality loss for your users.</p><p>So the first thing we started doing was to provide both a standard image and an image optimized for Retina displays, using the srcset attribute and the x descriptor. Like this:</p><pre>&lt;img<br>    src=&quot;image_1x.jpg&quot;<br>    srcset=&quot;<br>        image_1x.jpg 1x,<br>        image_2x.jpg 2x,<br>        image_3x.jpg 3x<br>    &quot;<br>    alt=&quot;Test Image for Retina&quot;<br>    width=&quot;1920&quot;<br>    height=&quot;600&quot;<br>/&gt;</pre><p>See the 1x and 2x? This helps the browser identify which image is the regular version and which is the Retina version. If the user has a Retina device, the browser wills serve the 2x image. If they don&#39;t, it&#39;ll serve the 1x version. And if the browser doesn&#39;t support srcset, then it&#39;ll use the one in the src attribute.</p><p>Let’s start adding code to make our website retina-ready.</p><h3>Step 1: Define Image Sizes</h3><p>We’re going to use add_image_size wordpress function to define sizes and hook it with after_setup_theme.</p><pre>add_action( &#39;after_setup_theme&#39;, function(){<br><br> $image_sizes = [<br>  [<br>   &#39;size&#39;  =&gt; &#39;thumbnail&#39;,<br>   &#39;width&#39;  =&gt; 150,<br>   &#39;height&#39; =&gt; 150<br>  ],<br>  [<br>   &#39;size&#39;  =&gt; &#39;medium&#39;,<br>   &#39;width&#39;  =&gt; 300,<br>   &#39;height&#39; =&gt; 300<br>  ],<br>  [<br>   &#39;size&#39;  =&gt; &#39;medium_large&#39;,<br>   &#39;width&#39;  =&gt; 768,<br>   &#39;height&#39; =&gt; 0<br>  ],<br>  [<br>   &#39;size&#39;  =&gt; &#39;large&#39;,<br>   &#39;width&#39;  =&gt; 1024,<br>   &#39;height&#39; =&gt; 1024<br>  ]<br> ];<br><br> foreach( $image_sizes as $sizes ) {<br>  add_image_size( sprintf(&#39;%s&#39;, $sizes[&#39;size&#39;]), $sizes[&#39;width&#39;], $sizes[&#39;height&#39;] );<br>  add_image_size( sprintf(&#39;%s@%dx&#39;, $sizes[&#39;size&#39;], 2), $sizes[&#39;width&#39;]*2, $sizes[&#39;height&#39;]*2 );<br>  add_image_size( sprintf(&#39;%s@%dx&#39;, $sizes[&#39;size&#39;], 3), $sizes[&#39;width&#39;]*3, $sizes[&#39;height&#39;]*3 );<br> }<br><br>} );</pre><p>The above code adding image sizes in following order:</p><pre>add_image_size( &#39;thumbnail&#39;, 150, 150 );<br>add_image_size( &#39;thumbnail@2x&#39;, 300, 300 );<br>add_image_size( &#39;thumbnail@3x&#39;, 450, 450 );<br>...</pre><p>If your images already uploaded then make sure to <a href="https://wordpress.org/plugins/regenerate-thumbnails/">regenerate</a> them.</p><h3>Step 2: Insert Retina Sizes in SRCSET</h3><p>We’re going to use wp_get_attachment_image_attributes filter hook, this hook provide us 3 image parameters, array of attribute values $attr, attachment $attachment, and requested size $size.</p><p>You can ready more about it in <a href="https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_attributes/">developer resources</a>.</p><pre>add_filter( &#39;wp_get_attachment_image_attributes&#39;, function( $attr, $attachment, $size ) {<br><br> // Code<br><br> return $attr;<br>}, 10, 3 );</pre><p>Here is complete code:</p><pre>add_filter( &#39;wp_get_attachment_image_attributes&#39;, function( $attr, $attachment, $size ) {<br><br> $img_id   = $attachment-&gt;ID;<br> $requested_image = wp_get_attachment_image_src( $img_id, $size );<br> $res   = [&#39;2x&#39;, &#39;3x&#39;];<br> $srcset   = [];<br> $size_args        = [<br>  &#39;width&#39;  =&gt; $requested_image[1],<br>  &#39;height&#39; =&gt; $requested_image[2]<br> ];<br><br> $srcset[] = $requested_image[0] .&#39; 1x&#39;;<br> foreach($res as $r) {<br>  $r_img = $size .&#39;@&#39;. $r;<br>  $r_src = wp_get_attachment_image_src($img_id, $r_img);<br>  if($r_src[3] == true) {<br>   $srcset[] = esc_url(https://medium.com/$r_src[0]) .&#39; &#39;. $r;<br>  }<br> }<br><br> $attr[&#39;src&#39;]    = $requested_image[0];<br> $attr[&#39;srcset&#39;] = implode( &#39;, &#39;, $srcset );<br> unset($attr[&#39;sizes&#39;]);<br><br> return $attr;<br>}, 10, 3 );</pre><p>First we define resolutions 2x, 3x in $res variable, then in loop we checked if image size exists $r_src = wp_get_attachment_image_src($img_id, $r_img); if it&#39;s true save them in $srcset[].</p><p>After that we used PHP function to convert array into string, then save the $srcset in $attr[&#39;srcset&#39;].</p><p>Final result will be looks like this:</p><p>Let me know if you have any trouble implementing this code in comment section.</p><p>Have fun coding!</p><p><em>Originally published at </em><a href="https://www.ahmadthedev.com/wordpress/retina-ready-images-without-plugin/"><em>https://www.ahmadthedev.com</em></a><em> on January 11, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbf9b063b3e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Lazy Load images in WordPress without Plugin?]]></title>
            <link>https://ahmadthedev.medium.com/how-to-lazy-load-images-in-wordpress-without-plugin-80b14e4787b4?source=rss-3506429a0f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/80b14e4787b4</guid>
            <category><![CDATA[snippet]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[website-performance]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <dc:creator><![CDATA[Ahmad Tahir]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 18:19:28 GMT</pubDate>
            <atom:updated>2023-01-12T11:50:59.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xSl1dQGFBb_0YSIQ.png" /></figure><p>Lazy-load is a way to prevent images from loading before scroll. There are many plugins that help you with this, some themes even have a built-in lazy-load function.</p><p>Here I will show you that it’s not hard to implement it yourself.</p><h3>Step 1: Replace SRC Attribute</h3><p>When an image has src attribute, it will always load no matter what. So our first step is to temporarily prefix them with data-.</p><p>In WordPress, we can filter the images html and replace img src attribute using str_replace() PHP function, add the following code in your theme functions.php.</p><pre>/**<br> * Lazy Load All Images<br> * <br> * To Exclude, simply add this attr to img html: loading=&quot;not_lazy&quot;<br> *<br> * @param string $html          Post thumbnail HTML<br> * <br> * @return string Filtered post image HTML.<br> */<br>add_filter( &#39;post_thumbnail_html&#39;, &#39;atdev_add_lazy_load_to_imgs&#39;, 10, 1 );<br>add_filter( &#39;wp_get_attachment_image&#39;, &#39;atdev_add_lazy_load_to_imgs&#39;, 10, 1 );<br>function atdev_add_lazy_load_to_imgs( $html ) {<br><br> if( ! is_admin() &amp;&amp; ! str_contains(strtolower($html), &#39;loading=&quot;not_lazy&quot;&#39;) ){<br><br>  $html = str_replace(<br>   &#39; src=&#39;, // Find<br>   &#39; loading=&quot;lazy&quot; data-lazy src=&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkqAcAAIUAgUW0RjgAAAAASUVORK5CYII=&quot; data-src=&#39;, // Replace<br>   $html // String<br>  );<br><br> }<br> return $html;<br>}</pre><h3>Step 2: Load in Intersect using JS</h3><p>The <a href="https://developers.google.com/web/updates/2016/04/intersectionobserver"><strong>intersection observer API</strong></a> helps to identify DOM elements that are in the viewport. It’s the way of implementing lazy load without writing event handler functions.</p><p>Add the following JS code in your theme footer.php.</p><pre>&lt;script&gt;<br>/**<br> * Lazy Load Images using Intersection Observer<br> * <br> */<br>var observer = new IntersectionObserver(onIntersect);<br>document.querySelectorAll(&quot;[data-lazy]&quot;).forEach((img) =&gt; {<br> observer.observe(img);<br>});<br><br>function onIntersect(entries) {<br> entries.forEach((entry) =&gt; {<br>  if (entry.target.getAttribute(&quot;loading&quot;) == &#39;not_lazy&#39; || entry.target.getAttribute(&quot;data-processed&quot;) || !entry.isIntersecting)<br>   return true;<br>  entry.target.setAttribute(&quot;src&quot;, entry.target.getAttribute(&quot;data-src&quot;));<br>  entry.target.setAttribute(&quot;data-processed&quot;, true);<br> });<br>}<br>&lt;/script&gt;</pre><p>You may not want to lazy load above the fold images, use the following JS code:</p><pre>&lt;script&gt;<br>/**<br> * (Trying to) Not lazy load above the fold images<br> */<br>document.addEventListener(&#39;DOMContentLoaded&#39;,() =&gt; {<br> <br> win_height = window.innerHeight;<br> imgs = document.getElementsByTagName(&#39;img&#39;);<br> for (var i = 0; i &lt; imgs.length; i++) {<br>  // At least 20 px above the fold<br>  if( imgs[i].getAttribute(&quot;loading&quot;) != &#39;not_lazy&#39; &amp;&amp; (imgs[i].offsetTop+20) &lt; win_height ){<br>   imgs[i].setAttribute(&quot;src&quot;, imgs[i].getAttribute(&quot;data-src&quot;));<br>   imgs[i].setAttribute(&quot;data-processed&quot;, true);<br>  } <br> }<br><br>});<br>&lt;/script&gt;</pre><p><strong>Note:</strong> Make sure &lt;img /&gt; must have height and width attribute.</p><h3>Conclusion:</h3><p>Lazy-load has become a necessity in all blogs and corporate websites. You don’t have to worry about SEO because Google themselves has confirmed that they can detect lazy-load.</p><p>It’s a best practice of SEO, which leads to lowering your web page load time by optimizing your overall site. This approach includes several benefits like-</p><ul><li>Your site visitors won’t require using much bandwidth to view your web pages.</li><li>You can boost your website’s search rankings.</li><li>It leads to an uplift of users and keeps them engaged, which ultimately leads to higher sales and conversions.</li><li>The site will be able to offer a better mobile experience.</li><li>Boost site performance by providing high-resolution images.</li></ul><p>What do you think of lazy loading? Have you used it to improve the performance of your website? Let me know, in the comment section below.</p><p>Have fun coding!</p><p><em>Originally published at </em><a href="https://www.ahmadthedev.com/wordpress/lazy-load-images-without-plugin/"><em>https://www.ahmadthedev.com</em></a><em> on January 6, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80b14e4787b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WordPress Add Meta Boxes — Ultimate Tutorial]]></title>
            <link>https://ahmadthedev.medium.com/wordpress-add-meta-boxes-ultimate-tutorial-9c6ad6690891?source=rss-3506429a0f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c6ad6690891</guid>
            <category><![CDATA[snippet]]></category>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[meta-box]]></category>
            <category><![CDATA[wordpress]]></category>
            <dc:creator><![CDATA[Ahmad Tahir]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 21:09:36 GMT</pubDate>
            <atom:updated>2023-01-12T11:45:53.012Z</atom:updated>
            <content:encoded><![CDATA[<h3>WordPress Add Meta Boxes — Ultimate Tutorial</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tg5syddFbXRGzuea.png" /></figure><p>Meta boxes are UI blocks in WordPress admin that allow you to manage post metadata.</p><p>Okay, what is metadata?</p><p>Every type of content in WordPress like posts, terms, users and comments has its own table in WordPress database, wp_posts, wp_terms, wp_users and wp_comments accordingly. Those tables are intended to store some default data, like post title and publish date for posts.</p><p>But what if you need to store something super-custom? Like a SEO-title for posts or an age for users or… product price for products? The answer is — metadata. WordPress also has specific database tables for that — wp_postmeta, wp_termmeta, wp_usermeta, wp_commentmeta.</p><p>Let me show you how to create a meta box in WordPress, here is a screenshot of what we are going to create:</p><p>Function add_meta_box() should be called inside an action hook, there are 3 options:</p><ul><li>add_meta_boxes</li><li>add_meta_boxes_{post_type} - here you can specify a specific post type name, e.g. add_meta_boxes_page - so the code will only run when editing page post type.</li></ul><pre>add_action( &#39;admin_menu&#39;, &#39;atdev_add_metabox&#39; );<br>// or add_action( &#39;add_meta_boxes&#39;, &#39;atdev_add_metabox&#39; );<br>// or add_action( &#39;add_meta_boxes_{post_type}&#39;, &#39;atdev_add_metabox&#39; );<br><br>function atdev_add_metabox() {<br><br> add_meta_box(<br>  &#39;atdev_metabox&#39;, // metabox ID<br>  &#39;Meta Box&#39;, // title<br>  &#39;wpdev_metabox_callback&#39;, // callback function<br>  &#39;page&#39;, // add meta box to custom post type (or post types in array)<br>  &#39;normal&#39;, // position (normal, side, advanced)<br>  &#39;default&#39; // priority (default, low, high, core)<br> );<br><br>}<br><br>// it is a callback function which actually displays the content of the meta box<br>function atdev_metabox_callback( $post ) {<br><br> echo &#39;hey&#39;;<br> <br>}</pre><p>Insert above code in your theme functions.php or in a custom plugin.</p><p>Now populate the meta box with custom fields.</p><pre>function atdev_metabox_callback( $post ) {<br><br> $seo_title = get_post_meta( $post-&gt;ID, &#39;seo_title&#39;, true );<br> $seo_robots = get_post_meta( $post-&gt;ID, &#39;seo_robots&#39;, true );<br><br> // nonce, actually I think it is not necessary here<br> wp_nonce_field( &#39;atdev_security&#39;, &#39;_atdevnonce&#39; );<br><br> echo &#39;&lt;table class=&quot;form-table&quot;&gt;<br>  &lt;tbody&gt;<br>   &lt;tr&gt;<br>    &lt;th&gt;&lt;label for=&quot;seo_title&quot;&gt;SEO title&lt;/label&gt;&lt;/th&gt;<br>    &lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;seo_title&quot; name=&quot;seo_title&quot; value=&quot;&#39; . esc_attr( $seo_title ) . &#39;&quot; class=&quot;regular-text&quot;&gt;&lt;/td&gt;<br>   &lt;/tr&gt;<br>   &lt;tr&gt;<br>    &lt;th&gt;&lt;label for=&quot;seo_robots&quot;&gt;SEO robots&lt;/label&gt;&lt;/th&gt;<br>    &lt;td&gt;<br>     &lt;select id=&quot;seo_robots&quot; name=&quot;seo_robots&quot;&gt;<br>      &lt;option value=&quot;&quot;&gt;Select...&lt;/option&gt;<br>      &lt;option value=&quot;index,follow&quot;&#39; . selected( &#39;index,follow&#39;, $seo_robots, false ) . &#39;&gt;Show for search engines&lt;/option&gt;<br>      &lt;option value=&quot;noindex,nofollow&quot;&#39; . selected( &#39;noindex,nofollow&#39;, $seo_robots, false ) . &#39;&gt;Hide for search engines&lt;/option&gt;<br>     &lt;/select&gt;<br>    &lt;/td&gt;<br>   &lt;/tr&gt;<br>  &lt;/tbody&gt;<br> &lt;/table&gt;&#39;;<br><br>}</pre><p>In the code above:</p><ul><li>I used function get_post_meta() to get the existing meta fields values and display them.</li><li>wp_nonce_field() is needed for additional security, when we save our meta box data, we can check the nonce value to make sure that the request come from the proper place.</li><li>selected() is a build-in WordPress function that simplifies the conditions and displaying selected=&quot;selected&quot; in the &lt;select&gt; field.</li></ul><p>If you are using this metabox on the page edit screen or for a custom post type, don’t forget to redefine supported post types, otherwise metabox data won’t be saved.</p><pre>add_action( &#39;save_post&#39;, &#39;atdev_save_meta&#39;, 10, 2 );<br>// or add_action( &#39;save_post_{post_type}&#39;, &#39;atdev_save_meta&#39;, 10, 2 );<br><br>function atdev_save_meta( $post_id, $post ) {<br><br> // nonce check<br> if ( ! isset( $_POST[ &#39;_atdevnonce&#39; ] ) || ! wp_verify_nonce( $_POST[ &#39;_atdevnonce&#39; ], &#39;atdev_security&#39; ) ) {<br>  return $post_id;<br> }<br><br> // check current user permissions<br> $post_type = get_post_type_object( $post-&gt;post_type );<br><br> if ( ! current_user_can( $post_type-&gt;cap-&gt;edit_post, $post_id ) ) {<br>  return $post_id;<br> }<br><br> // Do not save the data if autosave<br> if ( defined(&#39;DOING_AUTOSAVE&#39;) &amp;&amp; DOING_AUTOSAVE ) {<br>  return $post_id;<br> }<br><br> // define your own post type here<br> if( &#39;page&#39; !== $post-&gt;post_type ) {<br>  return $post_id;<br> }<br><br> if( isset( $_POST[ &#39;seo_title&#39; ] ) ) {<br>  update_post_meta( $post_id, &#39;seo_title&#39;, sanitize_text_field( $_POST[ &#39;seo_title&#39; ] ) );<br> } else {<br>  delete_post_meta( $post_id, &#39;seo_title&#39; );<br> }<br> if( isset( $_POST[ &#39;seo_robots&#39; ] ) ) {<br>  update_post_meta( $post_id, &#39;seo_robots&#39;, sanitize_text_field( $_POST[ &#39;seo_robots&#39; ] ) );<br> } else {<br>  delete_post_meta( $post_id, &#39;seo_robots&#39; );<br> }<br><br> return $post_id;<br><br>}</pre><p>Please keep in mind, that depending on your field type you must use sanitization, so in the above example I am using sanitize_text_field() function, but there are also another ones, like sanitize_textarea() for textarea fields, sanitize_email() etc.</p><p>Also it is also not necessary to use delete_post_meta() for some cases, for example for regular text fields. But isset() or empty() condition checks are still recommended because you would get PHP notices if a field value will be empty.</p><pre>$seo_title = isset( $_POST[ &#39;seo_title&#39; ] ) ? sanitize_text_field( $_POST[ &#39;seo_title&#39; ] ) : &#39;&#39;;<br>update_post_meta( $post_id, &#39;seo_title&#39;, $seo_title );</pre><p>Have fun coding!</p><p><em>Originally published at </em><a href="https://www.ahmadthedev.com/wordpress/create-meta-boxes/"><em>https://www.ahmadthedev.com</em></a><em> on January 1, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c6ad6690891" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>