Privacy Policy

/**
* Smart Technical Services Speed Optimization Snippet
*
* Instructions:
* Paste this code at the bottom of your active Astra Child Theme’s functions.php file,
* or add it as a new PHP snippet using a plugin like “Code Snippets” or “WPCode”.
*/

/**
* 1. Dequeue Contact Form 7 & SWV scripts on all pages except “Contact”
* This prevents these assets from loading on the Homepage, Services page, and About Us page.
*/
add_action( ‘wp_enqueue_scripts’, ‘sts_optimize_cf7_loading’, 99 );
function sts_optimize_cf7_loading() {
// Only load Contact Form 7 scripts on the page with slug “contact” or ID 18
if ( ! is_page( ‘contact’ ) && ! is_page( 18 ) ) {
// Dequeue JS Scripts
wp_dequeue_script( ‘contact-form-7’ );
wp_dequeue_script( ‘swv’ ); // SWV is the new CF7 validation engine

// Dequeue Stylesheets
wp_dequeue_style( ‘contact-form-7’ );
wp_dequeue_style( ‘astra-contact-form-7’ );
}
}

/**
* 2. Defer Non-Critical JavaScript
* Automatically adds the “defer” attribute to scripts, allowing the browser to parse HTML
* without waiting for JS downloads. jQuery is excluded to prevent breaking Elementor dependencies.
*/
add_filter( ‘script_loader_tag’, ‘sts_defer_non_critical_scripts’, 10, 3 );
function sts_defer_non_critical_scripts( $tag, $handle, $src ) {
// Protect admin dashboard
if ( is_admin() ) {
return $tag;
}

// Array of critical scripts that should NOT be deferred
$critical_scripts = array(
‘jquery’,
‘jquery-core’,
‘jquery-migrate’
);

if ( in_array( $handle, $critical_scripts ) ) {
return $tag;
}

// If already deferred or async, do nothing
if ( strpos( $tag, ‘defer’ ) !== false || strpos( $tag, ‘async’ ) !== false ) {
return $tag;
}

// Inject defer attribute
return str_replace( ‘ src’, ‘ defer src’, $tag );
}

/**
* 3. Preload Featured Image on Single Posts for LCP Optimization
* This instructs the browser to download the mobile-optimized featured image
* immediately in parallel, reducing Largest Contentful Paint (LCP) time.
*/
add_action( ‘wp_head’, ‘sts_preload_featured_image’, 1 );
function sts_preload_featured_image() {
if ( is_singular() && has_post_thumbnail() ) {
$thumbnail_id = get_post_thumbnail_id();
$image_src = wp_get_attachment_image_url( $thumbnail_id, ‘large’ );
$image_srcset = ”;

if ( $image_src ) {
// Check if using Cloudflare Images delivery URL
if ( strpos( $image_src, ‘imagedelivery.net’ ) !== false ) {
// Strip height parameter from preload href to match what Astra/Elementor outputs
$image_src = preg_replace( ‘/,h=[0-9]+/i’, ”, $image_src );
// Strip trailing width/height settings (e.g., /w=1024,h=765) to get the base image URL
$base_url = preg_replace( ‘//w=[0-9]+.*$/’, ”, $image_src );
$metadata = wp_get_attachment_metadata( $thumbnail_id );
$srcset_arr = array();

// Standard widths generated by WordPress and Elementor layout
$widths = array( 300, 768, 1024, 1200 );
if ( isset( $metadata[‘width’] ) ) {
$widths[] = (int) $metadata[‘width’];
}

$widths = array_unique( $widths );
sort( $widths );

foreach ( $widths as $width ) {
$srcset_arr[] = $base_url . ‘/w=’ . $width . ‘ ‘ . $width . ‘w’;
}

$image_srcset = implode( ‘, ‘, $srcset_arr );
} else {
// Fallback to standard WordPress srcset
$image_srcset = wp_get_attachment_image_srcset( $thumbnail_id, ‘large’ );
}

$image_sizes = ‘(max-width: 1024px) 100vw, 1024px’; // Matches Astra theme default dimensions

echo ”;
}
}
}

/**
* 4. Disable theme-rendered Featured Image on Single Posts
* This prevents Astra from outputting the top featured image to avoid having
* double images on pages where the image is manually added in the editor.
*/
add_filter( ‘astra_featured_image_enabled’, ‘sts_disable_single_post_featured_image’ );
function sts_disable_single_post_featured_image( $status ) {
if ( is_single() ) {
return false;
}
return $status;
}

/**
* 5. Programmatic JS Delay for Heavy Third-Party Scripts
* This buffers the final HTML output and rewrites script tags for GTM, Google Analytics,
* Facebook Pixel, Complianz, and JoinChat to type=”text/javascript-lazy”, delaying their
* execution until the first user interaction (scroll, touch, mouse move, etc.).
* This bypasses LiteSpeed Cache settings conflicts and drastically reduces Total Blocking Time (TBT).
*/
add_action( ‘wp’, ‘sts_start_delay_js_buffer’ );
function sts_start_delay_js_buffer() {
// Only run on front-end pages
if ( is_admin() || is_feed() ) {
return;
}
ob_start( ‘sts_delay_js_buffer_filter’ );
}

function sts_delay_js_buffer_filter( $html ) {
// If the page is empty or not HTML, do nothing
if ( empty( $html ) || stripos( $html, ‘<html' ) === false ) {
return $html;
}

// JavaScript keywords and patterns to delay
$delay_patterns = array(
'googletagmanager.com',
'gtag(',
'gtm.js',
'analytics.js',
'joinchat',
'fbq(',
'connect.facebook.net',
'complianz',
'google_gtagjs'
);

// Parse script tags
$html = preg_replace_callback( '/]*)>([sS]*?)/i’, function( $matches ) use ( $delay_patterns ) {
$attrs = $matches[1];
$content = $matches[2];

// Check if script matches any delay pattern
$should_delay = false;
foreach ( $delay_patterns as $pattern ) {
if ( stripos( $attrs, $pattern ) !== false || stripos( $content, $pattern ) !== false ) {
$should_delay = true;
break;
}
}

if ( $should_delay ) {
// If it has a src attribute, rewrite it to data-lazy-src and change type to text/javascript-lazy
if ( preg_match( ‘/bsrcs*=s*[“‘]([^”‘]+)[“‘]/i’, $attrs, $src_matches ) ) {
$src = $src_matches[1];
$new_attrs = preg_replace( ‘/bsrcs*=s*[“‘]([^”‘]+)[“‘]/i’, ”, $attrs );
// Remove async and defer attributes if present
$new_attrs = preg_replace( ‘/b(async|defer)b/i’, ”, $new_attrs );
// Remove any existing type attribute
$new_attrs = preg_replace( ‘/btypes*=s*[“‘]([^”‘]+)[“‘]/i’, ”, $new_attrs );

return ” . $content . ”;
} else {
// Inline script: remove any existing type attribute and set to text/javascript-lazy
$new_attrs = preg_replace( ‘/btypes*=s*[“‘]([^”‘]+)[“‘]/i’, ”, $attrs );
return ” . $content . ”;
}
}

return $matches[0];
}, $html );

// Inject the lazy loading execution manager just before
$lazy_loader_script = ‘

(function() {
var interacted = false;
var eventTypes = [“scroll”, “mousemove”, “mousedown”, “touchstart”, “keydown”];

function triggerDelayedScripts() {
if (interacted) return;
interacted = true;

// Clean up event listeners
eventTypes.forEach(function(e) {
window.removeEventListener(e, triggerDelayedScripts);
});

// Fetch and load all lazy scripts in order
var lazyScripts = document.querySelectorAll(‘script[type=”text/javascript-lazy”]’);
var index = 0;

function loadNext() {
if (index >= lazyScripts.length) return;
var script = lazyScripts[index++];
var newScript = document.createElement(“script”);

// Copy all attributes
for (var i = 0; i < script.attributes.length; i++) {
var attr = script.attributes[i];
if (attr.name !== "type" && attr.name !== "data-lazy-src") {
newScript.setAttribute(attr.name, attr.value);
}
}

newScript.setAttribute("type", "text/javascript");

if (script.hasAttribute("data-lazy-src")) {
newScript.setAttribute("src", script.getAttribute("data-lazy-src"));
// Wait for external script to load before running the next one to maintain execution order
newScript.onload = loadNext;
newScript.onerror = loadNext;
} else {
newScript.textContent = script.textContent;
script.parentNode.insertBefore(newScript, script);
script.parentNode.removeChild(script);
loadNext(); // Run next script immediately
return;
}

script.parentNode.insertBefore(newScript, script);
script.parentNode.removeChild(script);
}

loadNext();
}

eventTypes.forEach(function(e) {
window.addEventListener(e, triggerDelayedScripts, { passive: true });
});
})();
‘;

// Append just before the body closing tag
if ( stripos( $html, ” ) !== false ) {
$html = str_ireplace( ”, $lazy_loader_script . ”, $html );
} else {
$html .= $lazy_loader_script;
}

// 7. Programmatic SEO: Replace empty alt tags on the fly
$html = preg_replace(‘/]*?)balt=[“‘]s*[“‘]([^>]*?)>/i’, ‘‘, $html);

// 8. Programmatic SEO: Correct skipped heading rankings (H5 -> H3, H6 -> H4)
$html = preg_replace(‘/]*)>/i’, ‘

‘, $html);
$html = str_ireplace(‘

‘, ‘

‘, $html);
$html = preg_replace(‘/]*)>/i’, ‘

‘, $html);
$html = str_ireplace(‘

‘, ‘

‘, $html);

// ─────────────────────────────────────────────────────────────
// 9. SEO TASK #1: Homepage Title, Meta, OG replacements in HTML
// Applied via output buffer to ensure override of any cached values
// Using URL detection since is_front_page() doesn’t work in ob callbacks
// ─────────────────────────────────────────────────────────────
$request_uri = isset( $_SERVER[‘REQUEST_URI’] ) ? $_SERVER[‘REQUEST_URI’] : ”;
$request_path = rtrim( parse_url( $request_uri, PHP_URL_PATH ), ‘/’ );
$is_homepage = ( $request_path === ” || $request_path === ‘/index.php’ );

if ( $is_homepage ) {

// 9a. Replace tag<br /> $html = preg_replace(<br /> ‘/<title>[^<]*/i’,
Generator & AC Repair Services Jeddah | Smart Technical‘,
$html,
1
);

// 9b. Replace meta description
$html = preg_replace(
‘/<meta name="description" content="[^"]*"/i',
'<meta name="description" content="Expert generator repair, AC maintenance, motor rewinding & HVAC in Jeddah, Saudi Arabia. Available 24/7. Call +966545136673."',
$html,
1
);

// 9c. Replace OG title
$html = preg_replace(
'/(<meta property="og:title" content=")[^"]*(")/i',
'${1}Generator & AC Repair Services in Jeddah | Smart Technical Services${2}',
$html,
1
);

// 9d. Replace OG description
$html = preg_replace(
'/(<meta property="og:description" content=")[^"]*(")/i',
'${1}Expert generator repair, AC & HVAC in Jeddah, Saudi Arabia. Trusted by 1000+ clients. 24/7 service. Call +966545136673.${2}',
$html,
1
);

// 9e. Replace OG type (should be LocalBusiness not website)
$html = preg_replace(
'/(<meta property="og:type" content=")[^"]*(")/i',
'${1}business.business${2}',
$html,
1
);

// 9f. Replace Twitter title
$html = preg_replace(
'/(classes->get( YoastWPSEORepositoriesIndexable_Repository::class );
if ( $repo ) {
$indexable = $repo->find_by_id_and_type( $post_id, ‘post’ );
if ( $indexable ) {
$indexable->title = ‘Generator & AC Repair Services Jeddah | Smart Technical’;
$indexable->description = ‘Expert generator repair, AC maintenance, motor rewinding & HVAC in Jeddah, Saudi Arabia. Available 24/7. Call +966545136673.’;
$indexable->og_title = ‘Generator & AC Repair Services in Jeddah | Smart Technical Services’;
$indexable->og_description = ‘Expert generator repair, AC & HVAC in Jeddah. Trusted by 1000+ clients. Call +966545136673.’;
$indexable->twitter_title = ‘Generator & AC Repair | Smart Technical Services Jeddah’;
$indexable->twitter_description = ‘Expert generator, AC & HVAC services in Jeddah KSA. Call +966545136673.’;
$indexable->save();
}
}
} catch ( Exception $e ) {
// Silent fail – fallback to postmeta only
}
}

update_option( ‘sts_yoast_meta_v6’, gmdate( ‘Y-m-d H:i:s’ ) );

// Trigger LiteSpeed Cache purge for homepage
do_action( ‘litespeed_purge_post’, 2 );
do_action( ‘litespeed_purge_all’ );

// Trigger SPC Cloudflare cache purge using stored API credentials
$cf_api_token = get_option( ‘swcfpc_cf_api_token’, ” );
$cf_zone_id = get_option( ‘swcfpc_cf_zone_id’, ” );

if ( $cf_api_token && $cf_zone_id ) {
$cf_purge_url = ‘https://api.cloudflare.com/client/v4/zones/’ . $cf_zone_id . ‘/purge_cache’;
$cf_response = wp_remote_post( $cf_purge_url, array(
‘timeout’ => 10,
‘headers’ => array(
‘Authorization’ => ‘Bearer ‘ . $cf_api_token,
‘Content-Type’ => ‘application/json’,
),
‘body’ => json_encode( array( ‘purge_everything’ => true ) ),
) );
update_option( ‘sts_cf_purge_result’, is_wp_error( $cf_response ) ? ‘error’ : wp_remote_retrieve_response_code( $cf_response ) );
}
}

/**
* 8a. Override Homepage Yoast Title Tag (filter fallback)
* Target: <60 chars, includes primary keywords + brand
*/
add_filter( 'wpseo_title', 'sts_override_homepage_title', 99 );
function sts_override_homepage_title( $title ) {
if ( is_front_page() || is_home() ) {
return 'Generator & AC Repair Services Jeddah | Smart Technical';
}
return $title;
}

/**
* 8b. Override Homepage Yoast Meta Description
* Target: <155 chars, includes keywords, location, phone
*/
add_filter( 'wpseo_metadesc', 'sts_inject_homepage_meta_desc', 99 );
function sts_inject_homepage_meta_desc( $desc ) {
if ( is_front_page() || is_home() ) {
return 'Expert generator repair, AC maintenance, motor rewinding & HVAC in Jeddah, Saudi Arabia. Available 24/7. Call +966545136673.';
}
return $desc;
}

/**
* 8c. Override OpenGraph Title for Homepage
*/
add_filter( 'wpseo_opengraph_title', 'sts_override_og_title', 99 );
function sts_override_og_title( $title ) {
if ( is_front_page() || is_home() ) {
return 'Generator & AC Repair Services in Jeddah | Smart Technical Services';
}
return $title;
}

/**
* 8d. Override OpenGraph Description for Homepage
*/
add_filter( 'wpseo_opengraph_desc', 'sts_override_og_desc', 99 );
function sts_override_og_desc( $desc ) {
if ( is_front_page() || is_home() ) {
return 'Expert generator repair, AC & HVAC in Jeddah, Saudi Arabia. Trusted by 1000+ clients. 24/7 service. Call +966545136673.';
}
return $desc;
}

/**
* 8e. Add Twitter Card meta tags for Homepage
*/
add_action( 'wp_head', 'sts_homepage_twitter_card', 5 );
function sts_homepage_twitter_card() {
if ( ! ( is_front_page() || is_home() ) ) {
return;
}
echo '’ . “n”;
echo ” . “n”;
echo ” . “n”;
echo ” . “n”;
echo ” . “n”;
}

/**
* 8f. Inject Enhanced LocalBusiness + Service JSON-LD Schema on Homepage
* Covers: AEO/GEO (AI citations), Google Rich Results, Local Pack
*/
add_action( ‘wp_head’, ‘sts_inject_localbusiness_schema’, 2 );
function sts_inject_localbusiness_schema() {
if ( ! ( is_front_page() || is_home() ) ) {
return;
}
$schema = array(
‘@context’ => ‘https://schema.org’,
‘@graph’ => array(
// LocalBusiness Schema
array(
‘@type’ => array( ‘LocalBusiness’, ‘ProfessionalService’ ),
‘@id’ => ‘https://smart-technical-services.com/#localbusiness’,
‘name’ => ‘Smart Technical Services’,
‘alternateName’ => ‘STS Jeddah’,
‘url’ => ‘https://smart-technical-services.com’,
‘logo’ => ‘https://imagedelivery.net/EQ8WEfu4fd-oEuFuLNfqSw/90ca0d25-c98a-469d-a89f-0bec50fabe00/w=200,h=200,fit=crop’,
‘image’ => ‘https://imagedelivery.net/EQ8WEfu4fd-oEuFuLNfqSw/18636243-213b-48ba-db9f-aa6772101800/w=1200,h=630’,
‘description’ => ‘Smart Technical Services provides expert generator repair, AC maintenance, motor rewinding, HVAC, chiller, and electrical services in Jeddah, Saudi Arabia. Available 24/7.’,
‘telephone’ => array( ‘+966545136673’, ‘+966565766127′ ),
’email’ => ‘[email protected]’,
‘priceRange’ => ‘$$’,
‘currenciesAccepted’ => ‘SAR’,
‘paymentAccepted’ => ‘Cash, Bank Transfer’,
‘openingHoursSpecification’ => array(
array(
‘@type’ => ‘OpeningHoursSpecification’,
‘dayOfWeek’ => array( ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’ ),
‘opens’ => ’08:00′,
‘closes’ => ’22:00′,
),
array(
‘@type’ => ‘OpeningHoursSpecification’,
‘dayOfWeek’ => array( ‘Saturday’ ),
‘opens’ => ’09:00′,
‘closes’ => ’20:00′,
),
),
‘address’ => array(
‘@type’ => ‘PostalAddress’,
‘streetAddress’ => ‘Jeddah’,
‘addressLocality’ => ‘Jeddah’,
‘addressRegion’ => ‘Makkah Province’,
‘postalCode’ => ‘21577’,
‘addressCountry’ => ‘SA’,
),
‘geo’ => array(
‘@type’ => ‘GeoCoordinates’,
‘latitude’ => ‘21.5433’,
‘longitude’ => ‘39.1728’,
),
‘areaServed’ => array(
array( ‘@type’ => ‘City’, ‘name’ => ‘Jeddah’ ),
array( ‘@type’ => ‘City’, ‘name’ => ‘Makkah’ ),
array( ‘@type’ => ‘City’, ‘name’ => ‘Riyadh’ ),
array( ‘@type’ => ‘AdministrativeArea’, ‘name’ => ‘Saudi Arabia’ ),
),
‘hasMap’ => ‘https://maps.google.com/?q=Smart+Technical+Services+Jeddah’,
‘sameAs’ => array(
‘https://www.facebook.com/Smart.Technical.Services.KSA/’,
‘https://www.instagram.com/Smart_technical_services_ksa/’,
‘https://www.youtube.com/@smarttechnicalservices/’,
‘https://www.linkedin.com/company/smart-technical-services-ksa’,
‘https://mastodon.social/@Smart_Technical_Services/’,
),
‘hasOfferCatalog’ => array(
‘@type’ => ‘OfferCatalog’,
‘name’ => ‘Technical Services in Jeddah’,
‘itemListElement’ => array(
array( ‘@type’ => ‘Offer’, ‘itemOffered’ => array( ‘@type’ => ‘Service’, ‘name’ => ‘Generator Repair and Maintenance’ ) ),
array( ‘@type’ => ‘Offer’, ‘itemOffered’ => array( ‘@type’ => ‘Service’, ‘name’ => ‘AC Repair and Installation’ ) ),
array( ‘@type’ => ‘Offer’, ‘itemOffered’ => array( ‘@type’ => ‘Service’, ‘name’ => ‘Motor Rewinding’ ) ),
array( ‘@type’ => ‘Offer’, ‘itemOffered’ => array( ‘@type’ => ‘Service’, ‘name’ => ‘HVAC Maintenance’ ) ),
array( ‘@type’ => ‘Offer’, ‘itemOffered’ => array( ‘@type’ => ‘Service’, ‘name’ => ‘Generator Rental in Jeddah’ ) ),
array( ‘@type’ => ‘Offer’, ‘itemOffered’ => array( ‘@type’ => ‘Service’, ‘name’ => ‘Chiller Maintenance’ ) ),
array( ‘@type’ => ‘Offer’, ‘itemOffered’ => array( ‘@type’ => ‘Service’, ‘name’ => ‘Electrical Services’ ) ),
array( ‘@type’ => ‘Offer’, ‘itemOffered’ => array( ‘@type’ => ‘Service’, ‘name’ => ‘BMS Installation and Automation’ ) ),
array( ‘@type’ => ‘Offer’, ‘itemOffered’ => array( ‘@type’ => ‘Service’, ‘name’ => ‘Centrifugal Pump Maintenance’ ) ),
),
),
‘aggregateRating’ => array(
‘@type’ => ‘AggregateRating’,
‘ratingValue’ => ‘4.8’,
‘reviewCount’ => ‘127’,
‘bestRating’ => ‘5’,
‘worstRating’ => ‘1’,
),
),
// FAQ Schema for AEO — Homepage
array(
‘@type’ => ‘FAQPage’,
‘@id’ => ‘https://smart-technical-services.com/#faq’,
‘mainEntity’ => array(
array(
‘@type’ => ‘Question’,
‘name’ => ‘What services does Smart Technical Services offer in Jeddah?’,
‘acceptedAnswer’ => array(
‘@type’ => ‘Answer’,
‘text’ => ‘Smart Technical Services offers generator repair and maintenance, AC installation and repair, motor rewinding, HVAC maintenance, chiller servicing, BMS installation, electrical work, and equipment rental in Jeddah, Saudi Arabia.’,
),
),
array(
‘@type’ => ‘Question’,
‘name’ => ‘How do I contact Smart Technical Services in Jeddah?’,
‘acceptedAnswer’ => array(
‘@type’ => ‘Answer’,
‘text’ => ‘You can reach Smart Technical Services in Jeddah by calling +966545136673 or +966565766127, or by emailing [email protected]. Emergency services are available 24/7.’,
),
),
array(
‘@type’ => ‘Question’,
‘name’ => ‘Does Smart Technical Services provide emergency generator repair?’,
‘acceptedAnswer’ => array(
‘@type’ => ‘Answer’,
‘text’ => ‘Yes, Smart Technical Services provides 24/7 emergency generator repair and maintenance services throughout Jeddah and surrounding areas in Saudi Arabia.’,
),
),
array(
‘@type’ => ‘Question’,
‘name’ => ‘Does Smart Technical Services rent generators in Saudi Arabia?’,
‘acceptedAnswer’ => array(
‘@type’ => ‘Answer’,
‘text’ => ‘Yes, Smart Technical Services offers diesel generator rental in Jeddah and across Saudi Arabia for construction sites, events, and industrial facilities.’,
),
),
),
),
),
);

echo ” . “n”;
echo wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
echo “n” . ” . “n”;
}

/**
* ============================================================
* SEO TASK #2 — Article Schema for All Single Blog Posts
* Pillar: AEO/GEO (AI citation readiness), Technical SEO
* ============================================================
*/
add_action( ‘wp_head’, ‘sts_inject_article_schema’, 3 );
function sts_inject_article_schema() {
if ( ! is_singular( ‘post’ ) ) {
return;
}
global $post;
$author_name = get_the_author_meta( ‘display_name’, $post->post_author );
$date_pub = get_the_date( ‘c’, $post );
$date_mod = get_the_modified_date( ‘c’, $post );
$featured_img = get_the_post_thumbnail_url( $post, ‘large’ );
$excerpt = wp_strip_all_tags( get_the_excerpt( $post ) );
$categories = wp_get_post_categories( $post->ID, array( ‘fields’ => ‘names’ ) );
$permalink = get_permalink( $post );

$schema = array(
‘@context’ => ‘https://schema.org’,
‘@type’ => ‘Article’,
‘@id’ => $permalink . ‘#article’,
‘headline’ => get_the_title( $post ),
‘description’ => $excerpt ? $excerpt : get_the_title( $post ),
‘datePublished’ => $date_pub,
‘dateModified’ => $date_mod,
‘url’ => $permalink,
‘inLanguage’ => ‘en-US’,
‘author’ => array(
‘@type’ => ‘Organization’,
‘name’ => ‘Smart Technical Services’,
‘url’ => ‘https://smart-technical-services.com’,
),
‘publisher’ => array(
‘@type’ => ‘Organization’,
‘name’ => ‘Smart Technical Services’,
‘url’ => ‘https://smart-technical-services.com’,
‘logo’ => array(
‘@type’ => ‘ImageObject’,
‘url’ => ‘https://imagedelivery.net/EQ8WEfu4fd-oEuFuLNfqSw/90ca0d25-c98a-469d-a89f-0bec50fabe00/w=200,h=200,fit=crop’,
),
),
‘mainEntityOfPage’ => array(
‘@type’ => ‘WebPage’,
‘@id’ => $permalink,
),
);

if ( $featured_img ) {
$schema[‘image’] = array(
‘@type’ => ‘ImageObject’,
‘url’ => $featured_img,
);
}

if ( ! empty( $categories ) ) {
$schema[‘articleSection’] = implode( ‘, ‘, $categories );
}

echo ” . “n”;
echo wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
echo “n” . ” . “n”;
}

/**
* ============================================================
* SEO TASK #3 — Breadcrumb Schema on All Pages & Posts
* Pillar: Technical SEO + CTR (sitelinks breadcrumb in SERP)
* ============================================================
*/
add_action( ‘wp_head’, ‘sts_inject_breadcrumb_schema’, 4 );
function sts_inject_breadcrumb_schema() {
if ( is_front_page() || is_home() || is_404() ) {
return;
}

$breadcrumbs = array(
array(
‘@type’ => ‘ListItem’,
‘position’ => 1,
‘name’ => ‘Home’,
‘item’ => ‘https://smart-technical-services.com/’,
),
);

$position = 2;

// Category page
if ( is_category() ) {
$breadcrumbs[] = array(
‘@type’ => ‘ListItem’,
‘position’ => $position,
‘name’ => single_cat_title( ”, false ),
‘item’ => get_category_link( get_queried_object_id() ),
);
}

// Single post
if ( is_singular( ‘post’ ) ) {
$cats = get_the_category();
if ( ! empty( $cats ) ) {
$breadcrumbs[] = array(
‘@type’ => ‘ListItem’,
‘position’ => $position,
‘name’ => $cats[0]->name,
‘item’ => get_category_link( $cats[0]->term_id ),
);
$position++;
}
$breadcrumbs[] = array(
‘@type’ => ‘ListItem’,
‘position’ => $position,
‘name’ => get_the_title(),
‘item’ => get_permalink(),
);
}

// Single page
if ( is_page() ) {
$breadcrumbs[] = array(
‘@type’ => ‘ListItem’,
‘position’ => $position,
‘name’ => get_the_title(),
‘item’ => get_permalink(),
);
}

$schema = array(
‘@context’ => ‘https://schema.org’,
‘@type’ => ‘BreadcrumbList’,
‘itemListElement’ => $breadcrumbs,
);

echo ” . “n”;
echo wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
echo “n” . ” . “n”;
}

/**
* ============================================================
* SEO TASK #4 — Global Meta Robots Enhancement
* Ensure max-image-preview, max-snippet on all indexable pages
* ============================================================
*/
add_filter( ‘wpseo_robots’, ‘sts_enhance_robots_meta’, 99 );
function sts_enhance_robots_meta( $robots ) {
if ( is_singular() || is_front_page() ) {
return ‘index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1’;
}
return $robots;
}

/**
* ============================================================
* SEO TASK #5 — Canonical URL Enforcement
* Prevent duplicate content from trailing slashes / query strings
* ============================================================
*/
add_action( ‘wp_head’, ‘sts_enforce_canonical’, 1 );
function sts_enforce_canonical() {
if ( is_singular() ) {
$canonical = get_permalink();
if ( $canonical ) {
echo ” . “n”;
}
}
}

/**
* 9. Programmatic SEO: Inject Alt Tags to standard WordPress images that lack them
*/
add_filter( ‘wp_get_attachment_image_attributes’, ‘sts_inject_image_alt_tags’, 10, 2 );
function sts_inject_image_alt_tags( $attr, $attachment ) {
if ( empty( $attr[‘alt’] ) ) {
$title = get_the_title( $attachment->ID );
$attr[‘alt’] = ! empty( $title ) ? $title : ‘Smart Technical Services Jeddah’;
}
return $attr;
}

/**
* 10. Programmatic SEO: Disable lazy loading for the first image in single post content (LCP Optimization)
*/
add_filter( ‘the_content’, ‘sts_disable_lazy_load_first_image’ );
function sts_disable_lazy_load_first_image( $content ) {
if ( ! is_singular() ) {
return $content;
}

// Find the first tag and inject data-no-lazy=”1″ to tell LiteSpeed to bypass lazy loading
$content = preg_replace(
‘/]*?)>/i’,
‘,
$content,
1 // Limit to the first occurrence
);

return $content;
}

/**
* 11. Programmatic SEO: Optimize image ‘sizes’ attribute on single posts (LCP & size reduction)
*/
add_filter( ‘wp_calculate_image_sizes’, ‘sts_optimize_image_sizes_attribute’, 10, 2 );
function sts_optimize_image_sizes_attribute( $sizes, $size ) {
if ( is_singular() ) {
// Constrain maximum width on desktop screens to 700px to avoid downloading oversized images
return ‘(max-width: 767px) 100vw, 700px’;
}
return $sizes;
}

/**
* 12. Programmatic UI: Hide image captions globally for website visitors
* Injects inline CSS to hide captions (WordPress blocks, Elementor, and standard figures)
* from front-end visitors, while keeping them in the HTML source for SEO crawlers.
*/
add_action( ‘wp_head’, ‘sts_hide_image_captions_for_visitors’, 99 );
function sts_hide_image_captions_for_visitors() {
if ( is_admin() ) {
return;
}
echo ‘
.wp-caption-text,
figcaption,
.wp-element-caption,
.gallery-caption,
.elementor-image-caption,
.widget-image-caption {
display: none !important;
}
‘;
}