WordPress Codes

Super Snippets Bundle with the Switchboard

1) Download the Snippets bundle (loaded with awesome must-have snippets)
1a) If you only require the Switchboard, then just download that
2) Unzip the file
3) Go to Code Snippets > Import
4) Import the unzipped file
5) Activate the Snippets Switchboard

It is recommended that any separate snippets for font clamp, pageauditor, pagezoomer, landmarker, maskcurver, are removed before activating the new snippets inside the bundle.

The Filter Builder Version 5.1

1) Download the file
2) Unzip the file
3) Go to Code Snippets > Import
4) Import the unzipped file

Use extra codes below for additional expansions.

i) Off Canvas Reopen (keeps reopening Off Canvas if selecting filters). This should be added to Elementor Custom Codes.

PixRefiner - version 3.6

How to add (after taking a backup):
1) Install the Code Snippets Plugin
2) Click Add New 
3) Copy the below code
4) Click Save and Activate

Export-and-Import-V4

1) Unzip and add the Code Snippet to your source or destination site
2) Go to Tools to use Elementor V4 Export
3) Either Export or Import the Blueprint below (after unzipping)

Class-Name-Widen

1) Unzip and add the Code Snippet 

elementor-flight-deck

1) Unzip the file first to get the JSON
2) Go to the Code Snippets Plugin > Import
3) Add the JSON
4) Then Activate

v4-heading-paragraph-span

1) Unzip the file first to get the JSON
2) Go to the Code Snippets Plugin > Import
3) Add the JSON
4) Then Activate

flex-scroll-effects

1) Unzip and add the Code Snippet 

woocommerce-subscriptions

1) Unzip and add the Code Snippet 

form-submission-delete

1) Unzip and add the Code Snippet 

search-improve-35-words

1) Unzip and add the Code Snippet 

top-bar-width-mobile-devices

1) Unzip and import the Code Snippet 

wordpress-menu-variables

1) Unzip and import the Code Snippet 

forms-variables

1) Unzip and import the Code Snippet 

flex-variables

1) Unzip and import the Code Snippet

novamira-export

1) Unzip and import the Code Snippet

elementor-sidebar-layout

1) Unzip and import the Code Snippet

product-colour-variations

How to add (after taking a backup):
1) Install the Code Snippets Plugin
2) Click Add New 
3) Copy the below snippet
4) Click Save and Activate
5) Add a HTML widget into the Single Product template, and then paste the 2nd code.
6) Add the CSS to the ‘Add to Cart’ widget.

				
					/**
 * Woo Variation Radios + Auto Colour Swatches (reads term meta key: "color")
 * - Keeps the original <select> (hidden via CSS) for Woo compatibility
 * - Adds radio UI after it
 * - Works for taxonomy attributes (pa_*) and custom attributes
 */

add_filter('woocommerce_dropdown_variation_attribute_options_html', 'ws_variation_radios_with_term_colors', 20, 2);
function ws_variation_radios_with_term_colors($html, $args) {

    if ( empty($args['options']) || empty($args['product']) ) {
        return $html;
    }

    $product   = $args['product'];
    $attribute = $args['attribute']; // e.g. "pa_colour"
    $name      = !empty($args['name']) ? $args['name'] : 'attribute_' . sanitize_title($attribute);

    // Woo often passes selected in args; fallback to product default
    $selected  = isset($args['selected']) ? (string) $args['selected'] : (string) $product->get_variation_default_attribute($attribute);

    // Prevent duplicates if a theme/plugin re-filters the same HTML multiple times
    if ( strpos($html, 'ws-var-radios') !== false ) {
        return $html;
    }

    $out  = $html; // keep the select HTML (we will hide select in CSS)
    $out .= '<div class="ws-var-radios" data-attribute_name="' . esc_attr($name) . '">';

    foreach ( $args['options'] as $option ) {

        // IMPORTANT:
        // - For taxonomies: $option should be the term slug (what Woo expects)
        // - For custom attributes: $option is the raw string
        $value = (string) $option;
        $label = (string) $option;

        $hex = ''; // #rrggbb from term meta

        if ( taxonomy_exists($attribute) ) {
            $term = get_term_by('slug', $value, $attribute);
            if ( $term && !is_wp_error($term) ) {
                $label = $term->name;

                // Filter Builder v2 stores HEX here:
                $maybe = get_term_meta($term->term_id, 'color', true); //  [oai_citation:1‡filter-builder-version-2.code-snippets.json](sediment://file_00000000ce9471f4b6d0aed74334a195)
                $maybe = is_string($maybe) ? trim($maybe) : '';

                // Validate hex
                if ( preg_match('/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $maybe) ) {
                    $hex = $maybe;
                }
            }
        }

        $checked = checked($selected, $value, false);
        $style   = $hex ? ' style="--ws-swatch:' . esc_attr($hex) . ';"' : '';

        $out .= '<label class="ws-var-radio"' . $style . '>';
        $out .= '<input type="radio" name="' . esc_attr($name) . '" value="' . esc_attr($value) . '" ' . $checked . ' />';
        $out .= '<span class="ws-swatch" aria-hidden="true"></span>';
        $out .= '<span class="ws-label">' . esc_html(apply_filters('woocommerce_variation_option_name', $label)) . '</span>';
        $out .= '</label>';
    }

    $out .= '</div>';

    return $out;
}
				
			
				
					<script type="text/phast">jQuery(function($){$(document).on('change','.ws-var-radios input[type="radio"]',function(){var $radio=$(this);var name=$radio.attr('name');var value=$radio.val();var $select=$('select[name="'+name+'"]');if($select.length){$select.val(value).trigger('change');}});$(document).on('change','form.variations_form select',function(){var $select=$(this);var name=$select.attr('name');var value=$select.val();var $radios=$('.ws-var-radios input[type="radio"][name="'+name+'"]');if(!value){$radios.prop('checked',false);return;}
$radios.filter('[value="'+value+'"]').prop('checked',true);});$(document).on('click','.reset_variations',function(){setTimeout(function(){$('form.variations_form select').trigger('change');},0);});});</script>
				
			
				
					/* Hide the default dropdowns for product variations */
.woocommerce div.product form.cart .variations select {
display: none;
}

/* Radios wrapper */
selector .ws-var-radios{
  display:flex;
  flex-wrap:wrap;
  gap:25px;
}

/* Attribute Title alignment */
.woocommerce div.product form.cart .variations th {
text-align: left;
}



/* Each option */
.ws-var-radio{
  --ws-swatch: #fff; /*if no colour*/
  display:inline-flex;
  align-items:center;
  gap:6px;
  cursor:pointer;
  user-select:none;
}

/* Hide native radio */
.ws-var-radio input[type="radio"]{
  position:absolute;
  opacity:0;
  pointer-events:none;
}

/* Visible swatch dot */
.ws-var-radio .ws-swatch{
  width:15px;
  height:15px;
  border-radius:50px;
  background: var(--ws-swatch);
  display:inline-block;
    outline:1px solid #d0d0ce;
}

/* Checked state */
.ws-var-radio input[type="radio"]:checked + .ws-swatch{
  outline:2px solid #1e1e1e;
}

/* Keyboard focus */
.ws-var-radio input[type="radio"]:focus-visible + .ws-swatch{
  outline:1px solid #1e1e1e;
}

/* Reset / Clear variations link */
.woocommerce div.product form.cart .reset_variations {
    display: inline-block;      /* allows margin + hover area */
    margin-top: 15px;           /* spacing above */
    font-size: 16px;            /* font size */
    font-weight: 400;
    color: #007E9A;                /* text colour */
}

/* Hover state for Reset / Clear */
.woocommerce a.reset_variations:hover {
    color: #1e1e1e;             /* hover colour */
}

/* Set prices and stock colour */
.woocommerce div.product p.price,
.woocommerce div.product span.price,
.woocommerce-variation-price {
    color: #1e1e1e; 
}

.woocommerce div.product .stock {
    color: #1e1e1e;
}


.woocommerce div.product form.cart .variations th,
.woocommerce div.product form.cart .variations td {
  padding: 0 0 8px 0;
  background: #fff;
 line-height: 0em;
}

/* Make PayPal buttons match Add to Cart button width */
.woocommerce .wc-ppcp-button-container,
.woocommerce .paypal-buttons {
  max-width: 50%;
}

.ppc-button-wrapper {margin-top: 20px;
}
				
			

PDFView v.1.2 (Old Version)

PDFViewer v2.1

Site to Social

Currency/Number ACF Formatter

WooCommerce Recent Sales

Main Image Slider

Wishlist

Shortcode to use:
[ws_wishlist_heart size=”36″ off=”#000″ on=”#ff0050″]

taxonomy-dropdowns

				
					/* EXAMPLE Shortcode
[filter_dropdown 
    class="tax1" 
    taxonomy="poster-type" 
    placeholder="All Types" 
    border_color="#d0d0ce"
    border_radius="25px"
    padding="10px 25px"
    font_size="16px" 
    font_color="#444" 
    font_weight="600" 
    background_color="#f4f4f4"
    chevron_color="#999"
    exclude="uncategorized,paid"
]

EXAMPLE RESET Shortcode
[filter_reset_all
	placeholder="Reset All Filters"     
	border_color="#d0d0ce"
    border_radius="25px"
    font_size="16px" 
    font_color="#444" 
    font_weight="600" 
    padding="10px 25px"
    background_color="#fff"
    hover_background_color="#444"
    hover_font_color="#fff"
    hover_border_color="#444"
]
*/


function custom_taxonomy_filter_dropdown_shortcode($atts) {
    static $instance_id = 0;
    $instance_id++;

    $atts = shortcode_atts([
        'class' => 'filter-to-dropdown',
        'placeholder' => 'All Categories',
        'taxonomy' => 'category',
        'border_color' => '#ededed',
        'font_size' => '18px',
        'font_color' => '#444',
        'font_weight' => '400',
        'background_color' => '#f4f4f4',
        'chevron_color' => '#444',
        'border_radius' => '25px',
        'padding' => '10px 25px', // 🎯 dropdown padding control
        'exclude' => '',
    ], $atts);

    $select_id = 'custom-taxonomy-dropdown-' . $instance_id;
    $excluded_slugs = array_filter(array_map('trim', explode(',', $atts['exclude'])));

    ob_start();
    ?>

    <div class="custom-dropdown-wrapper">
        <select id="<?php echo esc_attr($select_id); ?>" class="custom-filter-dropdown no-jq-selectbox" data-filter-class="<?php echo esc_attr($atts['class']); ?>">
            <option value="__all"><?php echo esc_html($atts['placeholder']); ?></option>
            <?php
            $build_dropdown_options = function($terms, $taxonomy, $depth = 0) use (&$build_dropdown_options, $excluded_slugs) {
                foreach ($terms as $term) {
                    if (in_array($term->slug, $excluded_slugs)) {
                        continue;
                    }
                    $indent = str_repeat('— ', $depth);
                    echo '<option value="' . esc_attr($term->slug) . '">' . $indent . esc_html($term->name) . ' (' . intval($term->count) . ')</option>';

                    $children = get_terms([
                        'taxonomy' => $taxonomy,
                        'hide_empty' => false,
                        'parent' => $term->term_id,
                        'orderby' => 'name',
                        'order' => 'ASC',
                    ]);

                    if (!empty($children) && !is_wp_error($children)) {
                        $build_dropdown_options($children, $taxonomy, $depth + 1);
                    }
                }
            };

            $top_terms = get_terms([
                'taxonomy' => $atts['taxonomy'],
                'hide_empty' => false,
                'parent' => 0,
                'orderby' => 'name',
                'order' => 'ASC',
            ]);

            if (!empty($top_terms) && !is_wp_error($top_terms)) {
                $build_dropdown_options($top_terms, $atts['taxonomy']);
            }
            ?>
        </select>
    </div>

    <style>.custom-dropdown-wrapper{display:inline-block;text-align:left;}#<?php echo esc_attr($select_id);?>.custom-filter-dropdown{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:100%;padding:<?php echo esc_attr($atts['padding']);?>;font-size:<?php echo esc_attr($atts['font_size']);?> !important;color:<?php echo esc_attr($atts['font_color']);?> !important;font-weight:<?php echo esc_attr($atts['font_weight']);?> !important;background-color:<?php echo esc_attr($atts['background_color']);?> !important;border:1px solid <?php echo esc_attr($atts['border_color']);?> !important;border-radius:<?php echo esc_attr($atts['border_radius']);?> !important;background-image:url("data:image/svg+xml;charset=US-ASCII,<?php echo rawurlencode( '<svg width=\'12\' height=\'8\' viewBox=\'0 0 12 8\' xmlns=\'http://www.w3.org/2000/svg\'><path d=\'M1 1l5 5 5-5\' stroke=\'#' . ltrim($atts['chevron_color'],'#') . '\' stroke-width=\'2\' fill=\'none\' fill-rule=\'evenodd\'/></svg>' );?>");background-repeat:no-repeat;background-position:right 12px center;background-size:12px 8px;box-sizing:border-box;transition:border-color 0.2s ease;cursor:pointer;}</style>

    <script type="text/phast">jQuery(function($){$('.custom-filter-dropdown').each(function(){const filterClass=$(this).data('filter-class');if(filterClass){$('.'+filterClass).css({'opacity':'0','pointer-events':'none','height':'0','overflow':'hidden','margin':'0','padding':'0','position':'absolute'});}});$(document).on('change','.custom-filter-dropdown',function(){const $thisDropdown=$(this);const selected=$thisDropdown.val();const filterClass=$thisDropdown.data('filter-class');const $filterWidget=$('.'+filterClass);const $gridWidget=$filterWidget.closest('.elementor-widget').next('.elementor-widget');if(!$filterWidget.length||!$gridWidget.length){console.warn('[Filter Dropdown] Cannot find filter or grid for class:',filterClass);return;}
let $button;if(selected==='__all'){$button=$filterWidget.find('.e-filter-item[data-filter="__all"]');}else{$button=$filterWidget.find('.e-filter-item[data-filter="'+selected+'"]');}
if($button.length){$button.trigger('click');const gridId=$gridWidget.data('id');if(gridId&&window.elementorFrontend){const widgetInstance=window.elementorFrontend.getScope($('#elementor-'+gridId));if(widgetInstance&&widgetInstance.reload){widgetInstance.reload();}}}else if(selected==='__all'){const $allButton=$filterWidget.find('.e-filter-item[data-filter="__all"]');if($allButton.length){$allButton.trigger('click');}else{location.href=location.pathname;}}});});</script>

    <?php
    return ob_get_clean();
}
add_shortcode('filter_dropdown', 'custom_taxonomy_filter_dropdown_shortcode');

function custom_filter_reset_all_shortcode($atts) {
    $atts = shortcode_atts([
        'placeholder' => 'Reset All',
        'border_color' => '#ededed',
        'font_size' => '18px',
        'font_color' => '#444',
        'font_weight' => '400',
        'background_color' => '#f4f4f4',
        'border_radius' => '25px',
        'padding' => '10px 25px', // 🎯 reset button padding control
        'hover_background_color' => '#e0e0e0', // 🎯 New
        'hover_font_color' => '#222222',        // 🎯 New
        'hover_border_color' => '#d0d0d0',       // 🎯 New
    ], $atts);

    $unique_id = uniqid('reset_button_');

    ob_start();
    ?>

    <button type="button" class="custom-global-reset <?php echo esc_attr($unique_id); ?>"
        style="
            display: inline-block;
            padding: <?php echo esc_attr($atts['padding']); ?>;
            background: <?php echo esc_attr($atts['background_color']); ?>;
            color: <?php echo esc_attr($atts['font_color']); ?>;
            border: 1px solid <?php echo esc_attr($atts['border_color']); ?>;
            border-radius: <?php echo esc_attr($atts['border_radius']); ?>;
            font-size: <?php echo esc_attr($atts['font_size']); ?>;
            font-weight: <?php echo esc_attr($atts['font_weight']); ?>;
            cursor: pointer;
            transition: background 0.3s, color 0.3s, border-color 0.3s;
        "
    >
        <?php echo esc_html($atts['placeholder']); ?>
    </button>

    <style>.<?php echo esc_attr($unique_id);?>:hover{background:<?php echo esc_attr($atts['hover_background_color']);?> !important;color:<?php echo esc_attr($atts['hover_font_color']);?> !important;border-color:<?php echo esc_attr($atts['hover_border_color']);?> !important;}</style>

    <script type="text/phast">jQuery(function($){$(document).on('click','.custom-global-reset',function(){$('.custom-filter-dropdown').each(function(){const $thisDropdown=$(this);$thisDropdown.val('__all');const filterClass=$thisDropdown.data('filter-class');const $filterWidget=$('.'+filterClass);if($filterWidget.length){const $allButton=$filterWidget.find('.e-filter-item[data-filter="__all"]');if($allButton.length){$allButton.trigger('click');}}});});});</script>

    <?php
    return ob_get_clean();
}
add_shortcode('filter_reset_all', 'custom_filter_reset_all_shortcode');
				
			

elementor-base-code

				
					/* Div Block element.
Sets minimum width of 30px, adds 10px padding, and displays as a block-level element. */
.elementor .e-div-block-base {
    min-width: 30px;
    padding: 10px;
    display: block;
}

/* Flexbox element.
Creates a flex container with horizontal row layout and 10px padding. */
.elementor .e-flexbox-base {
    padding: 10px;
    display: flex;
    flex-direction: row;
}

/* Tabs wrapper element.
Stacks tab menu and content vertically with 30px gap spacing. */
.elementor .e-tabs-base {
    padding-block-start: 0px;
    display: flex;
    flex-direction: column;
    gap: 30px;
}

/* Tabs menu wrapper.
Displays tab buttons using flexbox and centres them horizontally. */
.elementor .e-tabs-menu-base {
    display: flex;
    justify-content: center;
}

/* Individual tab button element.
Sets width, colours, padding, borders, background, and cursor styling. */
.elementor .e-tab-base {
    width: 160px;
    color: #0C0D0E;
    cursor: pointer;
    padding: 8px;
    border-width: 2px;
    border-color: #E0E0E0;
    border-style: solid;
    background-color: #FFFFFF;
    display: block;
}

/* Selected tab state.
Changes border colour for the active tab and removes outline width. */
.elementor .e-tab-base.e--selected {
    border-color: #0C0D0E;
    outline-width: 0px;
}

/* Focused tab state.
Changes border colour when tab receives focus and removes outline width. */
.elementor .e-tab-base:focus {
    border-color: #0C0D0E;
    outline-width: 0px;
}

/* Hovered or keyboard-focused tab state.
Changes tab background colour on hover or visible focus. */
.elementor .e-tab-base:hover,
.elementor .e-tab-base:focus-visible {
    background-color: #E0E0E0;
}

/* Tabs content wrapper.
Displays tab content area as a block-level element. */
.elementor .e-tabs-content-area-base {
    display: block;
}

/* Individual tab content panel.
Sets minimum width, adds 10px padding, and displays as block. */
.elementor .e-tab-content-base {
    min-width: 30px;
    padding: 10px;
    display: block;
}

/* Form wrapper element.
Creates flexbox form layout with wrapping, spacing, alignment, and 20px padding. */
.elementor .e-form-base {
    padding: 20px;
    display: flex;
    flex-direction: row;
    gap: 10px;
    flex-wrap: wrap;
    align-content: start;
    align-items: flex-start;
}

/* Checkbox row inside forms.
Removes padding, adds 8px gap, and vertically aligns items. */
.elementor .e-form-base .e-form-checkbox-row {
    padding: 0px;
    gap: 8px;
    align-items: center;
}

/* Form success message.
Styles success notification with green colours and hides it by default. */
.elementor .e-form-success-message-base {
    font-size: 12px;
    color: #2F532E;
    text-align: center;
    padding: 12px;
    background-color: #D4E9D6;
    display: none;
}

/* Form error message.
Styles error notification with red colours and hides it by default. */
.elementor .e-form-error-message-base {
    font-size: 12px;
    color: #870000;
    text-align: center;
    padding: 12px;
    background-color: #ffdede;
    display: none;
}

/* Heading element.
Removes default heading margin spacing. */
.elementor .e-heading-base {
    margin: 0px;
}

/* Heading link element.
Removes default browser link styling and enables pointer cursor. */
.elementor .e-heading-link-base {
    all: unset;
    cursor: pointer;
}

/* Image link wrapper.
Makes linked image width fit content and inherit display behaviour. */
.elementor .e-image-link-base {
    width: fit-content;
    display: inherit;
}

/* Image element.
Displays image as a block-level element. */
.elementor .e-image-base {
    display: block;
}

/* Paragraph element.
Removes default paragraph margins. */
.elementor .e-paragraph-base {
    margin: 0px;
}

/* Paragraph link element.
Removes default browser link styling and enables pointer cursor. */
.elementor .e-paragraph-link-base {
    all: unset;
    cursor: pointer;
}

/* SVG element.
Sets default SVG dimensions and displays inline-block. */
.elementor .e-svg-base {
    width: 65px;
    height: 65px;
    display: inline-block;
}

/* Button element.
Adds padding, blue background, border radius, centre alignment, and inline-block display. */
.elementor .e-button-base {
    text-align: center;
    padding-block-start: 12px;
    padding-block-end: 12px;
    padding-inline-start: 24px;
    padding-inline-end: 24px;
    border-radius: 2px;
    border-width: 0px;
    background-color: #375EFB;
    display: inline-block;
}

/* YouTube embed element.
Maintains 16:9 aspect ratio and hides overflow. */
.elementor .e-youtube-base {
    overflow: hidden;
    aspect-ratio: 16/9;
}

/* Divider element.
Creates a 1px high black divider using background colour. */
.elementor .e-divider-base {
    height: 1px;
    border-width: 0px;
    border-color: transparent;
    border-style: none;
    background-color: #000;
}

/* Self-hosted video element.
Limits width to viewport, maintains 16:9 ratio, and displays inline-block. */
.elementor .e-self-hosted-video-base {
    max-width: 100vw;
    aspect-ratio: 16/9;
    display: inline-block;
}

/* Standard form input field.
Sets input height, font size, colours, and border styling. */
.elementor .e-form-input-base {
    height: 36px;
    font-size: 12px;
    color: #0c0d0e;
    border-radius: 0px;
    border-color: #D6D5D5;
}

/* Focused form input field.
Darkens border colour and removes browser outline. */
.elementor .e-form-input-base:focus {
    border-color: #706F6F;
    outline-style: none;
}

/* Form input placeholder text.
Sets placeholder text colour. */
.elementor .e-form-input-base::placeholder {
    color: #9DA5AE;
}

/* Form label element.
Sets label font size and text colour. */
.elementor .e-form-label-base {
    font-size: 14px;
    color: #0c0d0e;
}

/* Textarea field element.
Sets font size and border styling. */
.elementor .e-form-textarea-base {
    font-size: 12px;
    border-radius: 0px;
    border-color: #D6D5D5;
}

/* Focused textarea field.
Darkens border colour and removes browser outline. */
.elementor .e-form-textarea-base:focus {
    border-color: #706F6F;
    outline-style: none;
}

/* Textarea placeholder text.
Sets placeholder text colour. */
.elementor .e-form-textarea-base::placeholder {
    color: #9DA5AE;
}

/* Form submit button element.
Creates black button with centred content, padding, and white text. */
.elementor .e-form-submit-button-base {
    color: #fff;
    padding-block-start: 10px;
    padding-block-end: 10px;
    padding-inline-start: 28px;
    padding-inline-end: 30px;
    border-radius: 0px;
    border-width: 0px;
    background-color: #000;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* Hovered or focused submit button.
Changes background colour on hover or keyboard focus. */
.elementor .e-form-submit-button-base:hover,
.elementor .e-form-submit-button-base:focus-visible {
    background-color: #323232;
}

/* Checkbox input element.
Creates custom checkbox styling, sizing, borders, transitions, and removes browser appearance. */
.elementor .e-form-checkbox-base {
    width: 1.15em;
    height: 1.15em;
    color: #ffffff;
    border-radius: 0px;
    border-width: 1px;
    border-color: #D6D5D5;
    border-style: solid;
    background-color: transparent;
    transition: background-color 200ms;
    display: grid;
    justify-items: center;
    align-items: center;
    appearance: none;
}

/* Focused checkbox element.
Darkens border colour and removes browser outline. */
.elementor .e-form-checkbox-base:focus {
    border-color: #706F6F;
    outline-style: none;
}

/* Checked checkbox state.
Changes checkbox background colour when selected. */
.elementor .e-form-checkbox-base:checked {
    background-color: #69727D;
}

/* Checkbox checkmark pseudo-element.
Creates custom checkmark shape using clip-path and opacity transition. */
.elementor .e-form-checkbox-base::before {
    width: 65%;
    height: 65%;
    background-color: currentColor;
    opacity: 0%;
    transform-origin: 0% 100% 0px;
    transition: opacity 200ms;
    content: "";
    clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%);
}

/* Visible checkbox checkmark state.
Shows checkmark when checkbox is checked. */
.elementor .e-form-checkbox-base:checked::before {
    opacity: 100%;
}

/* Radio button element.
Creates custom circular radio button and removes browser appearance. */
.elementor .e-form-radio-button-base {
    width: 1.15em;
    height: 1.15em;
    color: #ffffff;
    border-radius: 50%;
    border-width: 1px;
    border-color: #D6D5D5;
    border-style: solid;
    background-color: transparent;
    display: grid;
    justify-items: center;
    align-items: center;
    appearance: none;
}

/* Focused radio button.
Darkens border colour and removes browser outline. */
.elementor .e-form-radio-button-base:focus {
    border-color: #706F6F;
    outline-style: none;
}

/* Checked radio button state.
Keeps background transparent when selected. */
.elementor .e-form-radio-button-base:checked {
    background-color: transparent;
}

/* Radio button inner dot pseudo-element.
Creates inner selected dot using opacity transition. */
.elementor .e-form-radio-button-base::before {
    width: 65%;
    height: 65%;
    border-radius: 50%;
    background-color: #706F6F;
    opacity: 0%;
    transition: opacity 200ms;
    content: "";
}

/* Visible radio button selected dot.
Shows inner dot when radio button is selected. */
.elementor .e-form-radio-button-base:checked::before {
    opacity: 100%;
}

/* Date picker field element.
Sets sizing, borders, colours, and typography for date input. */
.elementor .e-form-date-picker-base {
    width: 100%;
    height: 36px;
    font-size: 12px;
    color: #0c0d0e;
    border-radius: 0px;
    border-width: 1px;
    border-color: #D6D5D5;
    border-style: solid;
}

/* Focused date picker field.
Darkens border colour and removes browser outline. */
.elementor .e-form-date-picker-base:focus {
    border-color: #706F6F;
    outline-style: none;
}

/* Time picker field element.
Sets sizing, borders, colours, and typography for time input. */
.elementor .e-form-time-picker-base {
    width: 100%;
    height: 36px;
    font-size: 12px;
    color: #0c0d0e;
    border-radius: 0px;
    border-width: 1px;
    border-color: #D6D5D5;
    border-style: solid;
}

/* Focused time picker field.
Darkens border colour and removes browser outline. */
.elementor .e-form-time-picker-base:focus {
    border-color: #706F6F;
    outline-style: none;
}

/* Select dropdown field element.
Sets border styling, typography, and transparent background. */
.elementor .e-form-select-base {
    font-size: 12px;
    border-width: 1px;
    border-color: #D6D5D5;
    border-style: solid;
    background-color: transparent;
}

/* Focused select dropdown field.
Darkens border colour and removes browser outline. */
.elementor .e-form-select-base:focus {
    border-color: #706F6F;
    outline-style: none;
}

/* File upload field element.
Sets sizing, typography, colours, and border styling. */
.elementor .e-form-file-upload-base {
    height: 36px;
    font-size: 12px;
    color: #0c0d0e;
    border-radius: 0px;
    border-color: #D6D5D5;
}

/* Focused file upload field.
Darkens border colour and removes browser outline. */
.elementor .e-form-file-upload-base:focus {
    border-color: #706F6F;
    outline-style: none;
}
				
			

image-mask-merge

				
					/* Make the gap length animatable */
@property --g {
  syntax: "<length>";
  inherits: true;
  initial-value: 20px;
}

img {
  --g: 20px;

  --_g: var(--g)/calc(50% - var(--g)) calc(50% - var(--g))
    no-repeat conic-gradient(#000 0 0);

  -webkit-mask:
    left   var(--_i,) top    var(--_g),
    bottom var(--_i,) left   var(--_g),
    top    var(--_i,) right  var(--_g),
    right  var(--_i,) bottom var(--_g);
  mask:
    left   var(--_i,) top    var(--_g),
    bottom var(--_i,) left   var(--_g),
    top    var(--_i,) right  var(--_g),
    right  var(--_i,) bottom var(--_g);

  transition: filter .3s linear;
  cursor: pointer;

  /* Hook into scroll */
  view-timeline-name: --gapScroll;
  view-timeline-axis: block;

  animation: gap-shrink 1 linear both;
  animation-timeline: --gapScroll;
  animation-range: cover 45% cover 60%;
}

/* Animate the CSS var based on scroll */
@keyframes gap-shrink {
  from { --g: 20px; }
  to   { --g: 0px; }
}

/* ===== Mobile override ===== */
@media (max-width: 767px) {
  img {
    --g: 20px;          /* force a fixed gap (or set to 0px if you want no gap) */
    animation: none;    /* stop the scroll animation */
  }
}
				
			

drag-and-drop-ordering

				
					/**
 * Universal Admin Reorder (PATCHED)
 * Fixes:
 * - DO NOT force posts_per_page = -1 (keeps pagination fast)
 * - DO NOT interfere with admin-ajax (Quick Edit / inline-save)
 * - Save Quick Edit menu_order WITHOUT wp_update_post recursion
 * - Minor hardening + cleanup for columns/bulk actions across supported post types
 */

/**
 * 1) Enable menu_order support for all public post types including WooCommerce Products
 */
add_action('init', function () {
    $post_types = get_post_types(['public' => true], 'names');

    foreach ($post_types as $pt) {
        // Add "page-attributes" support (menu_order lives here in WP UI)
        if (!post_type_supports($pt, 'page-attributes')) {
            add_post_type_support($pt, 'page-attributes');
        }

        // Ensure products also have it (some setups omit it)
        if ($pt === 'product' && !post_type_supports($pt, 'page-attributes')) {
            add_post_type_support($pt, 'page-attributes');
        }
    }
}, 20);


/**
 * 2) Default admin post order by menu_order when supported and no explicit sort selected
 * PATCH: do NOT set posts_per_page = -1, and do NOT run during AJAX (Quick Edit)
 */
add_action('pre_get_posts', function ($q) {
    if (!is_admin() || !$q->is_main_query()) return;

    // Critical: do not touch admin-ajax requests (Quick Edit / inline-save etc.)
    if (wp_doing_ajax()) return;

    // Only on list table screens (edit.php)
    if (!function_exists('get_current_screen')) return;
    $screen = get_current_screen();
    if (!$screen || $screen->base !== 'edit') return;

    $post_type = $q->get('post_type');
    if (!$post_type) return;

    // Some admin screens provide array post_type – normalize
    if (is_array($post_type)) {
        $post_type = reset($post_type);
    }

    if (!post_type_supports($post_type, 'page-attributes')) return;

    // If user chose an orderby that isn't menu_order, respect it
    $orderby = isset($_GET['orderby']) ? sanitize_key($_GET['orderby']) : '';
    if ($orderby && $orderby !== 'menu_order') return;

    $q->set('orderby', 'menu_order');
    $q->set('order', 'ASC');

    // PATCH: keep pagination (no posts_per_page = -1)
}, 20);


/**
 * 3) Enqueue jQuery UI Sortable
 */
add_action('admin_enqueue_scripts', function () {
    wp_enqueue_script('jquery-ui-sortable');
});


/**
 * 4) Add reorder toggle button and script (edit.php only)
 */
add_action('admin_footer-edit.php', function () {
    if (!function_exists('get_current_screen')) return;
    $screen = get_current_screen();
    if (!$screen || empty($screen->post_type)) return;
    if (!post_type_supports($screen->post_type, 'page-attributes')) return;

    $nonce = wp_create_nonce('universal_order_nonce');
    $post_type = esc_js($screen->post_type);
    ?>
    <style>.reorder-button{display:inline-block;margin:1px 0 0 8px;padding:0 10px;line-height:2.15384615;font-size:13px;vertical-align:top;text-decoration:none;border:1px solid #2271b1;border-radius:3px;background:#f6f7f7;color:#2271b1;cursor:pointer;transition:all .2s ease}.reorder-button:hover{background:#f0f0f1;border-color:#0a4b78;color:#0a4b78}.reorder-button::before{content:'';margin-right:5px;font-weight:700;display:inline-block;transition:transform .3s ease}.reorder-button.active{background:#2271b1!important;border-color:#2271b1!important;color:#fff!important}.reorder-button.active:hover{background:#135e96!important;border-color:#135e96!important}.reorder-button.active::before{transform:rotate(90deg)}table.wp-list-table .column-reorder_handle{display:none}body.reorder-mode table.wp-list-table .column-reorder_handle{display:table-cell;width:40px;text-align:center}.drag-handle{display:none;width:24px;height:24px;border-radius:4px;background:#f0f0f1;border:1px solid #c3c4c7;position:relative;transition:all .2s ease;margin:0 auto}.drag-handle::before{content:'';position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:12px;height:2px;background:#787c82;box-shadow:0 4px 0 #787c82,0 -4px 0 #787c82;border-radius:1px}body.reorder-mode .drag-handle{display:block;cursor:move;animation:fadeIn .3s ease-out}@keyframes fadeIn{from{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}body.reorder-mode .drag-handle:hover{background:#2271b1;border-color:#2271b1;transform:scale(1.1)}body.reorder-mode .drag-handle:hover::before{background:#fff;box-shadow:0 4px 0 #fff,0 -4px 0 #fff}body.reorder-mode tr.ui-sortable-helper{display:table!important;table-layout:fixed!important;width:auto;background:#fff;box-shadow:0 3px 6px rgba(0,0,0,.15);opacity:.9}body.reorder-mode tr.ui-sortable-placeholder{background:#f0f0f1;visibility:visible!important;position:relative}body.reorder-mode tr.ui-sortable-placeholder td{background:rgba(34,113,177,.05)}.reorder-notice{display:none;background:#f0f7ff;border-left:4px solid #2271b1;padding:12px;margin:10px 0;animation:slideDown .3s ease-out}body.reorder-mode .reorder-notice{display:block}@keyframes slideDown{from{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.reorder-saving{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,.8);color:#fff;padding:20px 40px;border-radius:4px;z-index:100000;display:none}.reorder-saving.active{display:block}body.reorder-mode .row-actions{visibility:hidden}body.reorder-mode tr:hover{background:#f6f7f7}.column-menu_order{width:60px;text-align:center}.order-badge{display:inline-block;background:#dcdcde;color:#50575e;padding:2px 8px;border-radius:3px;font-size:12px;font-weight:500}body.reorder-mode .order-badge{background:#2271b1;color:#fff}</style>

    <div class="reorder-notice">
        <strong>Reorder Mode Active:</strong> Drag the handles to reorder items. Changes save automatically. Click "Toggle Reorder" again when done.
    </div>
    <div class="reorder-saving">
        <span class="spinner is-active" style="float:left;margin:0 10px 0 0;"></span>
        Saving order...
    </div>

    <script type="text/phast">jQuery(function($){var $button=$('<a href="#" class="reorder-button">Toggle Reorder</a>');setTimeout(function(){var $topNav=$('.tablenav.top');if($topNav.length){var $actionsArea=$topNav.find('.alignleft.actions.bulkactions');if($actionsArea.length){var $lastAction=$actionsArea.siblings('.alignleft.actions').last();if($lastAction.length)$lastAction.append($button);else $actionsArea.append($button);}else{$topNav.find('.alignleft').last().append($button);}}},100);var $titleArea=$('.wrap h1, .wrap h2').first();$('.reorder-notice').insertAfter($titleArea);var reorderActive=false;var $tbody=$('table.wp-list-table tbody');var originalTitle=document.title;$(document).on('keydown',function(e){if((e.ctrlKey||e.metaKey)&&e.key==='r'&&!$(e.target).is(':input')){e.preventDefault();$button.trigger('click');}});$button.on('click',function(e){e.preventDefault();reorderActive=!reorderActive;$('body').toggleClass('reorder-mode',reorderActive);$button.toggleClass('active',reorderActive);document.title=reorderActive?' Reordering - '+originalTitle:originalTitle;if(reorderActive){$tbody.sortable({items:'tr',axis:'y',handle:'td.column-reorder_handle',tolerance:'pointer',helper:function(e,tr){var $originals=tr.children();var $helper=tr.clone();$helper.children().each(function(index){$(this).width($originals.eq(index).width());});return $helper;},start:function(e,ui){ui.placeholder.height(ui.item.height());},update:function(e,ui){var movedId=(ui.item.attr('id')||'').replace('post-','');var newIndex=ui.item.index();$('.reorder-saving').addClass('active');$.post(ajaxurl,{action:'save_post_order',post_id:movedId,new_index:newIndex,post_type:'<?php echo $post_type; ?>',security:'<?php echo $nonce; ?>'},function(res){$('.reorder-saving').removeClass('active');if(res&&res.success){$tbody.find('tr').each(function(index){$(this).find('td.column-menu_order .order-badge').text(index+1);});}else{alert((res&&res.data)?res.data:'Order failed');$tbody.sortable('cancel');}}).fail(function(){$('.reorder-saving').removeClass('active');alert('Network error. Please try again.');$tbody.sortable('cancel');});}});}else{if($tbody.data('ui-sortable'))$tbody.sortable('destroy');}});$(window).on('beforeunload',function(){if(reorderActive)$('body').removeClass('reorder-mode');});});</script>
    <?php
});


/**
 * 5) Handle AJAX reorder saving
 * NOTE: This still reorders the whole list and updates menu_order for each item.
 * That’s expected (and only runs when you drag/drop), but it’s NOT part of Quick Edit.
 */
add_action('wp_ajax_save_post_order', function () {
    if (!current_user_can('edit_others_posts')) {
        wp_send_json_error('Permission denied');
    }
    if (!check_ajax_referer('universal_order_nonce', 'security', false)) {
        wp_send_json_error('Bad nonce');
    }

    $post_id   = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
    $new_index = isset($_POST['new_index']) ? (int) $_POST['new_index'] : 0;
    $post_type = sanitize_key($_POST['post_type'] ?? '');

    if (!$post_id || !$post_type) {
        wp_send_json_error('Invalid data');
    }

    $args = [
        'post_type'      => $post_type,
        'posts_per_page' => -1,
        'post_status'    => ['publish', 'draft', 'pending', 'future', 'private'],
        'orderby'        => 'menu_order',
        'order'          => 'ASC',
        'fields'         => 'ids',
    ];

    $all_ids = get_posts($args);

    if (!in_array($post_id, $all_ids, true)) {
        wp_send_json_error('Post ID not found');
    }

    $from = array_search($post_id, $all_ids, true);
    array_splice($all_ids, $from, 1);
    array_splice($all_ids, $new_index, 0, $post_id);

    // Fast update (avoid triggering save_post hooks repeatedly)
    global $wpdb;
    foreach ($all_ids as $index => $id) {
        $wpdb->update(
            $wpdb->posts,
            ['menu_order' => (int) $index],
            ['ID' => (int) $id],
            ['%d'],
            ['%d']
        );
        clean_post_cache((int) $id);
    }

    wp_send_json_success('Order saved');
});


/**
 * 6) WooCommerce respects menu_order when selected
 */
add_filter('woocommerce_default_catalog_orderby_options', function ($options) {
    $options['menu_order'] = 'Default sorting';
    return $options;
});

add_filter('woocommerce_get_catalog_ordering_args', function ($args) {
    if (isset($_GET['orderby']) && $_GET['orderby'] === 'menu_order') {
        $args['orderby'] = 'menu_order title';
        $args['order']   = 'ASC';
    }
    return $args;
});


/**
 * 7) Add drag handle and "Order" columns to admin tables
 * PATCH: avoid duplicate manage_edit-{$pt}_columns filters by using one filter to add both
 */
add_action('admin_init', function () {
    $post_types = get_post_types(['public' => true], 'names');

    foreach ($post_types as $pt) {
        if (!post_type_supports($pt, 'page-attributes')) continue;

        // Add drag handle + Order column
        add_filter("manage_edit-{$pt}_columns", function ($columns) {
            // Insert handle at start
            $columns = array_merge(['reorder_handle' => ''], $columns);

            // Add order column (near end)
            $columns['menu_order'] = 'Order';
            return $columns;
        });

        // Populate columns
        add_action("manage_{$pt}_posts_custom_column", function ($column, $post_id) {
            if ($column === 'menu_order') {
                $order = (int) get_post_field('menu_order', $post_id);
                echo '<span class="order-badge">' . esc_html($order + 1) . '</span>';
            } elseif ($column === 'reorder_handle') {
                echo '<div class="drag-handle"></div>';
            }
        }, 10, 2);

        // Make Order column sortable
        add_filter("manage_edit-{$pt}_sortable_columns", function ($columns) {
            $columns['menu_order'] = 'menu_order';
            return $columns;
        });
    }
});


/**
 * 8) Add bulk actions for order management (ALL supported post types)
 * PATCH: apply to every page-attributes-supported post type, not just post/page.
 */
add_filter('bulk_actions-edit-post', 'universal_order_add_bulk_actions');
add_filter('bulk_actions-edit-page', 'universal_order_add_bulk_actions');

add_action('admin_init', function () {
    $post_types = get_post_types(['public' => true], 'names');
    foreach ($post_types as $pt) {
        if (in_array($pt, ['post', 'page'], true)) continue;
        if (!post_type_supports($pt, 'page-attributes')) continue;

        add_filter("bulk_actions-edit-{$pt}", 'universal_order_add_bulk_actions');
    }
});

function universal_order_add_bulk_actions($bulk_actions) {
    if (!function_exists('get_current_screen')) return $bulk_actions;
    $screen = get_current_screen();
    if ($screen && !empty($screen->post_type) && post_type_supports($screen->post_type, 'page-attributes')) {
        $bulk_actions['reset_order']   = 'Reset Order';
        $bulk_actions['reverse_order'] = 'Reverse Order';
    }
    return $bulk_actions;
}


/**
 * 9) Handle bulk actions (ALL supported post types)
 */
add_filter('handle_bulk_actions-edit-post', 'universal_order_handle_bulk_actions', 10, 3);
add_filter('handle_bulk_actions-edit-page', 'universal_order_handle_bulk_actions', 10, 3);

add_action('admin_init', function () {
    $post_types = get_post_types(['public' => true], 'names');
    foreach ($post_types as $pt) {
        if (in_array($pt, ['post', 'page'], true)) continue;
        if (!post_type_supports($pt, 'page-attributes')) continue;

        add_filter("handle_bulk_actions-edit-{$pt}", 'universal_order_handle_bulk_actions', 10, 3);
    }
});

function universal_order_handle_bulk_actions($sendback, $doaction, $post_ids) {
    if ($doaction !== 'reset_order' && $doaction !== 'reverse_order') {
        return $sendback;
    }

    if (!function_exists('get_current_screen')) return $sendback;
    $screen = get_current_screen();
    if (!$screen || empty($screen->post_type)) return $sendback;

    $args = [
        'post_type'      => $screen->post_type,
        'posts_per_page' => -1,
        'post_status'    => ['publish', 'draft', 'pending', 'future', 'private'],
        'orderby'        => $doaction === 'reverse_order' ? 'menu_order' : 'date',
        'order'          => $doaction === 'reverse_order' ? 'DESC' : 'ASC',
        'fields'         => 'ids',
    ];
    $all_ids = get_posts($args);

    global $wpdb;
    foreach ($all_ids as $index => $id) {
        $wpdb->update(
            $wpdb->posts,
            ['menu_order' => (int) $index],
            ['ID' => (int) $id],
            ['%d'],
            ['%d']
        );
        clean_post_cache((int) $id);
    }

    $sendback = add_query_arg('bulk_order_updated', count($all_ids), $sendback);
    return $sendback;
}


/**
 * 10) Display admin notice for bulk actions
 */
add_action('admin_notices', function () {
    if (!empty($_REQUEST['bulk_order_updated']) && !empty($_REQUEST['_wp_http_referer'])) {
        $count = (int) $_REQUEST['bulk_order_updated'];
        echo '<div class="notice notice-success is-dismissible"><p>';
        echo sprintf('Order updated for %d item%s.', $count, $count !== 1 ? 's' : '');
        echo '</p></div>';
        ?>
        <script type="text/phast">jQuery(function(){if(window.history&&window.history.replaceState){var url=window.location.href;url=url.replace(/[?&]bulk_order_updated=[^&]+/,'');url=url.replace(/&&/,'&').replace(/\?&/,'?');if(url.slice(-1)==='?'||url.slice(-1)==='&')url=url.slice(0,-1);window.history.replaceState({},document.title,url);}});</script>
        <?php
    }
});


/**
 * 11) Add quick edit support for menu order
 */
add_action('quick_edit_custom_box', function ($column_name, $post_type) {
    if ($column_name !== 'menu_order') return;
    if (!post_type_supports($post_type, 'page-attributes')) return;
    ?>
    <fieldset class="inline-edit-col-left">
        <div class="inline-edit-col">
            <label>
                <span class="title">Order</span>
                <span class="input-text-wrap">
                    <input type="number" name="menu_order" class="menu_order" value="">
                </span>
            </label>
        </div>
    </fieldset>
    <?php
}, 10, 2);


/**
 * 12) Save quick edit menu order
 * PATCH: do NOT call wp_update_post() in save_post (prevents recursion + slow chains)
 */
add_action('save_post', function ($post_id) {

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    // Only handle when field is present
    if (!isset($_POST['menu_order'])) return;

    // Quick Edit includes _inline_edit nonce
    if (isset($_POST['_inline_edit']) && !wp_verify_nonce($_POST['_inline_edit'], 'inlineeditnonce')) {
        return;
    }

    $new_order = (int) $_POST['menu_order'];

    global $wpdb;
    $wpdb->update(
        $wpdb->posts,
        ['menu_order' => $new_order],
        ['ID' => (int) $post_id],
        ['%d'],
        ['%d']
    );
    clean_post_cache((int) $post_id);

}, 10, 1);
				
			

fluid-font-clamp-calculator - v.4

mask-curver - v2.0.1

apple-liquid-glass

There are 2 versions below. The first is more refractive glass like than the second, but try them out.

Note that the CSS at the top before adding the SVG script should be added to Custom CSS for the element/container.

				
					// Code 1
// CSS
selector {
  backdrop-filter: url(#liquid-prism-intense);
  -webkit-backdrop-filter: url(#liquid-prism-intense);
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 50px;
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}
selector:hover {
  transform: scale(1.02);
}

// Add to HTML Widget
<svg width="0" height="0" style="position: absolute;">
  <defs>
    <filter id="liquid-prism-intense" x="0%" y="0%" width="100%" height="100%" filterUnits="objectBoundingBox">
      
      <feTurbulence 
        type="fractalNoise" 
        baseFrequency="0.001 0.005" 
        numOctaves="1" 
        seed="17" 
        result="turbulence" 
      />

      <feComponentTransfer in="turbulence" result="mapped">
        <feFuncR type="gamma" amplitude="1" exponent="10" offset="0.5" />
        <feFuncG type="gamma" amplitude="0" exponent="1" offset="0" />
        <feFuncB type="gamma" amplitude="0" exponent="1" offset="0.5" />
      </feComponentTransfer>

      <feGaussianBlur in="turbulence" stdDeviation="3" result="softMap" />

      <feSpecularLighting 
        in="softMap" 
        surfaceScale="5" 
        specularConstant="1" 
        specularExponent="100" 
        lighting-color="white" 
        result="specLight"
      >
        <fePointLight x="-200" y="-200" z="300" />
      </feSpecularLighting>

      <feComposite 
        in="specLight" 
        operator="arithmetic" 
        k1="0" k2="1" k3="1" k4="0" 
        result="litImage" 
      />

      <feDisplacementMap 
        in="SourceGraphic" 
        in2="softMap" 
        scale="200" 
        xChannelSelector="R" 
        yChannelSelector="G" 
      />

    </filter>
  </defs>
</svg>
				
			
				
					// Code 2
// CSS
selector {
  backdrop-filter: url(#liquid-prism-intense2);
  -webkit-backdrop-filter: url(#liquid-prism-intense2);
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 50px;
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}
selector:hover {
  transform: scale(1.02);
}

// Add to HTML Widget
<svg width="0" height="0" style="position: absolute;">
  <defs>
    <filter id="liquid-prism-intense2" x="-50%" y="-50%" width="200%" height="200%">
      <feTurbulence baseFrequency="0.012 0.018" numOctaves="3" result="turbulence" seed="1" type="fractalNoise" />
      <feColorMatrix in="turbulence" type="saturate" values="0" result="grayscale" />
      <feDisplacementMap in="SourceGraphic" in2="grayscale" scale="30" result="displaced1" />
      <feTurbulence baseFrequency="0.025 0.035" numOctaves="2" result="turbulence2" seed="2" type="fractalNoise" />
      <feColorMatrix in="turbulence2" type="saturate" values="0" result="grayscale2" />
      <feDisplacementMap in="displaced1" in2="grayscale2" scale="20" result="displaced2" />
      <feOffset in="displaced2" dx="-1" dy="0" result="offsetR" />
      <feOffset in="displaced2" dx="1" dy="0" result="offsetB" />
      <feColorMatrix in="offsetR" type="matrix" result="redChannel"
        values="1 0 0 0 0
                0 0 0 0 0
                0 0 0 0 0
                0 0 0 1 0" />
      <feColorMatrix in="displaced2" type="matrix" result="greenChannel"
        values="0 0 0 0 0
                0 1 0 0 0
                0 0 0 0 0
                0 0 0 1 0" />
      <feColorMatrix in="offsetB" type="matrix" result="blueChannel"
        values="0 0 0 0 0
                0 0 0 0 0
                0 0 1 0 0
                0 0 0 1 0" />
      <feComposite in="redChannel" in2="greenChannel" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" result="rg" />
      <feComposite in="rg" in2="blueChannel" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" result="rgb" />
      <feGaussianBlur in="rgb" stdDeviation="0.8" />
    </filter>
  </defs>
</svg>
				
			

quote-form

				
					/* Code to add the Quote Selector */

<!DOCTYPE html>
<html lang="en">
<head>
    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Design Quote Calculator</title>
    <script type="text/phast" src="https://cdn.tailwindcss.com"></script>
    <style>body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background-color:#f8fafc;}.calculator-container{max-width:800px;margin:0 auto;background-color:white;border-radius:12px;box-shadow:0 10px 25px rgba(0,0,0,0.1);}.option-button{background-color:#f1f5f9;border:2px solid transparent;transition:all 0.3s ease;}.option-button:hover{background-color:#e2e8f0;}.option-button.selected{background-color:#ff0050;color:white;border-color:#ff0050;}.option-button.selected *{color:white;}.option-button.selected .icon-bg{background-color:black !important;}.primary-button{background-color:#ff0050;transition:all 0.3s ease;}.primary-button:hover{background-color:#e5004a;transform:translateY(-2px);}.result-container{border:2px dashed #e2e8f0;background-color:#f8fafc;}input[type="number"]{-moz-appearance:textfield;}input::-webkit-outer-spin-button,input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0;}input[type=date],input[type=email],input[type=number],input[type=password],input[type=search],input[type=tel],input[type=text],input[type=url],select,textarea{width:100px;border:1px solid #666;border-radius:3px;padding:.5rem 1rem;transition:all .3s;}</style>
</head>
<body class="py-10 px-4">
    <div class="calculator-container p-8">
        <h1 class="text-3xl font-bold text-center mb-2">Web Design Quote Calculator</h1>
        <p class="text-gray-600 text-center mb-8">Select your requirements to get an estimated quote</p>
        
        <div class="space-y-8">
            
            <div class="border-b pb-6">
                <h2 class="text-xl font-semibold mb-4">Website Options</h2>
                
                
                <div id="base_website" class="option-button p-4 rounded-lg cursor-pointer mb-4 selected">
                    <div class="flex items-center">
                        <div class="icon-bg bg-blue-100 p-3 rounded-full mr-4">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                        </div>
                        <div>
                            <p class="font-medium">Base Website Package</p>
                            <p class="text-sm text-gray-600">Includes responsive design, contact form</p>
                        </div>
                        <div class="ml-auto">
                            <p class="font-bold">$1,500</p>
                        </div>
                    </div>
                </div>
                
                
                <div id="pages-container" class="mt-4">
                    <label for="page_count" class="block text-sm font-medium text-gray-700 mb-2">Number of Pages:</label>
                    <div class="flex items-center">
                        <button id="decrease_pages" class="bg-gray-200 px-3 py-2 rounded-l-lg hover:bg-gray-300">-</button>
                        <input type="number" id="page_count" min="5" value="5" class="w-16 text-center border-y border-gray-200 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <button id="increase_pages" class="bg-gray-200 px-3 py-2 rounded-r-lg hover:bg-gray-300">+</button>
                        <span class="ml-4 text-sm text-gray-600">($225 per additional page)</span>
                    </div>
                </div>
            </div>
            
            
            <div>
                <h2 class="text-xl font-semibold mb-4">Additional Features</h2>
                <p class="text-gray-600 mb-4">Select the features you need for your website</p>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    
                    <div id="ecommerce" class="option-button p-4 rounded-lg cursor-pointer">
                        <div class="flex items-center">
                            <div class="icon-bg bg-blue-100 p-3 rounded-full mr-3">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
                                </svg>
                            </div>
                            <div>
                                <p class="font-medium">E-commerce Functionality</p>
                                <p class="text-sm text-gray-600">Online store with payment processing</p>
                                <p class="font-bold mt-1">+ $2,000</p>
                            </div>
                        </div>
                    </div>
                    
                    
                    <div id="seo" class="option-button p-4 rounded-lg cursor-pointer">
                        <div class="flex items-center">
                            <div class="icon-bg bg-blue-100 p-3 rounded-full mr-3">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" />
                                </svg>
                            </div>
                            <div>
                                <p class="font-medium">SEO Optimization</p>
                                <p class="text-sm text-gray-600">On-page SEO and keyword optimization</p>
                                <p id="seo_price" class="font-bold mt-1">+ $800</p>
                                <p id="seo_note" class="text-xs text-gray-500 mt-1 hidden">+$100 per additional page</p>
                            </div>
                        </div>
                    </div>
                    
                    
                    <div id="performance" class="option-button p-4 rounded-lg cursor-pointer">
                        <div class="flex items-center">
                            <div class="icon-bg bg-blue-100 p-3 rounded-full mr-3">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                                </svg>
                            </div>
                            <div>
                                <p class="font-medium">Performance Optimization</p>
                                <p class="text-sm text-gray-600">Speed and loading time improvements</p>
                                <p class="font-bold mt-1">+ $600</p>
                            </div>
                        </div>
                    </div>
                    
                    
                    <div id="makeover" class="option-button p-4 rounded-lg cursor-pointer">
                        <div class="flex items-center">
                            <div class="icon-bg bg-blue-100 p-3 rounded-full mr-3">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                                </svg>
                            </div>
                            <div>
                                <p class="font-medium">Investigation/Makeover</p>
                                <p class="text-sm text-gray-600">Analysis and redesign of existing site</p>
                                <p class="font-bold mt-1">+ $1,200</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            
            <div id="results-section" class="result-container p-6 rounded-lg mt-8">
                <h2 class="text-xl font-semibold mb-4">Your Estimated Quote</h2>
                
                <div class="flex flex-col md:flex-row justify-between items-center">
                    <div>
                        <p class="text-gray-600">Based on your selections:</p>
                        <ul id="selected-options" class="list-disc ml-5 mt-2 text-gray-700">
                            <li>Base Website Package: $1,500</li>
                        </ul>
                    </div>
                    <div class="bg-gray-100 p-6 rounded-lg mt-4 md:mt-0">
                        <p class="text-gray-600 mb-1">Estimated Cost:</p>
                        <p id="estimate_cost" class="text-3xl font-bold text-gray-900">$1,500</p>
                    </div>
                </div>
                
                <div class="mt-6 text-center">
                    <p class="text-gray-600 text-sm">This is an estimate. Contact us for a detailed quote.</p>
                </div>
            </div>
        </div>
    </div>

    <script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const basePrice=1500;const baseSeoPrice=800;const additionalPagePrice=225;const additionalSeoPerPage=100;const basePageCount=5;const options={base_website:{price:basePrice,label:'Base Website Package'},ecommerce:{price:2000,label:'E-commerce Functionality'},seo:{price:baseSeoPrice,label:'SEO Optimization',basePrice:baseSeoPrice},performance:{price:600,label:'Performance Optimization'},makeover:{price:1200,label:'Investigation/Makeover'}};const selectedOptions={base_website:{...options.base_website}};let currentPageCount=5;function updateSeoPrice(){const additionalPages=Math.max(0,currentPageCount-basePageCount);const additionalSeoCost=additionalPages*additionalSeoPerPage;const totalSeoPrice=baseSeoPrice+additionalSeoCost;document.getElementById('seo_price').textContent=`+ $${totalSeoPrice}`;const seoNote=document.getElementById('seo_note');if(additionalPages>0){seoNote.classList.remove('hidden');}else{seoNote.classList.add('hidden');}
options.seo.price=totalSeoPrice;if(selectedOptions.seo){selectedOptions.seo.price=totalSeoPrice;}}
function updateQuote(){let totalPrice=0;const selectedOptionsList=document.getElementById('selected-options');selectedOptionsList.innerHTML='';let additionalPages=Math.max(0,currentPageCount-basePageCount);let additionalPagesCost=additionalPages*additionalPagePrice;if(selectedOptions.base_website){selectedOptionsList.innerHTML+=`<li>Base Website Package: $${basePrice}</li>`;totalPrice+=basePrice;if(additionalPages>0){selectedOptionsList.innerHTML+=`<li>${additionalPages} Additional Pages: $${additionalPagesCost}</li>`;totalPrice+=additionalPagesCost;}}
updateSeoPrice();for(const[id,option]of Object.entries(selectedOptions)){if(id==='base_website')continue;totalPrice+=option.price;if(id==='seo'&&additionalPages>0){const additionalSeoCost=additionalPages*additionalSeoPerPage;selectedOptionsList.innerHTML+=`<li>${option.label}: $${baseSeoPrice} + $${additionalSeoCost} (${additionalPages} additional pages)</li>`;}else{selectedOptionsList.innerHTML+=`<li>${option.label}: $${option.price}</li>`;}}
if(selectedOptionsList.innerHTML===''){selectedOptionsList.innerHTML='<li>No options selected</li>';}
document.getElementById('estimate_cost').textContent='$'+totalPrice.toLocaleString();}
document.querySelectorAll('.option-button').forEach(button=>{button.addEventListener('click',function(){const optionId=this.id;this.classList.toggle('selected');if(this.classList.contains('selected')){selectedOptions[optionId]={...options[optionId]};if(optionId==='seo'&&currentPageCount>basePageCount){document.getElementById('seo_note').classList.remove('hidden');}}else{delete selectedOptions[optionId];if(optionId==='seo'){document.getElementById('seo_note').classList.add('hidden');}}
updateQuote();});});document.getElementById('decrease_pages').addEventListener('click',function(){const pageCountInput=document.getElementById('page_count');if(parseInt(pageCountInput.value)>5){pageCountInput.value=parseInt(pageCountInput.value)-1;currentPageCount=parseInt(pageCountInput.value);updateQuote();}});document.getElementById('increase_pages').addEventListener('click',function(){const pageCountInput=document.getElementById('page_count');pageCountInput.value=parseInt(pageCountInput.value)+1;currentPageCount=parseInt(pageCountInput.value);updateQuote();});document.getElementById('page_count').addEventListener('change',function(){if(parseInt(this.value)<5){this.value=5;}
currentPageCount=parseInt(this.value);updateQuote();});updateQuote();});</script>
<script type="text/phast">(function(){function c(){var b=a.contentDocument||a.contentWindow.document;if(b){var d=b.createElement('script');d.innerHTML="window.__CF$cv$params={r:'9433dbbd476ef77c',t:'MTc0NzgyODI0OS4wMDAwMDA='};var a=document.createElement('script');a.nonce='';a.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js';document.getElementsByTagName('head')[0].appendChild(a);";b.getElementsByTagName('head')[0].appendChild(d)}}if(document.body){var a=document.createElement('iframe');a.height=1;a.width=1;a.style.position='absolute';a.style.top=0;a.style.left=0;a.style.border='none';a.style.visibility='hidden';document.body.appendChild(a);if('loading'!==document.readyState)c();else if(window.addEventListener)document.addEventListener('DOMContentLoaded',c);else{var e=document.onreadystatechange||function(){};document.onreadystatechange=function(b){e(b);'loading'!==document.readyState&&(document.onreadystatechange=e,c())}}}})();</script></body>
</html>
				
			
				
					/* Code to link Quote Fields to Elementor Form */

<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const form=document.querySelector('form.elementor-form');if(!form)return;function updateFormFields(){const baseWebsite=document.getElementById('base_website')?.classList.contains('selected')?'Yes':'No';const pageCount=document.getElementById('page_count')?.value||'';const ecommerce=document.getElementById('ecommerce')?.classList.contains('selected')?'Yes':'No';const seo=document.getElementById('seo')?.classList.contains('selected')?'Yes':'No';const performance=document.getElementById('performance')?.classList.contains('selected')?'Yes':'No';const makeover=document.getElementById('makeover')?.classList.contains('selected')?'Yes':'No';const estimateCost=document.getElementById('estimate_cost')?.textContent.replace('$','').trim()||'';const additionalPages=Math.max(0,parseInt(pageCount)-5);const additionalPageCost=additionalPages*225;const additionalSeoCost=additionalPages*100;const set=(name,val)=>{const field=form.querySelector(`[name="form_fields[${name}]"]`);if(field)field.value=val;};set('base_website',baseWebsite);set('page_count',pageCount);set('ecommerce',ecommerce);set('seo',seo);set('performance',performance);set('makeover',makeover);set('estimate_cost',estimateCost);const breakdown=[];breakdown.push(`Page Count: ${pageCount}`);breakdown.push(`Estimate Cost: $${estimateCost}`);if(baseWebsite==='Yes')breakdown.push(`Base Website Package: $1500`);if(baseWebsite==='Yes'&&additionalPages>0){breakdown.push(`${additionalPages} Additional Pages: $${additionalPageCost}`);}
if(makeover==='Yes')breakdown.push(`Investigation/Makeover: $1200`);if(seo==='Yes'){breakdown.push(`SEO Optimization: $800${additionalPages > 0 ? `+$${additionalSeoCost}(${additionalPages}additional pages)` : ''}`);}
if(performance==='Yes')breakdown.push(`Performance Optimization: $600`);if(ecommerce==='Yes')breakdown.push(`E-commerce Functionality: $2000`);set('detailed_breakdown',breakdown.join('\n'));}
document.querySelectorAll('.option-button, #increase_pages, #decrease_pages').forEach(el=>{el.addEventListener('click',()=>setTimeout(updateFormFields,50));});document.getElementById('page_count')?.addEventListener('input',()=>setTimeout(updateFormFields,50));form.addEventListener('submit',function(e){updateFormFields();});updateFormFields();});</script>
				
			

trigger-scroll

				
					<style>@media (min-width:768px){.fade-text{position:absolute !important;top:0;left:0;width:100%;opacity:0;transform:translateY(30px);transition:none;z-index:1;pointer-events:none;}.fade-text.active{pointer-events:auto;z-index:2;}.fade-up{animation:fadeUp 0.7s ease-out forwards;}.fade-out{animation:fadeOutUp 0.3s ease-in forwards;}@keyframes fadeUp{from{opacity:0;transform:translateY(30px);}to{opacity:1;transform:translateY(0);}}@keyframes fadeOutUp{from{opacity:1;transform:translateY(0);}to{opacity:0;transform:translateY(-15px);}}}</style>

<script type="text/phast">document.addEventListener("DOMContentLoaded",function(){if(window.matchMedia("(min-width: 768px)").matches){const triggers=document.querySelectorAll('.scroll-section');const texts=document.querySelectorAll('.fade-text');let currentActiveId=null;function updateVisibility(){const viewportHeight=window.innerHeight;triggers.forEach(trigger=>{const rect=trigger.getBoundingClientRect();const id=trigger.getAttribute('data-show');const el=document.getElementById(id);const topTrigger=viewportHeight*0.5;const bottomTrigger=viewportHeight*0.55;const shouldBeVisible=rect.top<=topTrigger&&rect.bottom>=bottomTrigger;if(shouldBeVisible){if(currentActiveId!==id){if(currentActiveId){const prev=document.getElementById(currentActiveId);prev?.classList.remove('fade-up');prev?.classList.add('fade-out');prev?.addEventListener('animationend',()=>{prev.classList.remove('active','fade-out');},{once:true});}
el?.classList.add('active','fade-up');currentActiveId=id;}}else if(currentActiveId===id){el?.classList.remove('fade-up');el?.classList.add('fade-out');el?.addEventListener('animationend',()=>{el.classList.remove('active','fade-out');},{once:true});currentActiveId=null;}});}
window.addEventListener('scroll',updateVisibility);window.addEventListener('resize',updateVisibility);updateVisibility();texts.forEach(el=>{el.classList.remove('active','fade-up','fade-out');});}});</script>
				
			

stop-lazy-load-preload

				
					// Disable lazy load AND preload specific image IDs
add_filter('wp_img_tag_add_loading_attr', 'custom_disable_lazyload_for_lcp_images', 10, 3);
add_filter('wp_preload_resources', 'custom_preload_lcp_images');

// Define your LCP image attachment IDs here
function get_lcp_image_ids() {
    return [36792, 36791]; // Add or remove IDs as needed
}

// 1. Disable Lazy Loading for LCP images
function custom_disable_lazyload_for_lcp_images($value, $image, $context) {
    if (in_array($context, ['the_content', 'widget', 'elementor', 'post'])) {
        foreach (get_lcp_image_ids() as $image_id) {
            $image_url = wp_get_attachment_image_url($image_id, 'large');
            if ($image_url && strpos($image, ' src="' . $image_url . '"') !== false) {
                return false;
            }
        }
    }
    return $value;
}

// 2. Preload the same images in the <head>
function custom_preload_lcp_images($hints) {
    if (is_front_page() || is_singular()) {
        foreach (get_lcp_image_ids() as $image_id) {
            $image_url = wp_get_attachment_image_url($image_id, 'large');
            $mime = get_post_mime_type($image_id);
            $type = $mime ?: 'image/jpeg'; // Safer fallback
            if ($image_url) {
                $hints[] = [
                    'href' => $image_url,
                    'as'   => 'image',
                    'type' => $type,
                ];
            }
        }
    }
    return $hints;
}
				
			

pageauditor

				
					/**
 * Copyright (c) 2025 Imran Siddiq. All rights reserved.
 *
 * This code is proprietary and confidential. Unauthorized copying, reproduction, redistribution, modification, public display, 
 * or resale of this code, in whole or in part, is strictly prohibited without prior written permission from the creator, Imran Siddiq.
 *
 * For licensing inquiries, contact: info@websquadron.co.uk.
 */

// IMPORTANT NOTE: Clicking on the Audit Pane Title 'Built Audit' allows you to drag the pane.
// This tool is to be used when Editing with Elementor
// Using the Audit when viewing in Preview will show extra WordPress issues that should not be used.

function add_landmark_audit_guide() {
    static $landmark_audit_loaded = false;
    if ($landmark_audit_loaded) return;
    $landmark_audit_loaded = true;

    // --- Access control: must be logged in, be Admin/Editor AND be on allow list.
    if ( ! is_user_logged_in() ) return;

    $user   = wp_get_current_user();
    $uid    = (int) $user->ID;
    $uemail = strtolower($user->user_email);
    $ulogin = strtolower(
$user->user_login);
    // 1) Role gate (Admin/Editor)
    $has_role = current_user_can('manage_options') || current_user_can('edit_others_pages');
    if ( ! $has_role ) return;

    // 2) Optional block-list (deny even if otherwise allowed)
    $blocked_emails = [
        'info@websquadron.co.uk',
        // 'someone@domain.com',
    ];
    if ( in_array($uemail, array_map('strtolower',$blocked_emails), true) ) return;

    // 3) Allow-list: only these users can see the Audit
    $allow_emails = [
        'teammate@yourdomain.com',
        'teammate@yourdomain.com',
        // add more…
    ];
    $allow_ids = [1, 23]; // numeric WP user IDs
    $allow_usernames = ['alice','bob'];

    $allowed = in_array($uemail, array_map('strtolower',$allow_emails), true)
            || in_array($uid, $allow_ids, true)
            || in_array($ulogin, array_map('strtolower',$allow_usernames), true);

    if ( ! $allowed ) return;

	echo "";
    ?>
    <script type="text/phast">(function(){if(typeof window==='undefined'||typeof document==='undefined')return;if(window.top!==window.self)return;if(window.__AUDIT_GUIDE_INIT__)return;window.__AUDIT_GUIDE_INIT__=true;const OPEN=(window.__AUDIT_OPEN__=window.__AUDIT_OPEN__||new Map());let INTERACTING=false;let lastSignature='';let mo=null,heartbeat=null,debTimer=null,resizeHandler=null,topMO=null;function stopObserver(){try{if(mo)mo.disconnect();}catch(e){}
mo=null;try{if(heartbeat)clearInterval(heartbeat);}catch(e){}
heartbeat=null;if(debTimer){clearTimeout(debTimer);debTimer=null;}
if(resizeHandler){window.removeEventListener('resize',resizeHandler);resizeHandler=null;}
try{if(topMO)topMO.disconnect();}catch(e){}
topMO=null;}
const HIDE_KEY='__AUDIT_HIDE_V1__';const HIDDEN=new Set();try{const saved=localStorage.getItem(HIDE_KEY);if(saved)JSON.parse(saved).forEach(k=>HIDDEN.add(k));}catch(_){}
function isHidden(issueKey){return HIDDEN.has(issueKey);}
function setHidden(issueKey,hidden){if(hidden)HIDDEN.add(issueKey);else HIDDEN.delete(issueKey);try{localStorage.setItem(HIDE_KEY,JSON.stringify(Array.from(HIDDEN)));}catch(_){}}
let __CLAMP_CACHE__={time:0,info:null};const btn=document.createElement('button');btn.type='button';btn.textContent='Audit';Object.assign(btn.style,{position:'fixed',bottom:'30px',right:'30px',zIndex:2147483646,padding:'7px 12px',lineHeight:'normal',background:'#e53935',color:'#fff',border:'none',borderRadius:'3px',cursor:'grab',fontSize:'14px',boxShadow:'0 2px 8px rgba(0,0,0,.25)',userSelect:'none'});btn.setAttribute('aria-label','Open build audit panel');btn.setAttribute('aria-pressed','false');btn.setAttribute('title','Audit');btn.setAttribute('aria-haspopup','dialog');btn.setAttribute('aria-controls','audit-panel');btn.setAttribute('data-audit-btn','');btn.style.WebkitTapHighlightColor='transparent';btn.style.setProperty('outline','none','important');btn.style.setProperty('box-shadow','0 2px 6px rgba(0,0,0,.3)','important');const auditBtnStyle=document.createElement('style');auditBtnStyle.textContent=`
  [data-audit-btn] { outline: none !important; }
  [data-audit-btn]:focus,
  [data-audit-btn]:focus-visible {
    outline: none !important;
    box-shadow: 0 2px 6px rgba(0,0,0,.3) !important;
  }
`;document.head.appendChild(auditBtnStyle);const panel=document.createElement('div');Object.assign(panel.style,{position:'fixed',bottom:'70px',right:'20px',zIndex:2147483645,width:'600px',minWidth:'360px',maxWidth:'min(900px,92vw)',maxHeight:'72vh',overflow:'auto',background:'#fff',color:'#222',border:'1px solid #e5e5e5',borderRadius:'10px',padding:'12px',display:'none',font:'13px/1.45 -apple-system, Segoe UI, Roboto, Arial, sans-serif',boxShadow:'0 12px 36px rgba(0,0,0,.28)'});const title=document.createElement('div');title.textContent='Build Audit';Object.assign(title.style,{fontWeight:700,marginBottom:'8px',cursor:'move',padding:'4px 2px',borderBottom:'1px solid #f0f0f0'});panel.id='audit-panel';panel.setAttribute('role','dialog');panel.setAttribute('aria-modal','false');panel.setAttribute('aria-labelledby','audit-title');title.id='audit-title';const infoBtn=document.createElement('button');infoBtn.type='button';infoBtn.textContent='Info';Object.assign(infoBtn.style,{marginLeft:'auto',fontSize:'12px',lineHeight:'1',padding:'4px 8px',border:'1px solid #e2e2e2',borderRadius:'6px',background:'#f7f7f7',color:'#000',cursor:'pointer'});infoBtn.setAttribute('aria-haspopup','dialog');infoBtn.style.background='#f7f7f7';infoBtn.style.color='#000';const titleWrap=document.createElement('div');Object.assign(titleWrap.style,{display:'flex',alignItems:'center',gap:'8px'});titleWrap.appendChild(title);titleWrap.appendChild(infoBtn);const content=document.createElement('div');panel.appendChild(titleWrap);const infoBackdrop=document.createElement('div');Object.assign(infoBackdrop.style,{position:'fixed',inset:0,background:'rgba(0,0,0,.35)',zIndex:2147483647,display:'none'});infoBackdrop.setAttribute('aria-hidden','true');const infoPane=document.createElement('div');infoPane.id='audit-info-pane';infoPane.setAttribute('role','dialog');infoPane.setAttribute('aria-modal','true');infoPane.setAttribute('aria-labelledby','audit-info-title');Object.assign(infoPane.style,{position:'fixed',zIndex:2147483648,maxWidth:'min(900px, 92vw)',width:'720px',maxHeight:'95vh',overflow:'auto',left:'50%',top:'50%',transform:'translate(-50%, -50%)',background:'#fff',color:'#222',border:'1px solid #e5e5e5',borderRadius:'12px',boxShadow:'0 20px 60px rgba(0,0,0,.35)',display:'none'});infoPane.style.position='fixed';infoPane.style.top='0';infoPane.style.left='0';infoPane.style.right='auto';infoPane.style.transform='none';infoPane.style.setProperty('width','75vw','important');infoPane.style.setProperty('max-width','none','important');infoPane.style.height='100dvh';infoPane.style.maxHeight='100dvh';infoPane.style.overflow='auto';infoPane.style.boxSizing='border-box';const infoHead=document.createElement('div');infoHead.id='audit-info-title';infoHead.textContent='Build Audit — What each issue means & how to test/fix';Object.assign(infoHead.style,{fontWeight:700,padding:'12px 14px',borderBottom:'1px solid #efefef',position:'sticky',top:0,background:'#fff',zIndex:1});const infoX=document.createElement('button');infoX.type='button';infoX.setAttribute('aria-label','Close information panel');infoX.innerHTML='&times;';Object.assign(infoX.style,{position:'absolute',top:'8px',right:'10px',width:'32px',height:'32px',display:'inline-flex',alignItems:'center',justifyContent:'center',background:'transparent',border:'none',fontSize:'22px',lineHeight:'1',color:'#000',cursor:'pointer'});infoX.addEventListener('click',(e)=>{e.stopPropagation();closeInfo();});infoHead.appendChild(infoX);const infoBody=document.createElement('div');Object.assign(infoBody.style,{padding:'12px 14px',fontSize:'13px',lineHeight:'1.55'});const infoAccStyle=document.createElement('style');infoAccStyle.textContent=`
  #audit-info-pane .info-acc { margin:7px 0; border:1px solid #efefef; border-radius:3px; overflow:hidden; }
  #audit-info-pane .info-acc-head {
    all: unset; display:flex; align-items:center; gap:6px; width:100%;
    padding:5px 12px; cursor:pointer; background:#fafafa; border-bottom:1px solid #f0f0f0;
    font-size:13px; font-weight:700; line-height:1.45;
  }
#audit-info-pane .info-acc-head:focus,
#audit-info-pane .info-acc-head:focus-visible { outline: none !important; }
  #audit-info-pane .info-acc-head .chev { display:inline-block; transition:transform .18s ease; }
  #audit-info-pane .info-acc-head[aria-expanded="true"] .chev { transform: rotate(90deg); }
  #audit-info-pane .info-acc-body { padding:10px 12px; background:#fff; }
  #audit-info-pane .info-acc-body ul { margin:0; padding-left:18px; }
  #audit-info-pane .info-acc-body li { margin:6px 0; }
`;document.head.appendChild(infoAccStyle);const section=(title,items)=>{const key='info-'+title.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');return`
    <section class="info-acc" data-key="${key}">
      <button type="button" class="info-acc-head" aria-expanded="false">
        <span class="chev" aria-hidden="true">▶</span>
        <span>${title}</span>
      </button>
      <div class="info-acc-body" hidden>
        <ul>
          ${items.map(li => `<li>${li}</li>`).join('')}
        </ul>
      </div>
    </section>`;};const INFO_HTML=`
${section('MAIN: Missing', [
  '<b>What it means:</b> Your page’s primary content is not wrapped in a single <code>&lt;main&gt;</code> region, so assistive tech can’t jump past the header/nav directly to content.',
  '<b>How it checks:</b> Looks for exactly one top-level <code>&lt;main&gt;</code> (or an element with <code>role="main"</code>).',
  '<b>How to test (Elementor):</b> Open the page in Elementor → select the <i>topmost content</i> Container that holds your page content (not the Header template) → if “HTML Tag” isn’t set to <code>main</code>, the issue will appear.',
  '<b>How to fix (Elementor):</b> Select that top content Container → <b>Advanced ▸ HTML Tag ▸</b> choose <code>main</code>. If you don’t see the control, add a short “CSS ID” of <code>main</code> and keep using the Container; the Audit accepts <code>role="main"</code>/<code>#main</code> targets as valid.'
])}
${section('MAIN: Multiple', [
  '<b>What it means:</b> More than one region is marked as the main content. There must be exactly one <code>&lt;main&gt;</code> per page.',
  '<b>How it checks:</b> Counts <code>&lt;main&gt;</code> (and <code>role="main"</code>) elements.',
  '<b>How to test (Elementor):</b> In Navigator, check your top-level Containers. If more than one Container’s “HTML Tag” is set to <code>main</code>, the issue appears.',
  '<b>How to fix (Elementor):</b> Keep the real content wrapper as <code>main</code>. For any other Container set to <code>main</code>, change <b>Advanced ▸ HTML Tag</b> to <code>div</code>/<code>section</code>.'
])}
${section('HEADER: Missing', [
  '<b>What it means:</b> No site-level <code>&lt;header&gt;</code> landmark was found.',
  '<b>How it checks:</b> Looks for a single top-level <code>&lt;header&gt;</code> region.',
  '<b>How to test (Elementor):</b> If you built the header <i>inside the page</i>, select its outer Container and see if “HTML Tag” is <code>header</code>. If you use a Theme Builder Header, it will be outside the page canvas and typically passes by default.',
  '<b>How to fix (Elementor):</b> For page-embedded headers: select the header’s outer Container → <b>Advanced ▸ HTML Tag ▸</b> <code>header</code>. For Theme Builder: ensure the template’s outer wrapper uses <code>header</code> (Elementor usually sets this automatically).'
])}
${section('HEADER: Multiple', [
  '<b>What it means:</b> More than one top-level <code>&lt;header&gt;</code> landmark exists.',
  '<b>How it checks:</b> Counts top-level <code>&lt;header&gt;</code> elements.',
  '<b>How to test (Elementor):</b> In Navigator, if you placed a “header-like” section inside the page as well as using a Theme Builder Header, you may effectively have two.',
  '<b>How to fix (Elementor):</b> Keep the Theme Builder Header as the only <code>header</code>. Change any page-level “header” Container’s <b>HTML Tag</b> to <code>div</code>/<code>section</code>.'
])}
${section('FOOTER: Missing', [
  '<b>What it means:</b> No site-level <code>&lt;footer&gt;</code> landmark was found.',
  '<b>How it checks:</b> Looks for a top-level <code>&lt;footer&gt;</code> region.',
  '<b>How to test (Elementor):</b> If your footer is built on the page, select its outer Container and check “HTML Tag.” If you use Theme Builder, the footer is typically correct by default.',
  '<b>How to fix (Elementor):</b> For page-embedded footers: set the outer Container’s <b>HTML Tag</b> to <code>footer</code>. For Theme Builder: ensure the footer template’s wrapper is a <code>footer</code>.'
])}
${section('FOOTER: Multiple', [
  '<b>What it means:</b> More than one <code>&lt;footer&gt;</code> landmark exists.',
  '<b>How it checks:</b> Counts top-level <code>&lt;footer&gt;</code> elements.',
  '<b>How to test (Elementor):</b> Using a Theme Builder Footer plus a page-level “footer section” can create two.',
  '<b>How to fix (Elementor):</b> Keep the Theme Builder Footer as the only <code>footer</code>. Change any page-level “footer” Container’s <b>HTML Tag</b> to <code>div</code>/<code>section</code>.'
])}
${section('HEADINGS: Missing H1', [
  '<b>What it means:</b> The page has no <code>&lt;h1&gt;</code> top heading (the main page title).',
  '<b>How it checks:</b> Looks for at least one <code>H1</code>.',
  '<b>How to test (Elementor):</b> Select your main title Heading widget → in Content panel check “HTML Tag.” If it’s not <code>H1</code>, the issue appears.',
  '<b>How to fix (Elementor):</b> On your main title Heading widget set <b>Content ▸ HTML Tag</b> to <code>H1</code>. Use <code>H2/H3</code> for section titles.'
])}
${section('HEADINGS: Multiple H1', [
  '<b>What it means:</b> There should be exactly one <code>H1</code> per page.',
  '<b>How it checks:</b> Counts all <code>H1</code> elements.',
  '<b>How to test (Elementor):</b> In Navigator, click other Heading widgets and check their “HTML Tag.” If more than one is set to <code>H1</code>, the issue appears.',
  '<b>How to fix (Elementor):</b> Leave the true page title as <code>H1</code>. Change the others: <b>Content ▸ HTML Tag ▸</b> <code>H2</code>/<code>H3</code>.'
])}
${section('HEADINGS: Order skips levels', [
  '<b>What it means:</b> The heading outline jumps (e.g., H1 → H3) or moves backward. Headings should step by 1 level (or stay the same).',
  '<b>How it checks:</b> Compares each heading to the previous one within its section.',
  '<b>How to test (Elementor):</b> In Navigator, select a Heading and verify sequence: main title <code>H1</code>, section titles <code>H2</code>, sub-sections <code>H3</code>, etc.',
  '<b>How to fix (Elementor):</b> For each Heading widget, set <b>Content ▸ HTML Tag</b> so the order flows H1 → H2 → H3 without skipping or going backwards.'
])}
${section('HEADINGS: Content too long', [
  '<b>What it means:</b> A heading should be concise and scannable. If it runs too long, it becomes harder for screen readers and users to parse quickly.',
  '<b>How it checks:</b> Flags headings (h1–h6) where the text length exceeds 12 words or 80 characters.',
  '<b>How to test:</b> In your Elementor page, check the heading widget text. Add a heading that is 12+ words or 80+ characters.',
  '<b>How to fix:</b> Shorten the heading to a clear summary of the section. Move extra detail into a paragraph widget below the heading.'
])}
${section('ACCESSIBILITY: “Skip to content”', [
  '<b>What it means:</b> A keyboard user needs a visible-on-focus link that jumps to the main content.',
  '<b>How it checks:</b> Requires a link early in the tab order pointing to <code>#main</code> (or an element with <code>role="main"</code>) and that it becomes visible on focus.',
  '<b>How to test (Elementor):</b> In Navigator, add an <b>HTML</b> widget as the very first widget on the page and tab to it. If you don’t see a Skip link appear when it receives focus, the issue remains.',
  '<b>How to fix (Elementor):</b> 1) Give your main content Container a <b>CSS ID</b> of <code>main</code> (Advanced ▸ CSS ID). 2) Add an HTML widget at the very top with:<br><code>&lt;a class="skip-link" href="#main"&gt;Skip to content&lt;/a&gt;</code><br>3) In the same HTML widget, add a style block (or use Page ▸ Advanced ▸ Custom CSS in Pro):<br><code>&lt;style&gt;.skip-link{position:absolute;left:-9999px;} .skip-link:focus{left:8px;top:8px;z-index:99999;padding:.5rem 1rem;background:#fff;border:2px solid #000}&lt;/style&gt;</code>'
])}
${section('ACCESSIBILITY: Color contrast (AA) failures', [
  '<b>What it means:</b> Text must be ≥4.5:1 contrast (3:1 if large). Buttons/controls also need ≥3:1 for fills/borders vs surroundings.',
  '<b>How it checks:</b> Computes text vs background and control background/border vs surrounding background.',
  '<b>How to test (Elementor):</b> Pick a Heading/Text/Button → <b>Style</b> and temporarily set a very light text or border color. Reopen the Audit to see the failure.',
  '<b>How to fix (Elementor):</b> Select the widget → <b>Style</b> → adjust Text/Background/Border color until the Audit passes. For Buttons, ensure the fill or border contrasts ≥3:1 against the section background.'
])}
${section('ACCESSIBILITY: Text below 16px', [
  '<b>What it means:</b> Body text under 16px is hard to read for many users.',
  '<b>How it checks:</b> Finds representative elements computed below 16px.',
  '<b>How to test (Elementor):</b> Select a Text Editor/Heading widget → <b>Style ▸ Typography ▸ Size</b> and set 14px; the Audit should flag it.',
  '<b>How to fix (Elementor):</b> Increase <b>Typography ▸ Size</b> to ≥16px. Also check Line-Height for comfortable reading.'
])}
${section('ACCESSIBILITY: Button minimum size (24×24) failures', [
  '<b>What it means:</b> Click/tap targets should be at least 24×24px.',
  '<b>How it checks:</b> Measures visible hit area of links/buttons/icon-only controls.',
  '<b>How to test (Elementor):</b> Select a Button/Icon widget → reduce padding/size until it’s tiny; the Audit will flag it.',
  '<b>How to fix (Elementor):</b> Increase <b>Style ▸ Padding</b> (or Icon Size/Line Height) so the rendered button/hit area is ≥24×24px.'
])}
${section('ACCESSIBILITY: Mobile control spacing (≥12px) failures', [
  '<b>What it means:</b> On small screens, controls need ≥12px clear space between edges.',
  '<b>How it checks:</b> In a narrow viewport, measures minimum spacing between nearby controls (excludes typical menu-item vs menu-item).',
  '<b>How to test (Elementor):</b> Switch to Mobile preview → place two Buttons close together → the Audit will report spacing under 12px.',
  '<b>How to fix (Elementor):</b> On the parent Container, increase <b>Items Gap</b> (if using Containers) or add <b>Advanced ▸ Margin</b> to widgets so nearest edges are ≥12px on Mobile.'
])}
${section('ACCESSIBILITY: Aria-Labels for Vague or Missing descriptions', [
  '<b>What it means:</b> Links/buttons must have clear, specific accessible names. Icon-only controls need a programmatic label.',
  '<b>How it checks:</b> Flags vague CTAs (e.g., “Read more”), icon-only controls without labels, linked images without names, and unlabeled form fields.',
  '<b>How to test (Elementor):</b> Create a Button with text “Read more” or an Icon widget wrapped in a link with no text; the Audit will flag them.',
  '<b>How to fix (Elementor):</b> Prefer specific visible text (e.g., “Read more about Pricing”). For icon-only links/buttons, add <b>Advanced ▸ Attributes</b> → <code>aria-label="Open cart"</code>, or aria-label|Open Cart For forms, ensure each field has a Label in the Form widget.'
])}
${section('ACCESSIBILITY: Non-native buttons missing role/tabindex', [
  '<b>What it means:</b> Clickable <code>&lt;div&gt;</code>/<code>&lt;span&gt;</code> need <code>role="button"</code> and keyboard focus (<code>tabindex="0"</code>)—or better, use a real Button.',
  '<b>How it checks:</b> Finds non-native “button-like” elements that are missing role/tabindex.',
  '<b>How to test (Elementor):</b> Make a Container clickable (link in Advanced) with no Button widget; the Audit may flag inner non-native elements.',
  '<b>How to fix (Elementor):</b> Replace with a Button widget when possible. If you must keep a custom element: add <b>Advanced ▸ Attributes</b> → <code>role="button"</code> and <code>tabindex="0"</code>.'
])}
${section('CONTENT: No primary CTA found', [
  '<b>What it means:</b> The page lacks a clear next action outside navigation.',
  '<b>How it checks:</b> Looks for prominent non-nav buttons/links.',
  '<b>How to test (Elementor):</b> Remove the main Button from your hero or key section; the Audit will report no obvious CTA.',
  '<b>How to fix (Elementor):</b> Add a Button widget in the hero or after key content (e.g., “Contact us”, “Get a quote”) and link it to your target page.'
])}
${section('IMAGES: Non-modern formats', [
  '<b>What it means:</b> JPG/PNG are heavier; prefer WebP/AVIF for performance.',
  '<b>How it checks:</b> Flags <code>&lt;img&gt;</code> whose current src isn’t WebP/AVIF.',
  '<b>How to test (Elementor):</b> Drop an Image widget with a .jpg/.png. The Audit will list it.',
  '<b>How to fix (Elementor):</b> Replace the image: open the Image widget → click the thumbnail → upload/select a <b>.webp</b> (or AVIF) version.'
])}
${section('IMAGES: Alt-Text Description Missing', [
  '<b>What it means:</b> Informative images need meaningful <code>alt</code>. Decorative images should use empty alt (<code>alt=""</code>).',
  '<b>How it checks:</b> Flags missing, empty, or placeholder alt text.',
  '<b>How to test (Elementor):</b> Insert an Image widget → choose an image with empty “Alt Text” in the media dialog; the Audit will flag it.',
  '<b>How to fix (Elementor):</b> Click the image thumbnail → in the media dialog, fill the <b>Alt Text</b> field. For decorative images, set Alt Text intentionally empty (<code>""</code>).'
])}
${section('NAV: Multiple menus share the same aria-label', [
  '<b>What it means:</b> Multiple <code>&lt;nav&gt;</code> regions have the same accessible name, which confuses screen-reader navigation.',
  '<b>How it checks:</b> Groups navs by <code>aria-label</code>/<code>aria-labelledby</code> and finds duplicates.',
  '<b>How to test (Elementor):</b> If you use more than one Nav Menu widget, select each one → <b>Advanced ▸ Attributes</b> and check for identical <code>aria-label</code> values.',
  '<b>How to fix (Elementor):</b> On each Nav Menu’s outer Container or the widget: <b>Advanced ▸ Attributes</b> → add <code>aria-label="Primary navigation"</code>, <code>"Footer navigation"</code>, etc., making them unique.'
])}
${section('TYPOGRAPHY: font-size without clamp()', [
  '<b>What it means:</b> Fixed font sizes don’t scale fluidly across viewports; <code>clamp()</code> gives a responsive min/preferred/max.',
  '<b>How it checks:</b> Scans CSS/inline vars for <code>clamp()</code> on <code>font-size</code>.',
  '<b>How to test (Elementor):</b> Set a Heading/Text to a fixed px size (no responsive settings) and reopen the Audit.',
  '<b>How to fix (Elementor):</b> Give the widget a class (e.g., <code>fs-fluid</code> in <b>Advanced ▸ CSS Classes</b>) then add an HTML widget anywhere on the page with:<br><code>&lt;style&gt;.fs-fluid{font-size:clamp(1rem, 2.2vw, 1.5rem)}&lt;/style&gt;</code><br>(Or, if you have Pro: Page ▸ Advanced ▸ Custom CSS).'
])}
`;infoBody.innerHTML=INFO_HTML;(function initInfoAccordions(root){const heads=root.querySelectorAll('.info-acc-head');heads.forEach(head=>{const body=head.nextElementSibling;const toggle=()=>{const open=head.getAttribute('aria-expanded')==='true';head.setAttribute('aria-expanded',String(!open));body.hidden=open;};head.addEventListener('click',toggle);head.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();toggle();}});head.setAttribute('role','button');head.setAttribute('tabindex','0');});})(infoBody);const infoClose=document.createElement('button');infoClose.type='button';infoClose.textContent='Close';Object.assign(infoClose.style,{position:'sticky',bottom:0,margin:'12px',marginTop:'0',padding:'6px 10px',border:'1px solid #e2e2e2',borderRadius:'6px',background:'#f7f7f7',cursor:'pointer',float:'right'});infoClose.setAttribute('aria-label','Close information panel');infoPane.appendChild(infoHead);infoPane.appendChild(infoBody);infoPane.appendChild(infoClose);document.body.appendChild(infoBackdrop);document.body.appendChild(infoPane);function openInfo(){infoBackdrop.style.display='block';infoBackdrop.setAttribute('aria-hidden','false');infoPane.style.display='block';infoClose.focus();}
function closeInfo(){infoBackdrop.style.display='none';infoBackdrop.setAttribute('aria-hidden','true');infoPane.style.display='none';infoBtn.focus();}
infoBtn.setAttribute('aria-controls',infoPane.id);infoBtn.addEventListener('click',(e)=>{e.stopPropagation();openInfo();});infoClose.addEventListener('click',(e)=>{e.stopPropagation();closeInfo();});infoBackdrop.addEventListener('click',closeInfo);window.addEventListener('keydown',(e)=>{if(e.key==='Escape'&&infoBackdrop.style.display==='block')closeInfo();});panel.appendChild(content);const toggles=document.createElement('div');Object.assign(toggles.style,{display:'flex',flexWrap:'wrap',gap:'8px',margin:'8px 0 10px 0',fontSize:'12px',color:'#333'});const CATS=[{key:'contrast_aa',label:'Color Contrast'},{key:'text_min_16',label:'Text <16px'},{key:'images_alt_missing',label:'Alt-Text'},{key:'images_nonmodern',label:'WebP/AVIF Images'},{key:'font_no_clamp',label:'Clamp()'},{key:'aria_label',label:'Aria-Label'},{key:'cta_missing',label:'CTAs'},{key:'heading_too_long',label:'Long Headings'},{key:'control_min_size',label:'Control Size'},{key:'mobile_control_spacing',label:'Mobile Spacing'},{key:'nav_duplicate_labels',label:'Duplicate Nav'},{key:'skip_link',label:'Skip Link'},{key:'button_semantics',label:'Button Role/Tab'},];const GROUPS=[{groupKey:'landmark_main',label:'Main',members:['main_missing','main_multiple']},{groupKey:'landmark_header',label:'Header',members:['header_missing','header_multiple']},{groupKey:'landmark_footer',label:'Footer',members:['footer_missing','footer_multiple']},{groupKey:'headings_group',label:'Headings',members:['h1_missing','h1_multiple','heading_skips']},];function groupKeyFor(issueKey){if(/^main_/.test(issueKey))return'landmark_main';if(/^header_/.test(issueKey))return'landmark_header';if(/^footer_/.test(issueKey))return'landmark_footer';if(issueKey==='h1_missing'||issueKey==='h1_multiple'||issueKey==='heading_skips')return'headings_group';return null;}
function isHiddenEffective(issueKey){const g=groupKeyFor(issueKey);return isHidden(issueKey)||(g&&isHidden(g));}
function renderTogglesFor(issues){const present=new Set(issues.map(i=>i.key));toggles.innerHTML='';const WRAP_BASE={display:'inline-flex',alignItems:'center',gap:'6px',background:'#f7f7f7',border:'1px solid #eaeaea',borderRadius:'3px',padding:'2px 3px',cursor:'pointer'};const tweakCheckbox=(cb)=>{cb.style.margin='0';cb.style.cursor='pointer';cb.style.verticalAlign='middle';cb.style.position='relative';cb.style.top='0px';};const styleSpan=(span)=>{Object.assign(span.style,{display:'inline-block',background:'transparent',padding:'0',borderRadius:'0',cursor:'pointer'});};GROUPS.forEach(g=>{if(!g.members.some(m=>present.has(m)))return;const id='audit-toggle-'+g.groupKey;const wrap=document.createElement('label');wrap.setAttribute('for',id);Object.assign(wrap.style,WRAP_BASE);const cb=document.createElement('input');cb.type='checkbox';cb.id=id;cb.checked=!isHidden(g.groupKey);cb.addEventListener('change',()=>{setHidden(g.groupKey,!cb.checked);try{const res=audit(current.doc);renderPanel(res,current.doc);}catch(_){}});tweakCheckbox(cb);const span=document.createElement('span');span.textContent=g.label;styleSpan(span);wrap.append(cb,span);toggles.appendChild(wrap);});CATS.forEach(cat=>{if(!present.has(cat.key))return;const id='audit-toggle-'+cat.key;const wrap=document.createElement('label');wrap.setAttribute('for',id);Object.assign(wrap.style,WRAP_BASE);const cb=document.createElement('input');cb.type='checkbox';cb.id=id;cb.checked=!isHidden(cat.key);cb.addEventListener('change',()=>{setHidden(cat.key,!cb.checked);try{const res=audit(current.doc);renderPanel(res,current.doc);}catch(_){}});tweakCheckbox(cb);const span=document.createElement('span');span.textContent=cat.label;styleSpan(span);wrap.append(cb,span);toggles.appendChild(wrap);});toggles.style.display=toggles.children.length?'flex':'none';}
panel.insertBefore(toggles,content);(document.readyState==='loading'?document.addEventListener('DOMContentLoaded',()=>document.body.append(btn,panel),{once:true}):document.body.append(btn,panel));function makeDraggable(handleEl,moveEl){let drag=false,dx=0,dy=0;handleEl.addEventListener('mousedown',e=>{if(moveEl===panel&&e.target.classList.contains('audit-resizer'))return;drag=true;handleEl.style.cursor='grabbing';const r=moveEl.getBoundingClientRect();dx=e.clientX-r.left;dy=e.clientY-r.top;Object.assign(moveEl.style,{left:r.left+'px',top:r.top+'px',right:'auto',bottom:'auto'});document.addEventListener('mousemove',onMove);document.addEventListener('mouseup',onUp);});function onMove(e){if(!drag)return;Object.assign(moveEl.style,{left:(e.clientX-dx)+'px',top:(e.clientY-dy)+'px'});}
function onUp(){drag=false;handleEl.style.cursor=(handleEl===btn)?'grab':'move';document.removeEventListener('mousemove',onMove);document.removeEventListener('mouseup',onUp);}}
makeDraggable(title,panel);makeDraggable(btn,btn);(function addSEResizer(box){const h=document.createElement('div');h.className='audit-resizer audit-resizer-se';Object.assign(h.style,{position:'absolute',width:'14px',height:'14px',right:'-2px',bottom:'-2px',cursor:'nwse-resize',zIndex:2147483647});box.appendChild(h);h.addEventListener('mousedown',e=>{e.preventDefault();e.stopPropagation();INTERACTING=true;const sx=e.clientX,sy=e.clientY,r=box.getBoundingClientRect();const start={left:r.left,top:r.top,width:r.width,height:r.height};const minW=360,minH=160,maxW=Math.min(900,window.innerWidth-20);const onMove=(e)=>{const dx=e.clientX-sx,dy=e.clientY-sy;Object.assign(box.style,{left:start.left+'px',top:start.top+'px',width:Math.max(minW,Math.min(maxW,start.width+dx))+'px',height:Math.max(minH,start.height+dy)+'px',right:'auto',bottom:'auto'});};const onUp=()=>{document.removeEventListener('mousemove',onMove);document.removeEventListener('mouseup',onUp);setTimeout(()=>INTERACTING=false,180);};document.addEventListener('mousemove',onMove);document.addEventListener('mouseup',onUp);});})(panel);function removeHeadingBadges(doc){const d=doc||document;d.querySelectorAll('.audit-heading-badge').forEach(n=>{try{n.remove();}catch(e){}});d.querySelectorAll('[data-audit-pos-mod]').forEach(h=>{try{h.style.position=h.getAttribute('data-audit-prev-pos')||'';h.removeAttribute('data-audit-pos-mod');h.removeAttribute('data-audit-prev-pos');}catch(e){}});}
function addHeadingBadges(doc){const d=doc||document;removeHeadingBadges(d);const headings=d.querySelectorAll('h1,h2,h3,h4,h5,h6');headings.forEach(h=>{if(panel.contains(h)||btn.contains(h))return;const lvl=h.tagName.toUpperCase();const cs=(h.ownerDocument.defaultView||window).getComputedStyle(h);if(cs.position==='static'){h.setAttribute('data-audit-pos-mod','1');h.setAttribute('data-audit-prev-pos',h.style.position||'');h.style.position='relative';}
const b=d.createElement('span');b.className='audit-heading-badge';b.textContent=lvl;Object.assign(b.style,{position:'absolute',top:'-10px',right:'-10px',width:'24px',height:'24px',borderRadius:'50%',background:'#e53935BF',color:'#fff',display:'inline-flex',alignItems:'center',justifyContent:'center',fontSize:'14px',fontWeight:'400',fontFamily:'-apple-system, Segoe UI, Roboto, Arial, sans-serif',lineHeight:'14px',pointerEvents:'none',boxShadow:'0 0 0 2px rgba(255,255,255,0.9)',zIndex:2147483644,letterSpacing:'0.5px'});h.appendChild(b);});}
function panelOpen(){return panel.style.display==='block';}
function clearHighlights(doc){const d=doc||document;d.querySelectorAll('.audit-highlight').forEach(el=>{el.style.outline='';el.classList.remove('audit-highlight');});d.querySelectorAll('.audit-overlay').forEach(o=>o.remove());}
function createOverlayFor(el,targetDoc,opts={}){const d=targetDoc||document,overlay=d.createElement('div');overlay.className='audit-overlay';Object.assign(overlay.style,{position:'fixed',zIndex:2147483644,background:'rgba(229,57,53,0.16)',boxShadow:'inset 0 0 0 3px rgba(229,57,53,1)',pointerEvents:'none',borderRadius:getComputedStyle(el).borderRadius||'0'});function place(){const r=el.getBoundingClientRect();overlay.style.left=r.left+'px';overlay.style.top=r.top+'px';overlay.style.width=Math.max(0,r.width)+'px';overlay.style.height=Math.max(0,r.height)+'px';overlay.style.display=(r.width>0&&r.height>0)?'block':'none';}
(d.body||d.documentElement).appendChild(overlay);place();const win=d.defaultView||window;const onScroll=()=>place(),onResize=()=>place();win.addEventListener('scroll',onScroll,{passive:true});win.addEventListener('resize',onResize);const cleanup=()=>{overlay.remove();win.removeEventListener('scroll',onScroll);win.removeEventListener('resize',onResize);};if(opts.autoRemoveMs)setTimeout(cleanup,opts.autoRemoveMs);return cleanup;}
function highlightOnce(el,doc){el.style.outline='5px dashed #e53935';el.classList.add('audit-highlight');createOverlayFor(el,doc,{autoRemoveMs:1600});setTimeout(()=>{try{el.style.outline='';el.classList.remove('audit-highlight');}catch(e){}},1600);}
function findPreviewDoc(){const candidates=['iframe[name="editor-canvas"]','iframe.elementor-iframe','iframe[src*="post.php"]','iframe[src*="site-editor.php"]','iframe[src*="block-editor"]'];const iframe=document.querySelector(candidates.join(','))||document.querySelector('iframe');if(iframe){try{const fdoc=iframe.contentDocument||iframe.contentWindow.document;if(fdoc&&fdoc.body)return{doc:fdoc,iframe};}catch(e){}}
return{doc:document,iframe:null};}
function labelKind(el){let n=el;for(let i=0;i<6&&n;i++,n=n.parentElement){const id=(n.id||'').toLowerCase();const cls=(n.className||'').toString().toLowerCase();if(/elementor/.test(cls))return'builder:elementor';if(/bricks|brxe-/.test(cls))return'builder:bricks';if(/wp-block|block-editor|is-root-container/.test(cls))return'builder:gutenberg';if(id==='content'||/site-main|entry-content|theme|container/.test(cls))return'theme';}
return'unknown';}
function containerKeyFor(el){let n=el;while(n){if(n.nodeType!==1){n=n.parentElement;continue;}
const c=(n.className||'').toString();if(/elementor-section|elementor-top-section|elementor-container|e-con(\s|$)/.test(c)||n.tagName==='SECTION'||n.tagName==='ARTICLE'||n.tagName==='ASIDE'){return n;}
n=n.parentElement;}
return null;}
function srgbToLin(c){return(c<=0.04045)?c/12.92:Math.pow((c+0.055)/1.055,2.4);}
function relativeLuminance(rgb){const r=srgbToLin(rgb[0]/255),g=srgbToLin(rgb[1]/255),b=srgbToLin(rgb[2]/255);return 0.2126*r+0.7152*g+0.0722*b;}
function contrastRatio(fgRGB,bgRGB){const L1=relativeLuminance(fgRGB),L2=relativeLuminance(bgRGB);const lighter=Math.max(L1,L2),darker=Math.min(L1,L2);return(lighter+0.05)/(darker+0.05);}
function parseColor(str){if(!str)return null;const s=str.trim();if(s.startsWith('rgb')){const m=s.match(/rgba?\(([^)]+)\)/i);if(!m)return null;const p=m[1].split(',').map(v=>v.trim());const r=+p[0],g=+p[1],b=+p[2];const a=p[3]!==undefined?parseFloat(p[3]):1;return{r,g,b,a};}else if(s[0]==='#'){let h=s.slice(1);if(h.length===3)h=h.split('').map(c=>c+c).join('');if(h.length===6){return{r:parseInt(h.slice(0,2),16),g:parseInt(h.slice(2,4),16),b:parseInt(h.slice(4,6),16),a:1};}}
return null;}
function rgbToHex(rgb){const to2=n=>n.toString(16).padStart(2,'0');return'#'+to2(rgb[0])+to2(rgb[1])+to2(rgb[2]);}
function mixRGB(a,b,t){return[Math.round(a[0]*(1-t)+b[0]*t),Math.round(a[1]*(1-t)+b[1]*t),Math.round(a[2]*(1-t)+b[2]*t)];}
function effectiveBG(el,win){let n=el;while(n){const cs=win.getComputedStyle(n);const bg=parseColor(cs.backgroundColor);if(bg&&bg.a>0)return[bg.r,bg.g,bg.b];n=n.parentElement;}
return[255,255,255];}
function effectiveFG(el,win){const cs=win.getComputedStyle(el);const c=parseColor(cs.color);if(c&&(c.a===undefined||c.a>0))return[c.r,c.g,c.b];return null;}
function px(n){return parseFloat(String(n||'').replace('px',''))||0;}
function isLargeText(cs){const size=px(cs.fontSize);const weight=parseInt(cs.fontWeight,10)||400;const bold=weight>=700;return(size>=24)||(bold&&size>=18.66);}
function isUIComponent(el,cs){const tag=el.tagName;if(tag==='BUTTON'||tag==='INPUT'||tag==='SELECT'||tag==='TEXTAREA')return true;if(el.getAttribute('role')==='button')return true;if(tag==='A')return true;const cls=(el.className||'').toString().toLowerCase();if(/\bbutton\b|\bbtn\b|elementor-button|wp-block-button/.test(cls))return true;if((tag==='SVG'||tag==='I')&&el.closest('a,button,[role="button"]'))return true;return false;}
function isButtonLike(el,cs){const tag=el.tagName;if(tag==='INPUT'&&(el.type||'').toLowerCase()==='hidden')return false;if(tag==='BUTTON'||tag==='INPUT'||tag==='SELECT'||tag==='TEXTAREA')return true;if(el.getAttribute('role')==='button')return true;const cls=(el.className||'').toString().toLowerCase();if(tag==='A'&&isInMenuContext(el))return true;if(/\bbutton\b|\bbtn\b|elementor-button|wp-block-button__link/.test(cls))return true;if(tag==='A'){const disp=cs.display;const looksLikeIconLink=el.classList.contains('elementor-icon')||el.classList.contains('elementor-social-icon')||(!!el.querySelector('svg,img,i'));if(looksLikeIconLink&&(disp==='inline'||disp==='inline-block'||disp==='block'||disp==='flex'||disp==='inline-flex')){const r=el.getBoundingClientRect();if(r.width>=16&&r.height>=16)return true;}
const hasPadding=['paddingTop','paddingRight','paddingBottom','paddingLeft'].some(p=>(parseFloat(cs[p])||0)>2);if((disp==='inline-block'||disp==='block'||disp==='flex'||disp==='inline-flex')&&hasPadding)return true;}
if((tag==='SVG'||tag==='I')&&el.closest('a,button,[role="button"]'))return true;return false;}
function nearestAccessibleColor(fgRGB,bgRGB,required){const black=[0,0,0],white=[255,255,255];let best=null;for(let t=0;t<=1.0001;t+=0.01){const c=mixRGB(fgRGB,black,t);if(contrastRatio(c,bgRGB)>=required){best={rgb:c,t};break;}}
let bestW=null;for(let t=0;t<=1.0001;t+=0.01){const c=mixRGB(fgRGB,white,t);if(contrastRatio(c,bgRGB)>=required){bestW={rgb:c,t};break;}}
if(best&&bestW)return(best.t<=bestW.t)?best:bestW;else return best||bestW||((contrastRatio([0,0,0],bgRGB)>=contrastRatio([255,255,255],bgRGB))?{rgb:[0,0,0],t:1}:{rgb:[255,255,255],t:1});}
function nearestAccessibleBackground(fgRGB,bgRGB,required){const black=[0,0,0],white=[255,255,255];let best=null;for(let t=0;t<=1.0001;t+=0.01){const c=mixRGB(bgRGB,black,t);if(contrastRatio(fgRGB,c)>=required){best={rgb:c,t};break;}}
let bestW=null;for(let t=0;t<=1.0001;t+=0.01){const c=mixRGB(bgRGB,white,t);if(contrastRatio(fgRGB,c)>=required){bestW={rgb:c,t};break;}}
if(best&&bestW)return(best.t<=bestW.t)?best:bestW;if(best)return best;if(bestW)return bestW;return(contrastRatio(fgRGB,[0,0,0])>=contrastRatio(fgRGB,[255,255,255]))?{rgb:[0,0,0],t:1}:{rgb:[255,255,255],t:1};}
const IGNORE_UI=['#wpadminbar','#adminmenu','.wp-toolbar','.update-nag','.interface-interface-skeleton','.edit-post-layout','.edit-post-header','.block-editor','.block-editor__typewriter','.components-popover','.elementor-panel','.elementor-editor-dialog','.elementor-navigator','.bricks-frontend-editor','.brxe-iframe-toolbar','.oxygen-ui'].join(',');function isIgnoredChrome(el){return!!el.closest(IGNORE_UI);}
function isBuilderChrome(el){const body=el.ownerDocument&&el.ownerDocument.body;const bodyCls=(body&&body.className||'').toString().toLowerCase();const inElementor=/\belementor-editor-active\b/.test(bodyCls);const inBricks=/\bbricks-builder\b|\bbrxe-editor\b/.test(bodyCls);const inGuten=/\bblock-editor\b/.test(bodyCls);if(!(inElementor||inBricks||inGuten))return false;const cls=(el.className||'').toString().toLowerCase();const looksLikeOverlay=/(overlay|handle|resizer|draggable|sortable|ui|tooltip|context|ghost)/.test(cls);const looksLikeAdd=/(add-|^add$|empty|placeholder|dropzone)/.test(cls);const looksLikeEditor=/(editor|control|navigator|panel|inspector)/.test(cls);const matchesSpecific=el.closest('.elementor-element-overlay,.elementor-editor-element-settings,.elementor-add-section,.elementor-add-column,.elementor-widget-empty,.elementor-empty-view')||el.closest('.brxe-controls,.brxe-toolbar,.bricks-element-overlay');return!!(looksLikeOverlay||looksLikeAdd||looksLikeEditor||matchesSpecific);}
function surroundingBG(el,win){let p=el.parentElement;while(p){const cs=win.getComputedStyle(p);const bg=parseColor(cs.backgroundColor);if(bg&&bg.a>0)return[bg.r,bg.g,bg.b];p=p.parentElement;}
return[255,255,255];}
function hasOwnFill(cs){const bg=parseColor(cs.backgroundColor);return!!(bg&&bg.a>0);}
function visibleBorder(cs){const widths=['Top','Right','Bottom','Left'].map(side=>parseFloat(cs['border'+side+'Width'])||0);const styles=['Top','Right','Bottom','Left'].map(side=>cs['border'+side+'Style']||'none');const colors=['Top','Right','Bottom','Left'].map(side=>parseColor(cs['border'+side+'Color']));const anyIndex=widths.findIndex((w,i)=>w>0.5&&styles[i]!=='none'&&colors[i]&&(colors[i].a===undefined||colors[i].a>0));if(anyIndex===-1)return null;const c=colors[anyIndex];return[c.r,c.g,c.b];}
function nearestContrastingBackground(bgRGB,adjRGB,required){const black=[0,0,0],white=[255,255,255];let best=null,bestT=Infinity;for(let t=0;t<=1.0001;t+=0.01){const c=mixRGB(bgRGB,black,t);if(contrastRatio(c,adjRGB)>=required){best=c;bestT=t;break;}}
for(let t=0;t<=1.0001;t+=0.01){const c=mixRGB(bgRGB,white,t);if(contrastRatio(c,adjRGB)>=required){if(t<bestT){best=c;bestT=t;}
break;}}
if(!best){const k=contrastRatio([0,0,0],adjRGB);const w=contrastRatio([255,255,255],adjRGB);best=(k>=w)?[0,0,0]:[255,255,255];}
return{rgb:best,t:bestT};}
function isMobileView(win){try{return win.matchMedia&&win.matchMedia('(max-width: 767.98px)').matches;}catch(e){return win.innerWidth<=768;}}
function effectiveTargetRect(el){const rect=el.getBoundingClientRect();if(rect.width>0&&rect.height>0)return rect;const desc=el.querySelector('a,button,[role="button"],input:not([type="hidden"]),select,textarea,.button,.btn,.elementor-button,.wp-block-button__link');if(desc){const r2=desc.getBoundingClientRect();if(r2.width>0&&r2.height>0)return r2;}
return rect;}
function rectDistance(r1,r2){const dx=Math.max(0,Math.max(r1.left,r2.left)-Math.min(r1.right,r2.right));const dy=Math.max(0,Math.max(r1.top,r2.top)-Math.min(r1.bottom,r2.bottom));return Math.hypot(dx,dy);}
function labelFor(el){const txt=(el.innerText||el.textContent||'').trim().replace(/\s+/g,' ');if(txt)return txt.slice(0,80)+(txt.length>80?'…':'');const alt=el.getAttribute?.('aria-label')||el.getAttribute?.('alt')||el.getAttribute?.('title');return(alt||'').trim();}
function isInMenuContext(el){const MENU_CTX=['nav','[role="navigation"]','header .menu','footer .menu','.site-header .menu','.site-footer .menu','.main-navigation','.site-navigation','.navbar','.menu','.menu-container','.menu-wrap','.menu-items','.menu-list','.menu-primary','.menu-secondary','.menu-top','.menu-bottom','.footer-menu','.header-menu','.nav-menu','.navigation','.wp-block-navigation','.wp-block-navigation__container','.elementor-widget-nav-menu','.elementor-nav-menu','.elementor-menu','.elementor-nav','.brxe-nav-menu','.bricks-nav-menu','.bricks-mobile-menu','.mega-menu','.megamenu','.tt-mega-menu','.max-mega-menu'].join(',');return!!el.closest(MENU_CTX);}
function isMenuToggle(el){const cls=(el.className||'').toString().toLowerCase();if(/\bmenu-toggle\b|\belementor-menu-toggle\b|\bnav-toggle\b|\bhamburger\b/.test(cls))return true;if(el.matches?.('[aria-controls*="menu"],[aria-haspopup="menu"]'))return true;return false;}
function isSkipLink(el){if(!el||(el.tagName||'').toLowerCase()!=='a')return false;const cls=(el.className||'').toString().toLowerCase();const href=(el.getAttribute('href')||'').trim();if(/\bskip[-_ ]?link\b|\bskip[-_ ]?to[-_ ]?content\b|\bscreen-reader-shortcut\b/.test(cls))return true;if(/^#(main|content|primary|page|skip|site-main)$/i.test(href))return true;if(/\bscreen-reader-text\b|\bsr-only\b|\bvisually-hidden\b/.test(cls))return true;return false;}
function getTabbables(doc){const d=doc,win=d.defaultView||window;const nodes=Array.from(d.querySelectorAll('a[href],button,input,select,textarea,[tabindex]')).filter(el=>{const cs=win.getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return false;if(el.hasAttribute('disabled'))return false;const ti=parseInt(el.getAttribute('tabindex')||'0',10);return!Number.isNaN(ti)&&ti>=0;});return nodes;}
function collectSkipLinkIssue(doc){const d=doc;const win=d.defaultView||window;const links=Array.from(d.querySelectorAll('a')).filter(isSkipLink);const skip=links[0]||null;if(!skip){return{key:'skip_link',title:'ACCESSIBILITY: “Skip to content” link is missing',message:'Add a keyboard-accessible “Skip to content” link as the first focusable element.',fixes:['Place <code>&lt;a class="skip-link" href="#main"&gt;Skip to content&lt;/a&gt;</code> as the first focusable item inside <code>&lt;body&gt;</code>.','Ensure the target exists: <code>&lt;main id="main"&gt;</code> (or <code>role="main"</code>).','Make it visible on focus only (CSS below).','CSS: <code>.skip-link{position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden;} .skip-link:focus{left:8px;top:8px;width:auto;height:auto;padding:.5rem 1rem;background:#fff;border:2px solid #000;z-index:100000;}</code>'],elements:[]};}
const href=(skip.getAttribute('href')||'').trim();const targetId=href.startsWith('#')?href.slice(1):'';const target=targetId?d.getElementById(targetId):null;const els=[];const isMainLike=!!(target&&(target.tagName?.toLowerCase()==='main'||target.getAttribute('role')==='main'||/^(main|content|primary|page|site-main)$/i.test(targetId)));if(!target){els.push({el:skip,kind:labelKind(skip),role:'a',issue:'skiplink',sub:'target-missing',hint:`The href points to “${href||'(none)'}”, but that target isn’t in the DOM.`});}else if(!isMainLike){els.push({el:target,kind:labelKind(target),role:(target.tagName||'').toLowerCase(),issue:'skiplink',sub:'target-not-main',hint:`Target “#${targetId}” exists but isn’t a <main> or role="main".`});}
const tabbables=getTabbables(d);const idx=tabbables.indexOf(skip);if(idx===-1||idx>2){els.push({el:skip,kind:labelKind(skip),role:'a',issue:'skiplink',sub:'late',index:(idx>=0?idx+1:'unknown'),hint:'Make the skip link the first focusable element in the page.'});}
const cs=win.getComputedStyle(skip);const offscreenLikely=/clip:|clip-path:/.test(skip.getAttribute('style')||'')||((cs.position==='absolute'||cs.position==='fixed')&&((parseFloat(cs.left)||0)<=-500||(parseFloat(cs.right)||0)<=-500));if(offscreenLikely){els.push({el:skip,kind:labelKind(skip),role:'a',issue:'skiplink',sub:'maybe-not-visible-on-focus',hint:'Ensure the skip link becomes visible on :focus (reset left/top/clip; add padding/background/border).'});}
if(els.length===0){els.push({el:skip,kind:labelKind(skip),role:'a',issue:'skiplink',sub:'ok',hint:'Skip link present and appears correctly placed.'});}
return{key:'skip_link',title:'ACCESSIBILITY: “Skip to content”',message:'Checks presence, target, and early tab-order placement.',fixes:['Place the link first in tab order (ideally first in <code>&lt;body&gt;</code>).','Point it to a real main region: <code>&lt;main id="main"&gt;</code> (or role="main").','Ensure it is hidden visually but visible on <code>:focus</code>.',],elements:els};}
const EXCLUDE_SMALLTEXT='.elementor-item.elementor-item-anchor, .elementor-item.elementor-item-anchor *';function isExcludedSmallText(el){const a=el.closest('.elementor-item.elementor-item-anchor');if(!a)return false;return!isInMenuContext(a);}
const MIN_TEXT_PX=16;const HEADING_WORD_LIMIT=12;const HEADING_CHAR_LIMIT=80;function collectContrastFailures(doc){const d=doc;const win=d.defaultView||window;const selectors=['h1,h2,h3,h4,h5,h6','p,li,span,small,em,strong,blockquote,figcaption,label','a,button,[role="button"],.button,.btn,.elementor-button,.wp-block-button__link','svg,svg *','i'].join(',');const raw=Array.from(d.querySelectorAll(selectors)).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!el.classList?.contains('audit-heading-badge')&&!el.closest?.('.audit-heading-badge')).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el)).filter(el=>!isExcludedSmallText(el));const elements=raw.filter(el=>{const head=el.closest('h1,h2,h3,h4,h5,h6');if(head&&el!==head)return false;const ctl=el.closest('a,button,[role="button"],.button,.btn,.elementor-button,.wp-block-button__link');if(ctl&&el!==ctl&&el.tagName?.toLowerCase()!=='svg')return false;if(el.tagName&&el.tagName.toLowerCase()!=='svg'&&el.closest('svg'))return false;return true;});const fails=[];elements.forEach(el=>{try{const cs=win.getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;const fg=effectiveFG(el,win);if(!fg)return;const bg=effectiveBG(el,win);const threshold=isLargeText(cs)?3.0:4.5;const ratio=contrastRatio(fg,bg);if(ratio+1e-6<threshold){const fgFix=nearestAccessibleColor(fg,bg,threshold);const bgFix=nearestAccessibleBackground(fg,bg,threshold);fails.push({el,kind:labelKind(el),role:el.tagName.toLowerCase(),contrastType:'text-vs-bg',ratio:Number(ratio.toFixed(2)),required:threshold,fontSize:px(cs.fontSize).toFixed(1),fontWeight:parseInt(cs.fontWeight,10)||400,fgHex:rgbToHex(fg),bgHex:rgbToHex(bg),suggestFG:rgbToHex(fgFix.rgb),suggestBG:rgbToHex(bgFix.rgb)});}
if(isUIComponent(el,cs)){const adj=surroundingBG(el,win);const hasFill=hasOwnFill(cs);const borderRGB=visibleBorder(cs);if(hasFill){const bgContrast=contrastRatio(bg,adj);if(bgContrast+1e-6<3.0){const bgFix2=nearestContrastingBackground(bg,adj,3.0);fails.push({el,kind:labelKind(el),role:el.tagName.toLowerCase()+' (control background)',contrastType:'bg-vs-adj',ratio:Number(bgContrast.toFixed(2)),required:3.0,fontSize:px(cs.fontSize).toFixed(1),fontWeight:parseInt(cs.fontWeight,10)||400,bgHex:rgbToHex(bg),adjHex:rgbToHex(adj),suggestFG:'',suggestBG:rgbToHex(bgFix2.rgb)});}}else if(borderRGB){const bContrast=contrastRatio(borderRGB,adj);if(bContrast+1e-6<3.0){const bgFix2=nearestContrastingBackground(borderRGB,adj,3.0);fails.push({el,kind:labelKind(el),role:el.tagName.toLowerCase()+' (control border)',contrastType:'border-vs-adj',ratio:Number(bContrast.toFixed(2)),required:3.0,fontSize:px(cs.fontSize).toFixed(1),fontWeight:parseInt(cs.fontWeight,10)||400,borderHex:rgbToHex(borderRGB),adjHex:rgbToHex(adj),suggestFG:'',suggestBG:rgbToHex(bgFix2.rgb)});}}}}catch(e){}});return fails;}
function collectSmallTextFailures(doc){const d=doc;const win=d.defaultView||window;const selectors=['p,li,blockquote,figcaption,dd,dt,pre','h1,h2,h3,h4,h5,h6','.wp-block-paragraph,.wp-block-list,.elementor-widget-text-editor','span,a,em,strong,small'].join(',');const _px=v=>parseFloat(String(v||'').replace('px',''))||0;function isTextContainer(el){const t=(el.tagName||'').toLowerCase();if(/^(p|li|blockquote|figcaption|dd|dt|pre)$/.test(t))return true;if(/^h[1-6]$/.test(t))return true;const cls=(el.className||'').toString().toLowerCase();if(/\bwp-block-paragraph\b|\bwp-block-list\b|\belementor-widget-text-editor\b/.test(cls))return true;return false;}
function bubbleToTextContainer(el,size){let n=el;for(let i=0;i<6&&n&&n.parentElement;i++){const p=n.parentElement;const pcs=win.getComputedStyle(p);if(isIgnoredChrome(p)||isBuilderChrome(p))break;if(_px(pcs.fontSize)!==size)break;n=p;}
return isTextContainer(n)?n:el;}
const raw=Array.from(d.querySelectorAll(selectors)).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!el.classList?.contains('audit-heading-badge')&&!el.closest?.('.audit-heading-badge')).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el));const seen=new Set();const fails=[];raw.forEach(el=>{try{const cs=win.getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;const heading=/^h[1-6]$/i.test(el.tagName||'');const buttonLike=isButtonLike(el,cs);if(isInMenuContext(el)&&!heading&&!buttonLike)return;const txt=(el.innerText||el.textContent||'').trim().replace(/\s+/g,' ');if(!txt)return;const r=el.getBoundingClientRect();if(!heading&&!buttonLike){if((r.width<32&&txt.length<12)||r.height<10)return;}
const size=_px(cs.fontSize);if(!(size>0))return;let rep=el;if(buttonLike){rep=el.closest('a,button,[role="button"],.button,.btn,.elementor-button,.wp-block-button__link')||el;}else{rep=bubbleToTextContainer(el,size);}
if(isExcludedSmallText(rep))return;if(seen.has(rep))return;const repCS=win.getComputedStyle(rep);const repSize=_px(repCS.fontSize);if(repSize>0&&repSize<MIN_TEXT_PX){seen.add(rep);fails.push({el:rep,kind:labelKind(rep),role:(rep.tagName||'').toLowerCase()||'node',issue:'small-text',fontSize:Number(repSize.toFixed(1)),required:MIN_TEXT_PX});}}catch(e){}});return fails;}
function collectControlMinSizeFailures(doc){const d=doc;const win=d.defaultView||window;const selectors='a,button,[role="button"],input,select,textarea,.button,.btn,.elementor-button,.wp-block-button__link';const raw=Array.from(d.querySelectorAll(selectors)).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el));const elements=raw.filter(el=>{const ctl=el.closest('a,button,[role="button"],input,select,textarea,.button,.btn,.elementor-button,.wp-block-button__link');return!ctl||ctl===el;});const fails=[];elements.forEach(el=>{try{const cs=win.getComputedStyle(el);const type=(el.type||'').toLowerCase();if(type==='hidden')return;if(el.getAttribute('aria-hidden')==='true')return;if(cs.pointerEvents==='none')return;if(!isButtonLike(el,cs))return;if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;const hasText=(el.innerText||'').trim().length>0;const hasIcon=el.querySelector('svg,img,canvas,svg *')!=null;const bg=parseColor(cs.backgroundColor);const hasBg=!!(bg&&bg.a>0);const bCol=visibleBorder(cs);const hasBorder=!!bCol;if(!hasText&&!hasIcon&&!hasBg&&!hasBorder){return;}
const r=effectiveTargetRect(el);if(r.width<=0||r.height<=0)return;const w=Math.round(r.width);const h=Math.round(r.height);if(w<24||h<24){fails.push({el,kind:labelKind(el),role:el.tagName.toLowerCase(),width:w,height:h,requiredW:24,requiredH:24});}}catch(e){}});return fails;}
function collectMobileControlSpacingFailures(doc){const d=doc;const win=d.defaultView||window;if(!isMobileView(win))return[];const selectors='a,button,[role="button"],input,select,textarea,.button,.btn,.elementor-button,.wp-block-button__link';const nodes=Array.from(d.querySelectorAll(selectors)).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el)).filter(el=>!(isInMenuContext(el)&&!isMenuToggle(el)));const controls=[];nodes.forEach(el=>{try{const cs=win.getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;if(cs.pointerEvents==='none')return;if((el.type||'').toLowerCase()==='hidden')return;if(!isButtonLike(el,cs))return;const r=effectiveTargetRect(el);if(r.width<=0||r.height<=0)return;controls.push({el,rect:r,kind:labelKind(el),role:el.tagName.toLowerCase(),text:labelFor(el)});}catch(e){}});const fails=[];const REQUIRED=12;for(let i=0;i<controls.length;i++){for(let j=i+1;j<controls.length;j++){const a=controls[i],b=controls[j];const dist=rectDistance(a.rect,b.rect);const aInMenu=isInMenuContext(a.el)&&!isMenuToggle(a.el);const bInMenu=isInMenuContext(b.el)&&!isMenuToggle(b.el);if(aInMenu&&bInMenu)continue;if(dist+1e-6<REQUIRED){fails.push({el:a.el,kind:a.kind,role:a.role,spaceType:'mobile-spacing',dist:Math.round(dist),required:REQUIRED,partnerText:b.text||b.role});}}}
return fails;}
function collectCTACandidates(doc){const d=doc;const win=d.defaultView||window;const nodes=Array.from(d.querySelectorAll('a,button,[role="button"],.button,.btn,.elementor-button,.wp-block-button__link')).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el)).filter(el=>!isInMenuContext(el)).filter(el=>!isSkipLink(el));const ctas=[];nodes.forEach(el=>{try{const cs=win.getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;if(cs.pointerEvents==='none')return;if(!isButtonLike(el,cs))return;const r=effectiveTargetRect(el);if(r.width<=0||r.height<=0)return;const hasIcon=!!el.querySelector('svg,img,i,svg *');const hasBG=!!parseColor(cs.backgroundColor)?.a;const hasBorder=!!visibleBorder(cs);const hasPad=['paddingTop','paddingRight','paddingBottom','paddingLeft'].some(p=>(parseFloat(cs[p])||0)>4);const looksActiony=hasIcon||hasBG||hasBorder||hasPad||/button|btn|wp-block-button__link|elementor-button/.test((el.className||'').toString().toLowerCase());if(!looksActiony)return;ctas.push({el,kind:labelKind(el)});}catch(_){}});return ctas;}
function collectLongHeadings(doc){const d=doc;const win=d.defaultView||window;const out=[];const heads=Array.from(d.querySelectorAll('h1,h2,h3,h4,h5,h6')).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el));heads.forEach(h=>{try{const cs=win.getComputedStyle(h);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;let raw=h.innerText||h.textContent||'';const badge=h.querySelector('.audit-heading-badge');if(badge){const badgeText=badge.innerText||badge.textContent||'';raw=raw.replace(badgeText,'').trim();}
const norm=raw.replace(/[\u200B\u00AD]/g,'').replace(/[\s\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\n\r\t]+/g,' ').trim();if(!norm)return;const tokens=norm.split(' ').filter(t=>t);const wordCount=tokens.length;const charCount=norm.length;if(wordCount>HEADING_WORD_LIMIT||charCount>HEADING_CHAR_LIMIT){out.push({el:h,kind:labelKind(h),role:(h.tagName||'').toLowerCase(),issue:'heading-long',level:parseInt((h.tagName||'').slice(1),10)||null,words:wordCount,chars:charCount,limitWords:HEADING_WORD_LIMIT,limitChars:HEADING_CHAR_LIMIT,});}}catch(e){console.error('Error processing heading:',e);}});return out;}
function isModernImageURL(url){if(!url)return true;const u=String(url).split('#')[0].split('?')[0].toLowerCase().trim();if(!u||u.startsWith('data:'))return true;return u.endsWith('.webp')||u.endsWith('.avif');}
function collectNonModernImages(doc){const out=[];const d=doc;const imgs=Array.from(d.querySelectorAll('img'));for(const img of imgs){try{const raw=(img.currentSrc||img.getAttribute('src')||'').trim();if(!isModernImageURL(raw)){out.push({el:img,kind:labelKind(img),role:'img',issue:'nonmodern',src:raw});}}catch(e){}}
const svgImgs=Array.from(d.querySelectorAll('svg image'));for(const si of svgImgs){try{const href=si.getAttribute('href')||si.getAttributeNS('http://www.w3.org/1999/xlink','href')||'';if(!isModernImageURL(href)){const svg=si.closest('svg')||si;out.push({el:svg,kind:labelKind(svg),role:'svg-image',issue:'nonmodern',src:href});}}catch(e){}}
return out;}
function linkHasAccessibleName(a){const txt=(a.innerText||'').trim();if(txt)return true;const aria=(a.getAttribute('aria-label')||a.getAttribute('title')||'').trim();if(aria)return true;const labelledby=(a.getAttribute('aria-labelledby')||'').trim();if(labelledby){const el=a.ownerDocument.getElementById(labelledby);if(el&&(el.innerText||el.textContent||'').trim())return true;}
return false;}
function getByIdText(doc,id){if(!id)return'';const el=doc.getElementById(id);return(el&&(el.innerText||el.textContent)||'').trim();}
function hasAriaName(el,doc){const aria=(el.getAttribute('aria-label')||'').trim();if(aria)return true;const labelledby=(el.getAttribute('aria-labelledby')||'').trim();if(labelledby){const txt=getByIdText(doc,labelledby);if(txt)return true;}
return false;}
function getAccessibleName(el,doc){const labelledby=(el.getAttribute('aria-labelledby')||'').trim();if(labelledby){const txt=getByIdText(doc,labelledby);if(txt)return txt;}
const aria=(el.getAttribute('aria-label')||'').trim();if(aria)return aria;const tag=(el.tagName||'').toLowerCase();if(tag==='img'){const alt=(el.getAttribute('alt')||'').trim();if(alt)return alt;}
const txt=(el.innerText||'').trim();if(txt)return txt;const title=(el.getAttribute('title')||'').trim();if(title)return title;return'';}
function hasSpecificContext(name){const n=name.toLowerCase().replace(/\s+/g,' ').trim();if(/\b(about|for|on|to|in|of|the|this|that|these|those|pricing|product|services|blog|article|video|case|study|guide|docs|contact|support)\b/.test(n)&&n.split(' ').length>=3){return true;}
if(/^(read|learn|see|view)\s+more\b.*\S/.test(n))return true;if(/^(view|see)\s+(details|all)\b.*\S/.test(n))return true;return false;}
const VAGUE_CTA=new Set(['click here','read more','learn more','see more','view more','details','view details','info','view','go','continue','submit','start','try','try now','get started']);function isVagueName(name){const n=name.toLowerCase().replace(/\s+/g,' ').trim();if(VAGUE_CTA.has(n))return true;if(/^(read|learn|see|view)\s+more[.!>\-–—\s]*$/.test(n))return true;if(/^(view\s+details)[.!>\-–—\s]*$/.test(n))return true;return false;}
function isIconOnlyControl(el){const txt=(el.innerText||el.textContent||'').replace(/\s+/g,'').trim();if(txt)return false;return!!el.querySelector('svg,img,i,svg *');}
function hasFormLabel(el,doc){const tag=(el.tagName||'').toLowerCase();if(!/^(input|select|textarea)$/.test(tag))return true;const type=(el.getAttribute('type')||'').toLowerCase();if(type==='hidden')return true;let p=el.parentElement;for(let i=0;i<3&&p;i++,p=p.parentElement){if((p.tagName||'').toLowerCase()==='label')return true;}
const id=el.getAttribute('id');if(id){const lbl=(doc.querySelector(`label[for="${CSS.escape(id)}"]`)||null);if(lbl&&(lbl.innerText||lbl.textContent||'').trim())return true;}
if(hasAriaName(el,doc))return true;return false;}
function svgDescendantName(el,doc){const svg=el.querySelector('svg');if(!svg)return'';const labelledby=(svg.getAttribute('aria-labelledby')||'').trim();if(labelledby){const txt=getByIdText(doc,labelledby);if(txt)return txt;}
const aria=(svg.getAttribute('aria-label')||'').trim();if(aria)return aria;const t=svg.querySelector('title');const tt=(t&&(t.textContent||'').trim())||'';if(tt)return tt;return'';}
function hasMeaningfulAlt(img,opts={}){const{minLen=4}=opts;if(img.getAttribute('aria-hidden')==='true')return true;const role=(img.getAttribute('role')||'').toLowerCase();if(role==='presentation'||role==='none')return true;const altAttr=img.getAttribute('alt');if(altAttr==null)return false;const alt=altAttr.trim();if(alt.length<minLen){const owner=img.closest('a,button');return owner?linkHasAccessibleName(owner):false;}
if(/^(image|photo|picture|graphic|logo|icon)$/i.test(alt))return false;return true;}
function collectMissingAltImages(doc){const out=[];const d=doc;const win=d.defaultView||window;const imgs=Array.from(d.querySelectorAll('img'));for(const img of imgs){try{if(img.closest('svg'))continue;const cs=win.getComputedStyle(img);const isHidden=cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0;if(isHidden)continue;const r=img.getBoundingClientRect();if(r.width<=2&&r.height<=2)continue;if(!hasMeaningfulAlt(img,{minLen:4})){const src=(img.currentSrc||img.getAttribute('src')||'').trim();out.push({el:img,kind:labelKind(img),role:'img',issue:'alt-missing',src});}}catch(e){}}
return out;};function collectNonButtonSemantics(doc){const d=doc;const win=d.defaultView||window;const candidates=Array.from(d.querySelectorAll('div,span,i,svg,'+
'.button,.btn,.elementor-button,.wp-block-button__link,'+
'[role],[tabindex]')).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el));const out=[];const NATIVE=/^(BUTTON|A|INPUT|SELECT|TEXTAREA)$/;candidates.forEach(el=>{try{const cs=win.getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;if(NATIVE.test((el.tagName||'').toUpperCase()))return;const nativeAncestor=el.closest('a,button,input,select,textarea');if(nativeAncestor&&nativeAncestor!==el)return;if(!isButtonLike(el,cs))return;const containsNative=el.querySelector('a,button,input,select,textarea');const hasRoleAttr=(el.getAttribute('role')||'').trim()!=='';const tiAttr=el.getAttribute('tabindex');const tiNum=tiAttr==null?null:parseInt(tiAttr,10);const hasTab0=tiAttr!==null&&!Number.isNaN(tiNum)&&tiNum>=0;if(!hasRoleAttr&&!hasTab0&&containsNative)return;const role=(el.getAttribute('role')||'').toLowerCase();const hasRoleButton=role==='button';const missingRole=!hasRoleButton;const missingTab=!hasTab0;if(missingRole||missingTab){out.push({el,kind:labelKind(el),role:(el.tagName||'').toLowerCase(),issue:'button-semantics',missingRole,missingTab,tabindex:tiAttr==null?null:tiAttr});}}catch(_){}});return out;}
function navAccessibleLabel(el){const aria=(el.getAttribute('aria-label')||'').trim();if(aria)return aria;const labelledby=(el.getAttribute('aria-labelledby')||'').trim();if(labelledby){const ref=(el.ownerDocument||document).getElementById(labelledby);const txt=(ref&&(ref.innerText||ref.textContent)||'').trim();if(txt)return txt;}
return'';}
function collectDuplicateNavLabels(doc){const d=doc;const navs=Array.from(d.querySelectorAll('nav,[role="navigation"]')).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el));const map=new Map();for(const el of navs){const label=navAccessibleLabel(el);if(!label)continue;const key=label.toLowerCase();if(!map.has(key))map.set(key,[]);map.get(key).push({el,label,kind:labelKind(el)});}
const groups=[];const elements=[];map.forEach((arr,key)=>{if(arr.length>1){groups.push({label:arr[0].label,count:arr.length});arr.forEach(({el,label,kind})=>{elements.push({el,kind,role:'nav',issue:'nav-duplicate-label',ariaLabel:label});});}});return{groups,elements,total:elements.length};}
function collectNonClampFontSize(doc){const d=doc;const win=d.defaultView||window;const selectors=['h1,h2,h3,h4,h5,h6','p,li,blockquote,figcaption,dd,dt,pre','.wp-block-paragraph,.wp-block-list,.elementor-widget-text-editor,.elementor-heading-title','a,button,[role="button"],.button,.btn,.elementor-button,.wp-block-button__link'].join(',');const raw=Array.from(d.querySelectorAll(selectors)).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el)).filter(el=>!isSkipLink(el));const now=Date.now();let clampInfo=__CLAMP_CACHE__.info;if(!clampInfo||(now-__CLAMP_CACHE__.time)>1500){clampInfo=collectClampInfo(d);__CLAMP_CACHE__={time:now,info:clampInfo};}
const usingClamp=elementsUsingClampForProp(d,'font-size',clampInfo);const out=[];const seen=new Set();raw.forEach(el=>{try{const cs=win.getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;const txt=(el.innerText||el.textContent||'').trim();const hasIcon=!!el.querySelector('svg,img,svg *');const buttonLike=isButtonLike(el,cs);if(!txt&&!(buttonLike&&hasIcon))return;const heading=/^h[1-6]$/i.test(el.tagName||'');if(isInMenuContext(el)&&!heading&&!buttonLike)return;let rep=el;if(buttonLike){rep=el.closest('a,button,[role="button"],.button,.btn,.elementor-button,.wp-block-button__link')||el;}
if(seen.has(rep))return;if(usesClampViaCascade(rep,usingClamp))return;const size=parseFloat(win.getComputedStyle(rep).fontSize)||0;seen.add(rep);out.push({el:rep,kind:labelKind(rep),role:(rep.tagName||'').toLowerCase(),issue:'non-clamp-font',sel:labelSelectorForNonClamp(rep),fontSize:Number(size.toFixed(1))});}catch(_){}});return out;}
function collectAccessibleNameIssues(doc){const d=doc;const win=d.defaultView||window;const out=[];const ctrls=Array.from(d.querySelectorAll('a,button,[role="button"]')).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el));ctrls.forEach(el=>{try{const cs=win.getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;if(!isButtonLike(el,cs))return;const name=getAccessibleName(el,d);const iconOnly=isIconOnlyControl(el);const svgOnlyName=!name&&svgDescendantName(el,d);if(svgOnlyName){out.push({el,kind:labelKind(el),role:(el.tagName||'').toLowerCase(),issue:'accessible-name',sub:'svg-title-only',name:svgOnlyName,hint:'Name comes only from an inline SVG (<title>/aria). Prefer visible text or aria-label/aria-labelledby on the link/button.'});}
if(iconOnly&&!hasAriaName(el,d)&&!svgOnlyName){out.push({el,kind:labelKind(el),role:(el.tagName||'').toLowerCase(),issue:'accessible-name',sub:'icon-only-no-label',name:'',hint:'Add aria-label or visually hidden text for icon-only control.'});return;}
if(name&&isVagueName(name)&&!hasSpecificContext(name)){out.push({el,kind:labelKind(el),role:(el.tagName||'').toLowerCase(),issue:'accessible-name',sub:'vague',name,hint:'Make the name specific (e.g., “Read more about Pricing”). Prefer visible text or aria-labelledby.'});}
if((el.tagName||'').toLowerCase()==='a'){const hasImg=!!el.querySelector('img');if(hasImg&&!linkHasAccessibleName(el)){out.push({el,kind:labelKind(el),role:'a',issue:'accessible-name',sub:'image-link-no-name',name:'',hint:'Linked image needs meaningful alt on the <img>, or use aria-label/aria-labelledby on the link.'});}}}catch(_){}});const inputs=Array.from(d.querySelectorAll('input,select,textarea')).filter(el=>!panel.contains(el)&&!btn.contains(el)).filter(el=>!isIgnoredChrome(el)).filter(el=>!isBuilderChrome(el));inputs.forEach(el=>{try{const cs=win.getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||parseFloat(cs.opacity)===0)return;const type=(el.getAttribute('type')||'').toLowerCase();if(type==='hidden')return;if(!hasFormLabel(el,d)){out.push({el,kind:labelKind(el),role:(el.tagName||'').toLowerCase(),issue:'accessible-name',sub:'form-missing-label',name:'',hint:'Form controls require a visible <label>, aria-label, or aria-labelledby.'});}}catch(_){}});return out;}
function audit(doc){const mains=Array.from(doc.getElementsByTagName('main'));const headers=Array.from(doc.getElementsByTagName('header'));const footers=Array.from(doc.getElementsByTagName('footer'));const issues=[];if(mains.length===0){issues.push({key:'main_missing',title:'MAIN: Missing',message:'There must be just one Main. No <code>&lt;main&gt;</code> element was found wrapping the unique page content.',fixes:['<b>Elementor:</b> Set top container HTML Tag to <code>main</code>.','<b>Gutenberg:</b> Ensure template outputs a single <code>&lt;main&gt;</code>.'],elements:[]});}else if(mains.length>1){issues.push({key:'main_multiple',title:`MAIN: Multiple (${mains.length})`,message:'There must be just one Main.',fixes:['Reduce page to a single <code>&lt;main&gt;</code>.'],elements:mains.map(el=>({el,kind:labelKind(el)}))});}
if(headers.length===0){issues.push({key:'header_missing',title:'HEADER: Missing',message:'There should be one <code>&lt;header&gt;</code> landmark wrapping the top of the page.',fixes:['Add a <code>&lt;header&gt;</code> element at the top of the document.'],elements:[]});}else if(headers.length>1){issues.push({key:'header_multiple',title:`HEADER: Multiple (${headers.length})`,message:'There should be at most one Header landmark.',fixes:['Change extra <code>header</code> to <code>div</code>.'],elements:headers.map(el=>({el,kind:labelKind(el)}))});}
if(footers.length===0){issues.push({key:'footer_missing',title:'FOOTER: Missing',message:'There should be one <code>&lt;footer&gt;</code> landmark wrapping the bottom of the page.',fixes:['Add a <code>&lt;footer&gt;</code> element at the bottom of the document.'],elements:[]});}else if(footers.length>1){issues.push({key:'footer_multiple',title:`FOOTER: Multiple (${footers.length})`,message:'There should be at most one Footer landmark.',fixes:['Change extra <code>footer</code> to <code>div</code>.'],elements:footers.map(el=>({el,kind:labelKind(el)}))});}
const headings=Array.from(doc.querySelectorAll('h1,h2,h3,h4,h5,h6'));const h1s=headings.filter(h=>h.tagName.toLowerCase()==='h1');const headingSkips=[];let lastVirtual=null,lastContainer=null;function reset(){lastVirtual=null;}
for(let i=0;i<headings.length;i++){const node=headings[i];const lvl=+node.tagName.slice(1);const cKey=containerKeyFor(node);if(cKey!==lastContainer){reset();lastContainer=cKey;}
if(lastVirtual===null){lastVirtual=lvl;continue;}
const min=lastVirtual;const max=Math.min(6,lastVirtual+1);if(lvl<min){const suggest=Math.min(6,lastVirtual+1);headingSkips.push({prev:headings[i-1],curr:node,from:lastVirtual,to:lvl,suggest,kind:labelKind(node)});lastVirtual=suggest;}else if(lvl>max){const suggest=Math.min(6,lastVirtual+1);headingSkips.push({prev:headings[i-1],curr:node,from:lastVirtual,to:lvl,suggest,kind:labelKind(node)});lastVirtual=suggest;}else{lastVirtual=lvl;}}
if(h1s.length===0){issues.push({key:'h1_missing',title:'HEADINGS: Missing H1',message:'Exactly one <code>&lt;h1&gt;</code> is required.',fixes:['Add a page title as <code>H1</code>.'],elements:[]});}else if(h1s.length>1){issues.push({key:'h1_multiple',title:`HEADINGS: Multiple H1 (${h1s.length})`,message:'There must be only one <code>&lt;h1&gt;</code>.',fixes:['Change extra H1s to <code>H2/H3</code>.'],elements:h1s.map(el=>({el,kind:labelKind(el)}))});}
if(headingSkips.length){issues.push({key:'heading_skips',title:`HEADINGS: Order skips levels (${headingSkips.length})`,message:'Headings should move forwards; H1 → H2, or can be the same; H2 → H2. Do not go backwards or skip levels.',fixes:['Adjust so that each step changes by at most one level and does not go backwards.'],elements:headingSkips.map(s=>({el:s.curr,kind:s.kind||labelKind(s.curr),from:s.from,to:s.to,suggest:s.suggest}))});}
const skipIssue=collectSkipLinkIssue(doc);if(skipIssue&&(!skipIssue.elements||!skipIssue.elements.length||skipIssue.elements.some(e=>e.sub!=='ok'))){issues.push(skipIssue);}
const contrastFails=collectContrastFailures(doc);if(contrastFails.length){issues.push({key:'contrast_aa',title:`ACCESSIBILITY: Color contrast (AA) failures (${contrastFails.length})`,message:'Text must be ≥4.5:1 (or 3:1 if “large”). Buttons/controls must also have their background/border at ≥3:1 vs the adjacent background (non-text contrast).',fixes:['Large text 24px regular or 18.66px bold must be ≥3:1. Other text should be ≥4.5:1.','Increase contrast by changing text (foreground) or the background.','Button fill or border must be ≥3:1 vs the page/section background.','Ensure states (hover/focus/active) also meet contrast.'],elements:contrastFails.map(f=>({el:f.el,kind:f.kind||'unknown',role:f.role,contrastType:f.contrastType,ratio:f.ratio,required:f.required,fontSize:f.fontSize,fontWeight:f.fontWeight,fgHex:f.fgHex,bgHex:f.bgHex,adjHex:f.adjHex,borderHex:f.borderHex,suggestFG:f.suggestFG,suggestBG:f.suggestBG}))});}
const smallTextFails=collectSmallTextFailures(doc);if(smallTextFails.length){issues.push({key:'text_min_16',title:`ACCESSIBILITY: Text below 16px (${smallTextFails.length})`,message:'Body text should be at least 16px for readability. Smaller sizes can be difficult to read.',fixes:['Increase base/body font size to ≥ 16px.','If space is tight, ensure good contrast and line-height.'],elements:smallTextFails});}
const sizeFails=collectControlMinSizeFailures(doc);if(sizeFails.length){issues.push({key:'control_min_size',title:`ACCESSIBILITY: Button minimum size (24×24) failures (${sizeFails.length})`,message:'Interactive controls should have a minimum visible target size of 24×24px.',fixes:['Increase padding or line-height, or switch to a larger button style.','Ensure icon-only buttons have at least 24×24 px of clickable area.'],elements:sizeFails.map(s=>({el:s.el,kind:s.kind||'unknown',role:s.role,width:s.width,height:s.height,requiredW:s.requiredW,requiredH:s.requiredH}))});}
const spacingFails=collectMobileControlSpacingFailures(doc);if(spacingFails.length){issues.push({key:'mobile_control_spacing',title:`ACCESSIBILITY: Mobile control spacing (≥12px) failures (${spacingFails.length})`,message:'On mobile, interactive controls should be separated by at least 12px of clear space.',fixes:['Increase gap/margin between adjacent buttons/controls on mobile breakpoints.','Ensure stacked buttons have ≥12px margin-bottom / gap.'],elements:spacingFails.map(s=>({el:s.el,kind:s.kind||'unknown',role:s.role,spaceType:s.spaceType,dist:s.dist,required:s.required,partnerText:s.partnerText}))});}
const nonModernImages=collectNonModernImages(doc);if(nonModernImages.length){issues.push({key:'images_nonmodern',title:`IMAGES: Non-modern formats (${nonModernImages.length})`,message:'Images must use modern formats for performance. Convert to WebP or AVIF.',fixes:['Export assets as WebP or AVIF.','Avoid PNG/JPG unless there is a hard requirement.'],elements:nonModernImages});}
const missingAltImages=collectMissingAltImages(doc);if(missingAltImages.length){issues.push({key:'images_alt_missing',title:`IMAGES: Alt-Text Description Missing (${missingAltImages.length})`,message:'Meaningful alt text is required for informative images. Use empty <code>alt=""</code> only for purely decorative images (or set <code>role="presentation"</code>/<code>aria-hidden="true"</code>).',fixes:['Add concise, specific descriptions.','Images in the Header and Footer may adopt the Title as the Alt.','If the image is decorative, set <code>alt=""</code> or use <code>role="presentation"</code> / <code>aria-hidden="true"</code>.',],elements:missingAltImages});}
const dupNav=collectDuplicateNavLabels(doc);if(dupNav.total){const groupSummary=dupNav.groups.map(g=>`“${g.label}” × ${g.count}`).join('; ');issues.push({key:'nav_duplicate_labels',title:`NAV: Multiple menus share the same aria-label (${dupNav.groups.length} label${dupNav.groups.length>1?'s':''})`,message:`Multiple <code>&lt;nav&gt;</code> landmarks reuse the same accessible name, which can confuse screen-reader users when jumping between navigation regions. Duplicates: ${groupSummary}.`,fixes:['Give each navigation landmark a distinct, descriptive name via <code>aria-label</code> (or <code>aria-labelledby</code>).','Examples: <code>aria-label="Primary navigation"</code>, <code>"Secondary navigation"</code>, <code>"Footer navigation"</code>, or <code>"Additional site navigation"</code>.'],elements:dupNav.elements});}
const nonClampFont=collectNonClampFontSize(doc);if(nonClampFont.length){issues.push({key:'font_no_clamp',title:`TYPOGRAPHY: font-size without clamp() (${nonClampFont.length})`,message:'These text elements use a fixed font-size. Responsive fonts are more fluid.',fixes:['Swap fixed font-size for a clamp().','Use the Font Clamp Calculator.',],elements:nonClampFont});}
const accessibleNameFails=collectAccessibleNameIssues(doc);if(accessibleNameFails.length){issues.push({key:'aria_label',title:`ACCESSIBILITY: Aria-Labels for Vague or Missing descriptions (${accessibleNameFails.length})`,message:'Controls and links must have a clear accessible name. Avoid vague CTAs (“Read more”, “Click here”), label icon-only controls, ensure linked images are named, and label all form fields.',fixes:['Prefer specific, visible text on the control.','If needed, add aria-label="Contact Me", or use Custom Attributes: aria-label|Contact Me','Linked images: give the <img> a meaningful alt (or label the link).','Form fields: associate a <label> or use aria-label.'],elements:accessibleNameFails});}
const nonButtonSem=collectNonButtonSemantics(doc);if(nonButtonSem.length){issues.push({key:'button_semantics',title:`ACCESSIBILITY: Non-native buttons missing role/tabindex (${nonButtonSem.length})`,message:'Non-native elements (e.g., <div>/<span>) used as buttons must expose button semantics and be keyboard focusable.',fixes:['Add role="button" to non-native interactive elements.','Add tabindex="0" so they are focusable via keyboard.','Ensure Enter and Space activate the control (keyup for Enter, keydown for Space).'],elements:nonButtonSem});}
const ctaCandidates=collectCTACandidates(doc);if(ctaCandidates.length===0){issues.push({key:'cta_missing',title:'CONTENT: No primary CTA found',message:'No obvious call-to-action (button or prominent action link) was detected outside navigation. Pages should guide users with at least one clear next step.',fixes:['Add a prominent button or action link (e.g., “Contact us”, “Get a quote”, “Book a demo”).','Place it near the top of the page and/or after key sections.','Ensure it is visually distinct from body links.'],elements:[]});}
const longHeadings=collectLongHeadings(doc);if(longHeadings.length){issues.push({key:'heading_too_long',title:`CONTENT: Headings too long (${longHeadings.length})`,message:`Headings should be scannable. Aim for ≤ ${HEADING_WORD_LIMIT} words or ≤ ${HEADING_CHAR_LIMIT} characters.`,fixes:[`Trim to ≤ ${HEADING_WORD_LIMIT} words or ≤ ${HEADING_CHAR_LIMIT} characters.`,'Move supporting detail into body text or a subheading.'],elements:longHeadings});}
return{issues,counts:{main:mains.length,header:headers.length,footer:footers.length,h1:h1s.length,headingSkips:headingSkips.length,contrastFails:contrastFails.length,controlMinSize:sizeFails.length,mobileSpacing:spacingFails.length,imagesNonModern:nonModernImages.length,imagesAltMissing:missingAltImages.length,smallText:smallTextFails.length,navDuplicateLabels:dupNav.total,nonClampFont:nonClampFont.length,accessibleNames:accessibleNameFails.length,ctaCandidates:ctaCandidates.length,headingsLong:longHeadings.length,skipLink:(skipIssue&&(!skipIssue.elements||!skipIssue.elements.length||skipIssue.elements.some(e=>e.sub!=='ok')))?1:0,buttonSemantics:nonButtonSem.length}};}
function cssPath(el){if(!el||!(el.nodeType===1)){return'';}
const doc=el.ownerDocument||document;if(!window.CSS||typeof CSS.escape!=='function'){window.CSS=window.CSS||{};CSS.escape=CSS.escape||function(v){return String(v).replace(/[\0-\x1f\x7f]/g,'\uFFFD').replace(/^[0-9]/,'\\3$& ').replace(/[^a-zA-Z0-9_\u00A0-\uFFFF-]/g,'\\$&');};}
if(el.id){const s='#'+CSS.escape(el.id);try{if(doc.querySelectorAll(s).length===1)return s;}catch(_){}}
const parts=[];let node=el;while(node&&node.nodeType===1&&node!==doc.documentElement){let part=node.nodeName.toLowerCase();const raw=(node.className||'').toString().trim();if(raw){const classes=raw.split(/\s+/).filter(c=>c&&!/^(active|current|selected|hover|focus|open|opened|closing|loading)$/.test(c));if(classes.length)part+='.'+CSS.escape(classes[0]);}
const parent=node.parentElement;if(parent){const sameTag=Array.from(parent.children).filter(n=>n.tagName===node.tagName);if(sameTag.length>1){const idx=sameTag.indexOf(node)+1;part+=`:nth-child(${idx})`;}}
parts.unshift(part);const candidate=parts.join(' > ');try{if(doc.querySelectorAll(candidate).length===1){return candidate;}}catch(_){}
node=parent;}
if(parts.length)return parts.join(' > ');const tag=(el.tagName||'node').toLowerCase();const c0=((el.className||'')+'').split(/\s+/).filter(Boolean)[0];if(el.id)return`${tag}#${el.id}`;if(c0)return`${tag}.${c0}`;return tag;}
function labelSelectorForSmallText(el){const doc=el.ownerDocument||document;const ROOTS=['nav.elementor-nav-menu--dropdown','nav.elementor-nav-menu--main','.elementor-widget-nav-menu','.wp-block-navigation','nav[role="navigation"]','nav'].join(',');const root=el.closest(ROOTS);if(root){const tag=root.tagName.toLowerCase();const cls=((root.className||'')+'').trim().split(/\s+/).find(Boolean);return cls?`${tag}.${cls}`:tag;}
const a=el.closest('[class]');if(a){const tag=a.tagName.toLowerCase();const cls=((a.className||'')+'').trim().split(/\s+/).find(Boolean);return cls?`${tag}.${cls}`:tag;}
return(el.tagName||'node').toLowerCase();}
const HAS_CLAMP=v=>!!(v&&String(v).includes('clamp('));const READABLE=s=>{try{void s.cssRules;return true;}catch(e){return false;}};function collectClampInfo(doc){const win=doc.defaultView||window;const matchesMedia=media=>{if(!media||!media.mediaText)return true;try{return win.matchMedia(media.mediaText).matches;}catch(_){return true;}};const byProp=new Map();const clampTokens=new Set();const addSel=(prop,sel)=>{if(!byProp.has(prop))byProp.set(prop,new Set());byProp.get(prop).add(sel);};function scan(list){for(const rule of list){if(rule.type===CSSRule.MEDIA_RULE){if(matchesMedia(rule.media))scan(rule.cssRules);continue;}
if(rule.type===CSSRule.SUPPORTS_RULE){scan(rule.cssRules);continue;}
if(rule.type!==CSSRule.STYLE_RULE)continue;const st=rule.style;if(!st)continue;for(let i=0;i<st.length;i++){const p=st[i];if(p.startsWith('--')&&HAS_CLAMP(st.getPropertyValue(p)))clampTokens.add(p.trim());}
for(let i=0;i<st.length;i++){const p=st[i];if(HAS_CLAMP(st.getPropertyValue(p)))addSel(p,rule.selectorText);}
for(let i=0;i<st.length;i++){const p=st[i];const v=st.getPropertyValue(p);const m=v&&v.match(/var\(\s*(--[A-Za-z0-9_-]+)/g);if(!m)continue;for(const ref of m){const name=ref.replace(/^var\(\s*/,'').trim();if(clampTokens.has(name)){addSel(p,rule.selectorText);break;}}}}}
for(const sheet of Array.from(doc.styleSheets)){if(!READABLE(sheet))continue;try{scan(sheet.cssRules);}catch(_){}}
return{byProp,clampTokens};}
function elementsUsingClampForProp(doc,prop,clampInfo){const out=new Set();const{byProp,clampTokens}=clampInfo;const selSet=byProp.get(prop);if(selSet){for(const sel of selSet){try{doc.querySelectorAll(sel).forEach(n=>out.add(n));}catch(_){}}}
try{doc.querySelectorAll('[style*="clamp("]').forEach(n=>{const v=n.style.getPropertyValue(prop);if(v&&v.includes('clamp('))out.add(n);});}catch(_){}
if(clampTokens&&clampTokens.size){const toks=Array.from(clampTokens);try{doc.querySelectorAll('[style]').forEach(n=>{const v=n.style.getPropertyValue(prop);if(!v)return;for(const t of toks){if(v.includes(`var(${t}`)){out.add(n);break;}}});}catch(_){}}
return out;}
function usesClampViaCascade(el,usingClampSet){let n=el;for(let i=0;i<10&&n&&n.nodeType===1;i++){if(usingClampSet.has(n))return true;n=n.parentElement;}
return false;}
function labelSelectorForNonClamp(el){return labelSelectorForSmallText(el);}
function esc(s){return String(s).replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));}
function renderPanel(result,doc){const{issues,counts}=result;renderTogglesFor(issues);const visibleIssues=issues.filter(iss=>!isHiddenEffective(iss.key));const hiddenSig=Array.from(HIDDEN).sort().join(',');const sig=`${counts.main}|${counts.header}|${counts.footer}|${counts.h1}|${counts.headingSkips}|${counts.contrastFails}|${counts.controlMinSize}|${counts.mobileSpacing}|${counts.imagesNonModern}|${counts.imagesAltMissing}|${counts.smallText}|${counts.navDuplicateLabels}|${counts.nonClampFont}|${counts.accessibleNames}|${counts.ctaCandidates}|${counts.headingsLong}|${counts.skipLink}|${counts.buttonSemantics}|${issues.length}|hidden:${hiddenSig}`;if(!INTERACTING&&sig===lastSignature&&content.__renderedOnce)return;lastSignature=sig;content.__renderedOnce=true;clearHighlights(doc);const rowStyle='margin:6px 0;padding:8px 10px;background:#fafafa;border:1px solid #eee;border-radius:6px;font-size:12px;color:#333;display:flex;align-items:flex-start;gap:8px;cursor:pointer';const getLabelText=(el)=>{if(!el)return'';const txt=(el.innerText||el.textContent||'').trim().replace(/\s+/g,' ');if(txt)return txt.slice(0,140)+(txt.length>140?'…':'');const alt=el.getAttribute?.('aria-label')||el.getAttribute?.('alt')||el.getAttribute?.('title');return(alt||'').trim();};let html='';visibleIssues.forEach((issue,idx)=>{const els=(issue.elements||[]).slice();const isOpen=OPEN.get(issue.key)===true;html+=`
            <section class="audit-acc" data-issue="${idx}" data-key="${issue.key}"
                     style="margin:10px 0;border:1px solid #efefef;border-radius:10px;overflow:hidden">
              <button type="button" class="audit-acc-head" aria-expanded="${isOpen?'true':'false'}"
                      style="all:unset;display:flex;align-items:center;gap:8px;width:100%;padding:10px 12px;cursor:pointer;background:#fafafa;border-bottom:1px solid #f0f0f0;font-size:13px;line-height:1.45">
                <span class="audit-acc-chevron" aria-hidden="true"
                      style="display:inline-block;transform:${isOpen?'rotate(90deg)':'rotate(0deg)'};transition:transform .18s ease">▶</span>
				<span style="font-weight:700;font-size:13px">#${idx+1} — ${esc(issue.title)}</span>
              </button>
              <div class="audit-acc-body" ${isOpen?'':'hidden'} style="padding:10px;background:#fff">
                ${issue.message ? `<div style="margin-bottom:8px">${issue.message}</div>` : '' }
                ${(els.length)?`<div class="audit-els"data-count="${els.length}">${els.map((o,elIdx)=>{let meta='';if(o.contrastType==='text-vs-bg'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Text vs Background</b> Contrast ${o.ratio}:1; needs ≥ ${o.required}:1; font ${o.fontSize}px/${o.fontWeight}; text ${o.fgHex} on bg ${o.bgHex}. Suggested: <b>text ${o.suggestFG}</b> or <b>bg ${o.suggestBG}</b>.`;}else if(o.contrastType==='bg-vs-adj'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Background vs Page Background</b> Contrast ${o.ratio}:1; needs ≥ ${o.required}:1; button bg ${o.bgHex} on page bg ${o.adjHex}. Suggested: <b>button bg ${o.suggestBG}</b>.`;}else if(o.contrastType==='border-vs-adj'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Border vs Page Background</b> Contrast ${o.ratio}:1; needs ≥ ${o.required}:1; border ${o.borderHex} on page bg ${o.adjHex}. Suggested: <b>border ${o.suggestBG}</b>.`;}else if(typeof o.width==='number'&&typeof o.height==='number'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Control size</b> ${o.width}×${o.height}px; needs ≥ ${o.requiredW}×${o.requiredH}px.`;}else if(o.spaceType==='mobile-spacing'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Mobile control spacing</b> ${o.dist}px; needs ≥ ${o.required}px; too close to “${o.partnerText||'another control'}”.`;}else if(typeof o.ratio==='number'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) Contrast ${o.ratio}:1; needs ≥ ${o.required}:1.`;}else if(typeof o.from==='number'&&typeof o.to==='number'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) Detected jump H${o.from} → H${o.to}. Suggested: H${o.suggest}.`;}else if(o.issue==='nonmodern'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Image format</b> ${o.src || '(no src)'}; must be <b>WebP</b> or <b>AVIF</b>.`;}else if(o.issue==='alt-missing'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Alt text missing</b> ${o.src || '(no src)'} — add meaningful <code>alt</code> or mark decorative with <code>alt=""</code>.`;}else if(o.issue==='small-text'){const sel=labelSelectorForSmallText(o.el);meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'} • ${sel}) `+
`<b>Small text</b> ${o.fontSize}px; needs ≥ ${o.required}px.`;}else if(o.issue==='nav-duplicate-label'){const sel=(o.el&&(o.el.id?`#${o.el.id}`:(o.el.className||'').toString().split(/\s+/).filter(Boolean)[0]))||'nav';const shortSel=sel?`nav${sel.startsWith('#')?sel:'.'+sel}`:'nav';meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'} • ${shortSel}) `+
`<b>Duplicate nav aria-label</b> “${o.ariaLabel}”.`;}else if(o.issue==='non-clamp-font'){const sel=o.sel||labelSelectorForNonClamp(o.el);meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'} • ${sel}) `+
`<b>font-size not using clamp()</b> (computed ${o.fontSize}px).`;}else if(o.issue==='accessible-name'){if(o.sub==='vague'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) `+
`<b>Vague CTA</b> “${o.name}”. ${o.hint}`;}else if(o.sub==='icon-only-no-label'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) `+
`<b>Icon-only control without accessible name</b>. ${o.hint}`;}else if(o.sub==='image-link-no-name'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) `+
`<b>Linked image without accessible name</b>. ${o.hint}`;}else if(o.sub==='form-missing-label'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) `+
`<b>Form field missing label</b>. ${o.hint}`;}else if(o.sub==='svg-title-only'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) `+
`<b>SVG-only accessible name</b> “${o.name}”. ${o.hint}`;}else{meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) Accessible name issue.`;}}else if(o.issue==='heading-long'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) `+
`<b>Heading too long</b> H${o.level || '?'} — ${o.words} words / ${o.chars} chars; `+
`aim ≤ ${HEADING_WORD_LIMIT} words or ≤ ${HEADING_CHAR_LIMIT} chars.`;}else if(o.issue==='skiplink'){if(o.sub==='ok'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) ✓ Skip link present and early in tab order.`;}else if(o.sub==='target-missing'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Skip link target missing</b> — ${o.hint}`;}else if(o.sub==='target-not-main'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Skip link target isn’t the main region</b> — ${o.hint}`;}else if(o.sub==='late'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Skip link appears late in tab order</b> (tab index ~ ${o.index}). ${o.hint}`;}else if(o.sub==='maybe-not-visible-on-focus'){meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) <b>Skip link may remain invisible on focus</b> — ${o.hint}`;}else{meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) Skip link check.`;}}else if(o.issue==='button-semantics'){const bits=[];if(o.missingRole)bits.push('missing role="button"');if(o.missingTab)bits.push(`missing tabindex="0"${o.tabindex!=null ? `(found tabindex="${o.tabindex}")` : ''}`);meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) `+
`<b>Non-native button</b> — ${bits.join('; ')}.`;}else{const text=getLabelText(o.el);meta=`(builder:${o.kind?.split(':')[1]||o.kind||'unknown'}) ${text}`;}
return`<div class="audit-el-block" data-elidx="${elIdx}" style="${rowStyle}">
                      <div class="audit-row-text" style="flex:1;min-width:0">${meta}</div>
                    </div>`;}).join('')}</div>`:''
                }
                ${issue.fixes && issue.fixes.length ? `<div style="font-size:12px;color:#666;margin:8px 0 4px 0">How to fix:</div><ol style="margin:0 0 0 18px;padding:0">${issue.fixes.map(step=>`<li style="margin:4px 0">${step}</li>`).join('')}</ol>` : ''}
              </div>
            </section>`;});content.innerHTML=html;const accHeads=content.querySelectorAll('.audit-acc-head');accHeads.forEach(head=>{head.setAttribute('tabindex','0');head.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();head.click();}});head.addEventListener('click',()=>{INTERACTING=true;const section=head.parentElement;const body=head.nextElementSibling;const key=section.getAttribute('data-key');const nowOpen=head.getAttribute('aria-expanded')!=='true';OPEN.set(key,nowOpen);head.setAttribute('aria-expanded',String(nowOpen));head.querySelector('.audit-acc-chevron').style.transform=nowOpen?'rotate(90deg)':'rotate(0deg)';body.hidden=!nowOpen;if(nowOpen){const issueIdx=+section.getAttribute('data-issue');const blocks=section.querySelectorAll('.audit-el-block');const issue=visibleIssues[issueIdx];let hoverOff=null;blocks.forEach(b=>{if(b.__auditBound)return;b.__auditBound=true;const elIdx=+b.getAttribute('data-elidx');const obj=(issue.elements||[])[elIdx];if(!obj||!obj.el)return;b.addEventListener('mouseenter',()=>{try{obj.el.style.outline='5px dashed #e53935';obj.el.classList.add('audit-highlight');hoverOff=createOverlayFor(obj.el,doc);}catch(e){}});b.addEventListener('mouseleave',()=>{try{obj.el.style.outline='';obj.el.classList.remove('audit-highlight');if(hoverOff){hoverOff();hoverOff=null;}}catch(e){}});b.addEventListener('click',()=>{try{obj.el.scrollIntoView({behavior:'smooth',block:'center'});highlightOnce(obj.el,doc);}catch(e){}});});}else{clearHighlights(doc);}
setTimeout(()=>{INTERACTING=false;},180);});});if(panel.style.display==='block')addHeadingBadges(doc);else removeHeadingBadges(doc);}
let current=findPreviewDoc();function startObserver(targetDoc){if(!panelOpen())return;stopObserver();const root=targetDoc.documentElement||targetDoc.body||targetDoc;const fire=()=>{if(INTERACTING||!panelOpen())return;const res=audit(targetDoc);renderPanel(res,targetDoc);};const debounced=()=>{if(debTimer)clearTimeout(debTimer);debTimer=setTimeout(fire,120);};mo=new(window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver)(debounced);try{mo.observe(root,{childList:true,subtree:true,attributes:true,characterData:true});}catch(e){}
heartbeat=setInterval(fire,800);resizeHandler=debounced;window.addEventListener('resize',resizeHandler,{passive:true});fire();}
function attachIframeWatchers(){if(!panelOpen())return;document.querySelectorAll('iframe').forEach(ifr=>{ifr.addEventListener('load',()=>{if(!panelOpen())return;try{const fdoc=ifr.contentDocument||ifr.contentWindow.document;if(fdoc&&fdoc.body){current={doc:fdoc,iframe:ifr};startObserver(fdoc);}}catch(e){current={doc:document,iframe:null};startObserver(document);}});});}
function startTopWatcher(){if(!panelOpen())return;try{topMO=new MutationObserver(()=>{if(!panelOpen())return;const again=findPreviewDoc();if(again.doc&&again.doc!==current.doc){removeHeadingBadges(current.doc);current=again;startObserver(again.doc);attachIframeWatchers();}});topMO.observe(document.documentElement,{childList:true,subtree:true});}catch(e){}}
btn.addEventListener('click',()=>{const opening=panel.style.display==='none'||panel.style.display==='';panel.style.display=opening?'block':'none';btn.setAttribute('aria-pressed',opening?'true':'false');btn.setAttribute('aria-label',opening?'Close build audit panel':'Open build audit panel');if(opening){current=findPreviewDoc();const res=audit(current.doc);renderPanel(res,current.doc);addHeadingBadges(current.doc);startObserver(current.doc);attachIframeWatchers();startTopWatcher();}else{stopObserver();removeHeadingBadges(current.doc);clearHighlights(current.doc);}});current=findPreviewDoc();window.addEventListener('beforeunload',()=>{try{stopObserver();}catch(e){}});})();</script>
    <?php
}
add_action('wp_footer', 'add_landmark_audit_guide');
add_action('admin_footer', 'add_landmark_audit_guide');
add_action('elementor/editor/after_enqueue_scripts', 'add_landmark_audit_guide');
				
			

skip-to-content-fix

				
					add_action('wp_footer', function () {
    ?>
    <script type="text/phast">window.addEventListener("DOMContentLoaded",()=>{const existingMain=document.querySelector("main");if(existingMain){if(!existingMain.id||existingMain.id.trim().length===0){existingMain.id="content";}
return;}
const wrapper=document.querySelector('[data-elementor-type="single"], [data-elementor-type="single-post"], [data-elementor-type="wp-page"], [data-elementor-type="wp-post"]');if(wrapper&&wrapper.parentElement&&!wrapper.closest("main")){const mainTag=document.createElement("main");mainTag.id="content";wrapper.parentElement.insertBefore(mainTag,wrapper);mainTag.appendChild(wrapper);}});</script>
    <?php
});
				
			

conditional-logic-simple

				
					<style>.elementor-field-group[data-conditional-hidden="true"]{display:none !important;}input[type="checkbox"],input[type="radio"]{accent-color:#ff0050;appearance:auto !important;display:inline-block;vertical-align:middle;width:15px;height:15px;cursor:pointer;}input[type="checkbox"]:checked + label,input[type="radio"]:checked + label{font-weight:bold;color:#ff0050;}.elementor-field-option,.elementor-field-subgroup{display:flex;align-items:center;font-size:15px;margin-bottom:15px;gap:6px;}</style>

<script type="application/json" id="form-logic-rules">[["cond_website_options","reason","equals","Websites"],["cond_seo_options","reason","equals","SEO"],["cond_consultation_options","reason","equals","Consultation"],["cond_budget","cond_website_options","equals","Brand New Site","reason","Websites"]]</script>

<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const logicScript=document.getElementById('form-logic-rules');if(!logicScript)return;let rules;try{rules=JSON.parse(logicScript.textContent);}catch(error){console.error('Invalid form logic JSON:',error);return;}
const getFieldElements=(fieldName)=>document.querySelectorAll(`[name="form_fields[${fieldName}]"], [name="form_fields[${fieldName}][]"]`);const getFieldWrapper=(fieldId)=>{const field=document.querySelector(`[id^="form-field-${fieldId}"]`);return field?field.closest('.elementor-field-group'):null;};const evaluateRules=()=>{rules.forEach(rule=>{const[target,field,operator,value,dependsOn,dependsValue]=rule;const triggerFields=getFieldElements(field);const targetWrapper=getFieldWrapper(target);if(!triggerFields.length||!targetWrapper){console.warn('Missing trigger or target field for rule:',rule);return;}
let match=false;triggerFields.forEach(field=>{const fieldValue=(field.value||'').trim().toLowerCase();const expected=value.trim().toLowerCase();if((field.type==='checkbox'||field.type==='radio')?(field.checked&&fieldValue===expected):(fieldValue===expected)){match=true;}});if(dependsOn&&dependsValue){const parentFields=getFieldElements(dependsOn);let parentMatch=false;parentFields.forEach(parentField=>{const parentValue=(parentField.value||'').trim().toLowerCase();const expected=dependsValue.trim().toLowerCase();if((parentField.type==='checkbox'||parentField.type==='radio')?(parentField.checked&&parentValue===expected):(parentValue===expected)){parentMatch=true;}});match=match&&parentMatch;}
if(match){targetWrapper.removeAttribute('data-conditional-hidden');}else{targetWrapper.setAttribute('data-conditional-hidden','true');}});};const allFields=document.querySelectorAll('[name^="form_fields["]');allFields.forEach(field=>{field.addEventListener('change',evaluateRules);field.addEventListener('input',evaluateRules);});document.querySelectorAll('[id^="form-field-cond_"]').forEach(field=>{const wrapper=field.closest('.elementor-field-group');if(wrapper){wrapper.setAttribute('data-conditional-hidden','true');}});evaluateRules();});</script>
				
			

flip-desktop-click-mobile-click

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){document.querySelectorAll('.flipper').forEach(function(card){card.addEventListener('click',function(e){if(e.target.closest('a, button'))return;const isFlipped=card.classList.contains('flipped');document.querySelectorAll('.flipper.flipped').forEach(el=>{el.classList.remove('flipped');});if(!isFlipped){card.classList.add('flipped');}});});});</script>
<style>.flipper{transition:0.3s;transform-style:preserve-3d;position:relative;width:300px;height:400px;}.flipper.flipped{transform:rotateY(180deg);}.front,.back{backface-visibility:hidden;position:absolute;width:100%;height:100%;top:0;left:0;}.front{z-index:2;transform:rotateY(0deg);}.back{transform:rotateY(180deg);}</style>
				
			

flip-desktop-hover-mobile-click

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const isHoverable=window.matchMedia('(hover: hover)').matches;if(!isHoverable){document.querySelectorAll('.flipper').forEach(function(card){card.addEventListener('click',function(e){if(e.target.closest('a, button'))return;const isFlipped=card.classList.contains('flipped');document.querySelectorAll('.flipper.flipped').forEach(el=>{el.classList.remove('flipped');});if(!isFlipped){card.classList.add('flipped');}});});}});</script>
<style>.flipper{transition:0.3s;transform-style:preserve-3d;position:relative;width:300px;height:400px;}@media (hover:hover){.flipper:hover{transform:rotateY(180deg);}}.flipper.flipped{transform:rotateY(180deg);}.front,.back{backface-visibility:hidden;position:absolute;width:100%;height:100%;top:0;left:0;}.front{z-index:2;transform:rotateY(0deg);}.back{transform:rotateY(180deg);}</style>
				
			

tab-nav-button

				
					<div class="tabs-navigation">
    <button id="prev-tab" class="tab-nav">&#9665; Previous</button>
    <button id="next-tab" class="tab-nav">Next &#9655;</button>
</div>

<style>.tabs-navigation{display:flex;justify-content:center;gap:10px;margin-top:0px;}.tab-nav{background-color:#fff;color:#222222;padding:7px 10px;width:110px;border:solid 1px #DDDDDD;cursor:pointer;font-size:16px;border-radius:5px;transition:background-color 0.3s;}.tab-nav:hover{background-color:#DDDDDD;color:#222222;}.tab-nav:focus{background-color:#fff;color:#222222;}</style>

<script type="text/phast">jQuery(document).ready(function($){function switchTab(direction){let allTabs=$(".e-n-tab-title");let currentTab=$(".e-n-tab-title[aria-selected='true']");let currentIndex=allTabs.index(currentTab);let newIndex=direction==="next"?currentIndex+1:currentIndex-1;if(newIndex>=0&&newIndex<allTabs.length){allTabs.eq(newIndex).trigger("click");}}
$("#prev-tab").click(function(){switchTab("prev");});$("#next-tab").click(function(){switchTab("next");});});</script>
				
			

staggered-loop

				
					<style>.e-loop-item{opacity:0;transform:translateY(20px);transition:opacity 1.0s ease,transform 2.0s;}.e-loop-item.visible{opacity:1;transform:translateY(0);transition-delay:calc(var(--animation-order) * 0.3s);}</style>

<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){let loopObserver=null;function animateVisibleLoopItems(){const items=document.querySelectorAll('.e-loop-item');let order=1;items.forEach(item=>{item.classList.remove('visible');if(item.offsetParent!==null){item.style.setProperty('--animation-order',order++);setTimeout(()=>{item.classList.add('visible');},50);}});}
function observeLoopContainer(){if(loopObserver){loopObserver.disconnect();}
const firstItem=document.querySelector('.e-loop-item');if(!firstItem)return;const loopContainer=firstItem.parentElement;if(!loopContainer)return;loopObserver=new MutationObserver(function(mutationsList){let itemsChanged=false;mutationsList.forEach(mutation=>{if(mutation.addedNodes.length>0||mutation.removedNodes.length>0){itemsChanged=true;}});if(itemsChanged){setTimeout(()=>{animateVisibleLoopItems();},50);}});loopObserver.observe(loopContainer,{childList:true});}
animateVisibleLoopItems();observeLoopContainer();jQuery(function($){$(document).on('click','.e-filter-item',function(){setTimeout(function(){animateVisibleLoopItems();observeLoopContainer();},400);});});});</script>
				
			

redirection

				
					add_action('template_redirect', function() {
    $redirects = [
        '/old-page-url/' => '/new-page-url/',
        '/pix/' => '/pix2/',
    ];
    $current = $_SERVER['REQUEST_URI'];
    if (isset($redirects[$current])) {
        wp_redirect(home_url($redirects[$current]), 301);
        exit;
    }
});
				
			

cover-pdf

				
					<div id="pdf-container" style="width: 300px; height: 406px; overflow: hidden; position: relative;">
  <img decoding="async"
    id="pdf-preview"
    src="https://file.webp"
    alt="PDF Preview"
    style="width: 100%; height: 100%; object-fit: contain; cursor: pointer;"
    onclick="showPDF()"
  >
</div>

<script type="text/phast">function showPDF(){const container=document.getElementById('pdf-container');container.innerHTML=`
      <iframe
        src="https://file.pdf#page=1&view=FitH"
        style="width: 100%; height: 100%; border: none; overflow: hidden;"
      ></iframe>
    `;}</script>
				
			

embed-pdf

				
					<div style="width: 300px; height: 406px; overflow: hidden;">
  <iframe loading="lazy" src="https://file.pdf#page=1&amp;view=FitH" style="width: 100%; height: 100%; border: none;"></iframe>
</div>
				
			

important-info

				
					function add_important_information_widget() {
    wp_add_dashboard_widget(
        'important_information_widget',
        'Important Information',
        'important_information_widget_content'
    );
}
add_action( 'wp_dashboard_setup', 'add_important_information_widget' );

function important_information_widget_content() {
    echo '<div style="font-size: 13px;">';
    echo '<h2 style="font-size: 13px; font-weight: bold; margin: 20px 0px -10px 0px;">Web Contact</h2>';
    echo '<ul>';
    echo '<li>Web Designer: Imran Siddiq</li>';
    echo '<li>Email: <a href="mailto:info@websquadron.co.uk" style="color: #0000ff; font-weight: bold;">info@websquadron.co.uk</a></li>';
    echo '<li>Website: <a href="https://learn.websquadron.co.uk" target="_blank" style="color: #0000ff; font-weight: bold;">https://learn.websquadron.co.uk</a></li>';
    echo '</ul>';
	
    echo '<h2 style="font-size: 13px; font-weight: bold; margin: 20px 0 -10px 0;">Care Plan</h2>';
    echo '<ul>';
    echo '<li>£90 Monthly</li>';
    echo '<li>Incl. Plugin Updates, SSL Certificate, Backups, & 3 Minor Revisions.</li>';
    echo '<li>Major Revisions start at £60 and will be agreed prior to work.</li>';
    echo '<li>Consultations can be booked at £80 per 30 mins, or £150 per hour.</li>';
    echo '</ul>';

    echo '<h2 style="font-size: 13px; font-weight: bold; margin: 20px 0 -10px 0;">Licenses</h2>';
    echo '<ul>';
    echo '<li>Domain - Auto-Renew 123-Reg - April</li>';
    echo '<li>Hosting - Auto-Renew Elementor Hosting - April</li>';
    echo '<li>Builder - Auto-Renew Elementor Pro - May</li>';
    echo '<li>Filters - Auto-Renew Gridbuilder - June</li>';
    echo '</ul>';
    echo '</div>';
}

				
			

pause-container-bg-video

				
					<style>#pause-btn2{display:block;}#play-btn2{display:none;}</style>


<script type="text/phast">jQuery(document).ready(function($){var video=$('.elementor-element-eb6f186 .elementor-background-video-hosted')[0];var pauseBtn=$('#pause-btn2');var playBtn=$('#play-btn2');var isPlaying=video.autoplay&&!video.paused;if(isPlaying){pauseBtn.show();playBtn.hide();}else{pauseBtn.hide();playBtn.show();}
pauseBtn.on('click',function(){if(isPlaying){video.pause();pauseBtn.hide();playBtn.show();isPlaying=false;}});playBtn.on('click',function(){if(!isPlaying){video.play();pauseBtn.show();playBtn.hide();isPlaying=true;}});$(video).on('play',function(){isPlaying=true;pauseBtn.show();playBtn.hide();});$(video).on('pause',function(){isPlaying=false;pauseBtn.hide();playBtn.show();});});</script>
				
			

current-query-sort

				
					add_action( 'elementor/query/customorder', function( $query ) {
    $query->set( 'orderby', 'date' );
    // $query->set( 'orderby', 'title' );
    // $query->set( 'orderby', 'menu_order' );
    $query->set( 'order', 'ASC' );
});
				
			

pause-video-widget

				
					<style>#pause-btn{display:block;}#play-btn{display:none;}</style>


<script type="text/phast">jQuery(document).ready(function($){var video=$('.videopause .elementor-video')[0];var pauseBtn=$('#pause-btn');var playBtn=$('#play-btn');var isPlaying=video.autoplay&&!video.paused;if(isPlaying){pauseBtn.show();playBtn.hide();}else{pauseBtn.hide();playBtn.show();}
pauseBtn.on('click',function(){if(isPlaying){video.pause();pauseBtn.hide();playBtn.show();isPlaying=false;}});playBtn.on('click',function(){if(!isPlaying){video.play();pauseBtn.show();playBtn.hide();isPlaying=true;}});$(video).on('play',function(){isPlaying=true;pauseBtn.show();playBtn.hide();});$(video).on('pause',function(){isPlaying=false;pauseBtn.hide();playBtn.show();});});</script>
				
			

off-canvas-same-pane-anchor

				
					<style>.e-off-canvas{z-index:100;display:none;visibility:hidden;opacity:0;transition:visibility 0s linear 0.2s,opacity 0.2s linear;}.e-off-canvas-visible{display:block !important;visibility:visible !important;opacity:1 !important;z-index:9999 !important;}.e-off-canvas-hidden{visibility:hidden !important;opacity:0 !important;z-index:10 !important;}body::before{content:"";position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(255,255,255,1);opacity:0;visibility:hidden;z-index:9998;transition:opacity 0.2s linear,visibility 0s linear 0.2s;}body.off-canvas-active::before{opacity:1;visibility:visible;transition:opacity 0.2s linear;}</style>

<script type="text/phast">jQuery(function($){function forceRepaint(){document.body.style.display='none';document.body.offsetHeight;document.body.style.display='block';window.dispatchEvent(new Event('resize'));}
function closeAllOffCanvas(exceptID=null){let anyOpen=false;$(".e-off-canvas").each(function(){let canvasID=$(this).attr("id");if(!exceptID||canvasID!==exceptID){$(this).removeClass("e-off-canvas-visible").addClass("e-off-canvas-hidden").attr("aria-hidden","true").css({"z-index":"10","visibility":"hidden","opacity":"0"});setTimeout(()=>{if($(this).attr("aria-hidden")==="true"){$(this).css("display","none");}},0);}else{anyOpen=true;}});setTimeout(()=>{if(!$(".e-off-canvas-visible").length){$("body").removeClass("off-canvas-active");forceRepaint();}},0);}
function openOffCanvas(targetID){let targetCanvas=$(targetID);if(targetCanvas.length){closeAllOffCanvas(targetID);setTimeout(()=>{targetCanvas.removeClass("e-off-canvas-hidden").addClass("e-off-canvas-visible").attr("aria-hidden","false").css({"z-index":"9999","visibility":"visible","opacity":"1","display":"block"});$("body").addClass("off-canvas-active");forceRepaint();},0);}}
function decodeBase64(str){try{return atob(str);}catch(e){return null;}}
$(document).on('click','[href*="elementor-action%3Aaction%3Doff_canvas%3Aopen"]',function(event){event.preventDefault();let href=decodeURIComponent($(this).attr("href"));let base64Match=href.match(/settings=([^&]+)/);if(base64Match){let decodedSettings=decodeBase64(base64Match[1]);try{let settingsObj=JSON.parse(decodedSettings);if(settingsObj.id){let offCanvasID="#off-canvas-"+settingsObj.id;openOffCanvas(offCanvasID);}}catch(e){}}});$(document).on('click','[href*="elementor-action%3Aaction%3Doff_canvas%3Aclose"]',function(event){event.preventDefault();closeAllOffCanvas();});$(".e-off-canvas").each(function(){$(this).attr("aria-hidden","true").css({"z-index":"10","visibility":"hidden","opacity":"0","display":"none"});});$(document).on('click','a[href*="#"]',function(event){let href=$(this).attr('href');if(href.indexOf('#')!==-1){closeAllOffCanvas();}});});</script>
				
			

ACF-Text-Editor

				
					function acf_field_shortcode($atts) {
    $atts = shortcode_atts(array(
        'field' => '',
        'post_id' => false,
    ), $atts, 'acf');

    if (function_exists('get_field')) {
        $field_value = get_field($atts['field'], $atts['post_id']);

        // If the field is an array (like a select, relationship, or taxonomy field)
        if (is_array($field_value)) {
            $output = [];

            foreach ($field_value as $item) {
                if (is_numeric($item)) {
                    // Check if it's a post ID
                    $post = get_post($item);
                    if ($post) {
                        $output[] = get_the_title($post->ID);
                        continue;
                    }

                    // Check if it's a taxonomy term ID
                    $term = get_term($item);
                    if (!is_wp_error($term) && !empty($term)) {
                        $output[] = $term->name;
                        continue;
                    }
                }

                // If it's not a number, just add the value
                $output[] = $item;
            }

            return esc_html(implode(', ', $output));
        }

        // If it's a single post ID, get the post title
        if (is_numeric($field_value)) {
            $post = get_post($field_value);
            if ($post) {
                return esc_html(get_the_title($post->ID));
            }

            $term = get_term($field_value);
            if (!is_wp_error($term) && !empty($term)) {
                return esc_html($term->name);
            }
        }

        return esc_html($field_value);
    }

    return '';
}
add_shortcode('acf', 'acf_field_shortcode');
				
			

stroke-and-non-stroke

				
					We <span class="outline-text">Design, Build</span> and <span class="outline-text">Maintain</span> Affordable Websites
				
			

off-canvas-apple-mobile-menu

				
					<style>.e-off-canvas{z-index:100;display:none;visibility:hidden;opacity:0;transition:visibility 0s linear 0.2s,opacity 0.2s linear;}.e-off-canvas-visible{display:block !important;visibility:visible !important;opacity:1 !important;z-index:9999 !important;}.e-off-canvas-hidden{visibility:hidden !important;opacity:0 !important;z-index:10 !important;}body::before{content:"";position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(255,255,255,1);opacity:0;visibility:hidden;z-index:9998;transition:opacity 0.2s linear,visibility 0s linear 0.2s;}body.off-canvas-active::before{opacity:1;visibility:visible;transition:opacity 0.2s linear;}</style>

<script type="text/phast">jQuery(function($){function forceRepaint(){document.body.style.display='none';document.body.offsetHeight;document.body.style.display='block';window.dispatchEvent(new Event('resize'));}
function closeAllOffCanvas(exceptID=null){let anyOpen=false;$(".e-off-canvas").each(function(){let canvasID=$(this).attr("id");if(!exceptID||canvasID!==exceptID){$(this).removeClass("e-off-canvas-visible").addClass("e-off-canvas-hidden").attr("aria-hidden","true").css({"z-index":"10","visibility":"hidden","opacity":"0"});setTimeout(()=>{if($(this).attr("aria-hidden")==="true"){$(this).css("display","none");}},0);}else{anyOpen=true;}});setTimeout(()=>{if(!$(".e-off-canvas-visible").length){$("body").removeClass("off-canvas-active");forceRepaint();}},0);}
function openOffCanvas(targetID){let targetCanvas=$(targetID);if(targetCanvas.length){closeAllOffCanvas(targetID);setTimeout(()=>{targetCanvas.removeClass("e-off-canvas-hidden").addClass("e-off-canvas-visible").attr("aria-hidden","false").css({"z-index":"9999","visibility":"visible","opacity":"1","display":"block"});$("body").addClass("off-canvas-active");forceRepaint();},0);}}
function decodeBase64(str){try{return atob(str);}catch(e){return null;}}
$(document).on('click','[href*="elementor-action%3Aaction%3Doff_canvas%3Aopen"]',function(event){event.preventDefault();let href=decodeURIComponent($(this).attr("href"));let base64Match=href.match(/settings=([^&]+)/);if(base64Match){let decodedSettings=decodeBase64(base64Match[1]);try{let settingsObj=JSON.parse(decodedSettings);if(settingsObj.id){let offCanvasID="#off-canvas-"+settingsObj.id;openOffCanvas(offCanvasID);}}catch(e){}}});$(document).on('click','[href*="elementor-action%3Aaction%3Doff_canvas%3Aclose"]',function(event){event.preventDefault();closeAllOffCanvas();});$(".e-off-canvas").each(function(){$(this).attr("aria-hidden","true").css({"z-index":"10","visibility":"hidden","opacity":"0","display":"none"});});$(document).on('click','a[href*="#"]',function(event){let href=$(this).attr('href');if(href.indexOf('#')!==-1){closeAllOffCanvas();}});});</script>
				
			

colour-contrast-checker-wcag

				
					add_action('admin_menu', 'contrast_checker_menu');
add_action('admin_init', 'contrast_checker_settings');

function contrast_checker_menu() {
    add_options_page('Contrast Checker', 'Contrast Checker', 'manage_options', 'contrast-checker', 'contrast_checker_page');
}

function contrast_checker_settings() {
    add_settings_section('contrast_checker_section', 'Contrast Checker - Web Content Accessibility Guidelines (WCAG) 2.1 ', null, 'contrast-checker');

    add_settings_field('background_color', 'Background Color', 'background_color_callback', 'contrast-checker', 'contrast_checker_section');
    add_settings_field('text_color', 'Foreground Color', 'foreground_color_callback', 'contrast-checker', 'contrast_checker_section');
    add_settings_field('font_size', 'Font Size (px)', 'font_size_callback', 'contrast-checker', 'contrast_checker_section');

    register_setting('contrast_checker_group', 'background_color');
    register_setting('contrast_checker_group', 'text_color');
    register_setting('contrast_checker_group', 'font_size'); // Ensures font size persists
}

function background_color_callback() {
    $background_color = get_option('background_color', '#FFFFFF');
    echo '<div style="display: flex; align-items: center; gap: 5px;">'; // Reduce gap
    echo '<input type="text" id="background_color" name="background_color" value="' . esc_attr($background_color) . '" class="my-color-field" style="font-size: 15px !important; width: 120px;" />';
    echo '<span id="background_color_hex" style="font-size: 15px;">' . esc_attr($background_color) . '</span></div>';
}

function foreground_color_callback() {
    $foreground_color = get_option('text_color', '#000000');
    echo '<div style="display: flex; align-items: center; gap: 5px;">'; // Reduce gap
    echo '<input type="text" id="text_color" name="text_color" value="' . esc_attr($foreground_color) . '" class="my-color-field" style="font-size: 15px !important; width: 120px;" />';
    echo '<span id="text_color_hex" style="font-size: 15px;">' . esc_attr($foreground_color) . '</span></div>';
}

function font_size_callback() {
    $font_size = get_option('font_size', '16');
    echo '<div style="display: flex; align-items: center; gap: 5px;">'; // Reduce gap
    echo '<input type="number" id="font_size" name="font_size" value="' . esc_attr($font_size) . '" min="1" max="100" style="font-size: 15px !important; width: 60px;" />';
    echo '<span id="font_size_value" style="font-size: 15px;">px</span></div>';
}

function contrast_checker_page() {
    ?>
    <div class="wrap" style="font-size: 15px; line-height: 1.2em; background-color: #ffffff; padding: 16px; border-radius: 5px;">
        <h1 style="font-size: 0px; line-height: 0em;">Contrast Checker</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields('contrast_checker_group');
            do_settings_sections('contrast-checker');
            submit_button('Check Colors', 'primary', 'submit', true);
            ?>
        </form>
        <div id="contrast-result" style="margin-top: 20px;"></div>
        <div style="margin-top: 20px; font-size: 15px; line-height: 1em;">
            <h2 style="font-size: 15px; line-height: 1em;"><br>Tips for AA and AAA</h2>
            <p style="font-size: 15px; line-height: 1.2em;">1. Larger Fonts of 24px can pass the AA rule.<br>2. If you need to test Non-text elements, increase the font to 24px.<br>3. Inactive/disabled UI components do not require contrast compliance.<br>4. Logos and branding are exempt from contrast rules.</p>
            <h2 style="font-size: 15px; line-height: 1em;">What is AA?</h2>
            <p style="font-size: 15px; line-height: 1.2em;">AA requires a contrast ratio of at least 4.5:1 for normal text (less than 24px) and 3:1 for large text (minimum 24px). Non-text elements (like buttons, icons, form fields, focus indicators, etc should be at least 3.1.</p>
            <h2 style="font-size: 15px; line-height: 1em;">What is AAA?</h2>
            <p style="font-size: 15px; line-height: 1.2em;">AAA requires a contrast ratio of at least 7:1 for normal text (less than 24px) and 4.5:1 for large text (minimum 24px). Non-text elements (like buttons, icons, form fields, focus indicators, etc should be at least 4.5.1.</p>
        </div>
    </div>
    <style>.my-color-field{font-size:15px !important;}.contrast-pass-yes{color:#007E33;font-weight:600;}.contrast-pass-no{color:#E60000;font-weight:600;}</style>
    <style>.form-table td,.form-table th{padding:4px 10px !important;}.form-table{border-spacing:5px;}.my-color-field{font-size:15px !important;width:120px;}#font_size{width:60px;}.wrap form{margin-top:10px;}#contrast-result{margin-top:10px !important;}</style>
    <?php
}

// Enqueue the color picker script and add inline script
add_action('admin_enqueue_scripts', 'contrast_checker_enqueue_scripts');
function contrast_checker_enqueue_scripts($hook_suffix) {
    if ($hook_suffix != 'settings_page_contrast-checker') {
        return;
    }
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
    wp_add_inline_script('wp-color-picker', '
        jQuery(document).ready(function($) {
            function updateContrast() {
                var bgColor = $("#background_color").val();
                var txtColor = $("#text_color").val();
                var fontSize = $("#font_size").val();

                // Update the button style
                $("#submit").css({
                    "background-color": bgColor,
                    "color": txtColor,
                    "border": "1px solid " + txtColor,
                    "font-size": fontSize + "px"
                });

                $.ajax({
                    url: ajaxurl,
                    type: "POST",
                    data: {
                        action: "check_contrast",
                        bg_color: bgColor,
                        txt_color: txtColor,
                        font_size: fontSize
                    },
                    success: function(response) {
                        if (response.success) {
                            $("#contrast-result").html(response.data);
                        }
                    }
                });
            }

            $(".my-color-field").wpColorPicker({
                defaultColor: {
                    background_color: "#FFFFFF",
                    text_color: "#000000"
                },
                change: function(event, ui) {
                    var color = ui.color.toString();
                    if (event.target.id === "background_color") {
                        $("#background_color_hex").text(color);
                    } else if (event.target.id === "text_color") {
                        $("#text_color_hex").text(color);
                    }
                    updateContrast();
                }
            });

            $("#font_size").on("input", function() {
                updateContrast();
            });

            // Initial contrast check and button style update
            updateContrast();
        });
    ');
}

// AJAX handler for checking contrast
add_action('wp_ajax_check_contrast', 'ajax_check_contrast');
function ajax_check_contrast() {
    $bg_color = sanitize_hex_color($_POST['bg_color']);
    $txt_color = sanitize_hex_color($_POST['txt_color']);
    $font_size = intval($_POST['font_size']);
    $result = check_contrast($bg_color, $txt_color, $font_size);
    wp_send_json_success($result);
}

function check_contrast($bg_hex, $txt_hex, $font_size) {
    $bg_rgb = hex_to_rgb($bg_hex);
    $txt_rgb = hex_to_rgb($txt_hex);

    $bg_luminance = luminance($bg_rgb);
    $txt_luminance = luminance($txt_rgb);

    // Define thresholds based on font size
    $aa_threshold = ($font_size >= 24) ? 3.0 : 4.5; // Large text is 24px or larger
    $aaa_threshold = ($font_size >= 24) ? 4.5 : 7.0; // Large text is 24px or larger

    // Calculate the current contrast ratio
    $contrast_ratio = contrast_ratio($bg_luminance, $txt_luminance);

    // Determine if the current colors pass AA and AAA
    $aa_pass = ($contrast_ratio >= $aa_threshold) ? '<span class="contrast-pass-yes">Yes</span>' : '<span class="contrast-pass-no">No</span>';
    $aaa_pass = ($contrast_ratio >= $aaa_threshold) ? '<span class="contrast-pass-yes">Yes</span>' : '<span class="contrast-pass-no">No</span>';

    // Calculate suggested foreground colors for AA and AAA compliance
    $suggested_aa = adjust_foreground_color($bg_rgb, $txt_rgb, $aa_threshold);
    $suggested_aaa = adjust_foreground_color($bg_rgb, $txt_rgb, $aaa_threshold);

    // Calculate suggested background colors for AA and AAA compliance
    $suggested_bg_aa = adjust_background_color($bg_rgb, $txt_rgb, $aa_threshold);
    $suggested_bg_aaa = adjust_background_color($bg_rgb, $txt_rgb, $aaa_threshold);

    // Calculate the contrast ratio for the suggested colors
    $suggested_aa_rgb = hex_to_rgb($suggested_aa);
    $suggested_aa_luminance = luminance($suggested_aa_rgb);
    $suggested_aa_ratio = contrast_ratio($bg_luminance, $suggested_aa_luminance);

    $suggested_aaa_rgb = hex_to_rgb($suggested_aaa);
    $suggested_aaa_luminance = luminance($suggested_aaa_rgb);
    $suggested_aaa_ratio = contrast_ratio($bg_luminance, $suggested_aaa_luminance);

    $suggested_bg_aa_rgb = hex_to_rgb($suggested_bg_aa);
    $suggested_bg_aa_luminance = luminance($suggested_bg_aa_rgb);
    $suggested_bg_aa_ratio = contrast_ratio($suggested_bg_aa_luminance, $txt_luminance);

    $suggested_bg_aaa_rgb = hex_to_rgb($suggested_bg_aaa);
    $suggested_bg_aaa_luminance = luminance($suggested_bg_aaa_rgb);
    $suggested_bg_aaa_ratio = contrast_ratio($suggested_bg_aaa_luminance, $txt_luminance);

    // Return the results
    return '
        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
            <div style="background-color: ' . esc_attr($bg_hex) . '; width: 20px; height: 20px; border: 1px solid #000;"></div>
            <div style="background-color: ' . esc_attr($txt_hex) . '; width: 20px; height: 20px; border: 1px solid #000;"></div>
        </div>
        <div style="font-size: 15px; line-height: 1.2em;">
            <div style="margin-bottom: 5px;"><strong>Contrast Ratio:</strong> ' . round($contrast_ratio, 2) . '</div>
            <div style="margin-bottom: 5px;"><strong>AA Compliant:</strong> ' . $aa_pass . '</div>
            <div style="margin-bottom: 5px;"><strong>AAA Compliant:</strong> ' . $aaa_pass . '</div>
        </div>
        <div style="margin-top: 20px; font-size: 15px; line-height: 1.2em;">
    <div style="margin-bottom: 15px;">
        <strong>Suggested Foreground Color for AA:</strong>
        <span style="background-color: ' . $suggested_aa . '; width: 20px; height: 20px; display: inline-block; border: 1px solid #000; margin-right: 10px;"></span> 
        ' . $suggested_aa . '
        <span style="margin-left: 10px;"><strong>Contrast Ratio:</strong> ' . round($suggested_aa_ratio, 2) . '</span>
    </div>
    <div style="margin-bottom: 15px;">
        <strong>Suggested Background Color for AA:</strong>
        <span style="background-color: ' . $suggested_bg_aa . '; width: 20px; height: 20px; display: inline-block; border: 1px solid #000; margin-right: 10px;"></span> 
        ' . $suggested_bg_aa . '
        <span style="margin-left: 10px;"><strong>Contrast Ratio:</strong> ' . round($suggested_bg_aa_ratio, 2) . '</span>
    </div>
    <div style="margin-bottom: 15px;">
        <strong>Suggested Foreground Color for AAA:</strong>
        <span style="background-color: ' . $suggested_aaa . '; width: 20px; height: 20px; display: inline-block; border: 1px solid #000; margin-right: 10px;"></span> 
        ' . $suggested_aaa . '
        <span style="margin-left: 10px;"><strong>Contrast Ratio:</strong> ' . round($suggested_aaa_ratio, 2) . '</span>
    </div>
    <div style="margin-bottom: 15px;">
        <strong>Suggested Background Color for AAA:</strong>
        <span style="background-color: ' . $suggested_bg_aaa . '; width: 20px; height: 20px; display: inline-block; border: 1px solid #000; margin-right: 10px;"></span> 
        ' . $suggested_bg_aaa . '
        <span style="margin-left: 10px;"><strong>Contrast Ratio:</strong> ' . round($suggested_bg_aaa_ratio, 2) . '</span>
    </div>
</div>';
}

// Function to adjust the background color to meet the target contrast ratio
function adjust_background_color($bg_rgb, $txt_rgb, $target_ratio) {
    $txt_luminance = luminance($txt_rgb);
    $step = 0.02; // Adjust step value for precision and performance

    // Incrementally adjust the RGB values to find a compliant color
    for ($i = 0; $i <= 1; $i += $step) {
        $test_rgb = adjust_rgb_lightness($bg_rgb, $i);
        $test_luminance = luminance($test_rgb);
        if (contrast_ratio($test_luminance, $txt_luminance) >= $target_ratio) {
            return rgb_to_hex($test_rgb);
        }

        $test_rgb = adjust_rgb_lightness($bg_rgb, -$i);
        $test_luminance = luminance($test_rgb);
        if (contrast_ratio($test_luminance, $txt_luminance) >= $target_ratio) {
            return rgb_to_hex($test_rgb);
        }
    }

    return "#FFFFFF"; // fallback to white if no suitable color found
}

function hex_to_rgb($hex) {
    $hex = ltrim($hex, '#');
    $r = hexdec(substr($hex, 0, 2)) / 255;
    $g = hexdec(substr($hex, 2, 2)) / 255;
    $b = hexdec(substr($hex, 4, 2)) / 255;
    return array($r, $g, $b);
}

function rgb_to_hex($rgb) {
    return sprintf("#%02x%02x%02x", round($rgb[0] * 255), round($rgb[1] * 255), round($rgb[2] * 255));
}

function luminance($rgb) {
    list($r, $g, $b) = $rgb;
    $r = ($r <= 0.03928) ? $r / 12.92 : pow(($r + 0.055) / 1.055, 2.4);
    $g = ($g <= 0.03928) ? $g / 12.92 : pow(($g + 0.055) / 1.055, 2.4);
    $b = ($b <= 0.03928) ? $b / 12.92 : pow(($b + 0.055) / 1.055, 2.4);
    return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
}

function contrast_ratio($l1, $l2) {
    $lighter = max($l1, $l2);
    $darker = min($l1, $l2);
    return ($lighter + 0.05) / ($darker + 0.05);
}

function adjust_foreground_color($bg_rgb, $txt_rgb, $target_ratio) {
    $bg_luminance = luminance($bg_rgb);
    $step = 0.02; // Adjust step value for precision and performance

    // Incrementally adjust the RGB values to find a compliant color
    for ($i = 0; $i <= 1; $i += $step) {
        $test_rgb = adjust_rgb_lightness($txt_rgb, $i);
        $test_luminance = luminance($test_rgb);
        if (contrast_ratio($test_luminance, $bg_luminance) >= $target_ratio) {
            return rgb_to_hex($test_rgb);
        }

        $test_rgb = adjust_rgb_lightness($txt_rgb, -$i);
        $test_luminance = luminance($test_rgb);
        if (contrast_ratio($test_luminance, $bg_luminance) >= $target_ratio) {
            return rgb_to_hex($test_rgb);
        }
    }

    return "#000000"; // fallback to black if no suitable color found
}

function adjust_rgb_lightness($rgb, $adjustment) {
    return array(
        min(1, max(0, $rgb[0] + $adjustment)),
        min(1, max(0, $rgb[1] + $adjustment)),
        min(1, max(0, $rgb[2] + $adjustment))
    );
}
				
			

Hide-AI-User-Setting

				
					add_action('admin_footer', function () {
    ?>
    <script type="text/phast">document.addEventListener("DOMContentLoaded",function(){const elementorAiH2=document.querySelector('tr th h2');if(elementorAiH2&&elementorAiH2.textContent.trim()==='Elementor - AI'){elementorAiH2.textContent=' ';}
const elementorAiTableHeader=document.querySelector('th:has(label[for="elementor_enable_ai"])');if(elementorAiTableHeader){elementorAiTableHeader.textContent=' ';}
const elementorAiStatus=document.querySelector('label[for="elementor_enable_ai"]');if(elementorAiStatus){elementorAiStatus.textContent=' ';}});</script>
    <?php
});
				
			

open-off-canvas-page-load

				
					<script type="text/phast">document.addEventListener("DOMContentLoaded",function(){let lastOpened=localStorage.getItem("offCanvasOpenedTime");let now=new Date().getTime();let oneHour=60*60*1000;if(!lastOpened||now-lastOpened>oneHour){setTimeout(function(){let offCanvas=document.querySelector('.e-off-canvas[aria-label="Launch001"]');if(offCanvas){let offCanvasButton=document.querySelector('.elementor-icon[href*="off_canvas"]');if(offCanvasButton){offCanvasButton.click();localStorage.setItem("offCanvasOpenedTime",now);}}},500);}});</script>
				
			

horizontal-scroll

				
					<style>@media (min-width:768px){.e-n-carousel{overflow:hidden;height:100vh;position:relative;}.elementor-swiper-button-next,.elementor-swiper-button-prev{display:none;}.e-n-carousel .swiper-wrapper{display:flex;flex-direction:row;transition:transform 0.2s ease;}.e-n-carousel .swiper-slide{flex:0 0 100vw;height:100vh;}.stickyicon{position:fixed;top:20px;right:20px;z-index:1000;cursor:pointer;opacity:0;pointer-events:none;transition:opacity 0.3s ease;}}</style>
<script type="text/phast" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script type="text/phast" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
<script type="text/phast">function initCarousel(){if(window.matchMedia('(min-width: 768px)').matches){gsap.registerPlugin(ScrollTrigger);const swiperWrapper=document.querySelector('.swiper-wrapper');const slides=document.querySelectorAll('.swiper-slide');const stickyIcon=document.querySelector('.stickyicon');const skipSection=document.getElementById('skip');const totalSlides=slides.length;gsap.set(swiperWrapper,{x:0});const totalScrollWidth=(totalSlides-1)*window.innerWidth;const enablePinning=true;const scrollEndValue=`+=${totalSlides * window.innerHeight}`;const scrollAnimation=gsap.to(swiperWrapper,{x:()=>-totalScrollWidth,ease:'none',scrollTrigger:{trigger:'.e-n-carousel',pin:enablePinning,scrub:true,end:scrollEndValue,anticipatePin:1,pinSpacing:true,},});ScrollTrigger.create({trigger:'.e-n-carousel',start:'top top',end:scrollEndValue,onEnter:()=>{stickyIcon.style.opacity='1';stickyIcon.style.pointerEvents='auto';},onLeave:()=>{stickyIcon.style.opacity='0';stickyIcon.style.pointerEvents='none';},onEnterBack:()=>{stickyIcon.style.opacity='1';stickyIcon.style.pointerEvents='auto';},onLeaveBack:()=>{stickyIcon.style.opacity='0';stickyIcon.style.pointerEvents='none';},});stickyIcon.addEventListener('click',()=>{if(skipSection){gsap.to(window,{scrollTo:skipSection.offsetTop,duration:0.1,ease:'none',});}});}}
initCarousel();window.addEventListener('resize',()=>{initCarousel();if(window.matchMedia('(min-width: 768px)').matches){ScrollTrigger.refresh();}});</script>
				
			

title-tabs-styling

				
					<span class="title-tab">Drag & Drop Editing<br>
  <span class="title-text-tab">
    Build perfectly designed websites<br>Create exactly what you want.
  </span>
</span>
				
			

image-swap

				
					<script type="text/phast">jQuery(document).ready(function($){$('.thumbnail-image img').on('click',function(){var clickedSrc=$(this).attr('src');$('#main-image img').attr('src',clickedSrc);});});</script>

<style>.thumbnail-image{cursor:pointer;}</style>
				
			

shipping-methods-based-on-cart-totals

				
					add_filter( 'woocommerce_package_rates', 'gncy_hide_shipping_based_on_threshold', 10, 2 );
function gncy_hide_shipping_based_on_threshold( $rates, $package ) {
    $threshold = 40; // Threshold for hiding and showing shipping methods
    $subtotal = WC()->cart->get_subtotal(); // Get the cart subtotal

    if ( $subtotal > $threshold ) {
        // Hide flat rate when subtotal exceeds the threshold
        if ( isset( $rates['flat_rate:4'] ) ) {
            unset( $rates['flat_rate:4'] );
        }
    } else {
        // Hide free shipping when subtotal is below the threshold
        if ( isset( $rates['free_shipping:3'] ) ) {
            unset( $rates['free_shipping:3'] );
        }

        // Add the custom message to the cart totals section
        add_action( 'woocommerce_after_cart_totals', 'gncy_add_free_shipping_message' );
    }

    return $rates;
}

// Add the custom message directly below cart totals
function gncy_add_free_shipping_message() {
    echo '<div id="free-shipping-message" style="margin-top: 15px; font-size: 14px; color: #007cba; text-align: left;">
            <p>Free Shipping when you spend $40+</p>
          </div>';
}
				
			

css-colour-history-elementor-top

				
					function add_custom_script_with_history_and_width_to_elementor() {
    ?>
    <script data-phast-original-type="text/javascript" type="text/phast">(function(){function updateUIWithButtons(){const preview=document.getElementById('elementor-preview-responsive-wrapper');if(preview){let displayWidth=document.getElementById('width');if(!displayWidth){displayWidth=document.createElement('div');displayWidth.id='width';displayWidth.style.position='fixed';displayWidth.style.top='10px';displayWidth.style.left='315px';displayWidth.style.color='white';displayWidth.style.backgroundColor='#0C0D0E';displayWidth.style.padding='7px 10px';displayWidth.style.zIndex='9999';displayWidth.style.fontSize='14px';document.body.appendChild(displayWidth);}
let width=preview.offsetWidth||0;width=width-40;displayWidth.textContent=''+width+'px';let historyButton=document.getElementById('history-button');if(!historyButton){historyButton=document.createElement('div');historyButton.id='history-button';historyButton.style.position='fixed';historyButton.style.top='8px';historyButton.style.left='245px';historyButton.style.backgroundColor='#0C0D0E';historyButton.style.border='none';historyButton.style.cursor='pointer';historyButton.style.padding='5px';historyButton.style.zIndex='9999';historyButton.style.width='30px';historyButton.style.height='30px';historyButton.style.display='flex';historyButton.style.alignItems='center';historyButton.style.justifyContent='center';historyButton.innerHTML=`
                        <svg class="MuiSvgIcon-root MuiSvgIcon-fontSizeMedium css-vubbuv" focusable="false" aria-hidden="true" viewBox="0 0 24 24" style="fill: white; transform: scale(0.8); transform-origin: center;">
                            <path fill-rule="evenodd" clip-rule="evenodd" d="M8.08961 4.0956C10.0932 3.02269 12.4216 2.72496 14.6307 3.25921C16.8397 3.79346 18.7748 5.1223 20.0667 6.99219C21.3585 8.86208 21.9168 11.1421 21.6349 13.3973C21.353 15.6525 20.2507 17.725 18.5383 19.2194C16.8259 20.7137 14.6233 21.5254 12.3506 21.4994C10.078 21.4734 7.89454 20.6117 6.21673 19.0786C4.53891 17.5456 3.48423 15.4484 3.25392 13.1874C3.21194 12.7753 3.51197 12.4072 3.92405 12.3652C4.33614 12.3233 4.70422 12.6233 4.7462 13.0354C4.93916 14.9298 5.82281 16.6868 7.22855 17.9713C8.63428 19.2558 10.4637 19.9777 12.3678 19.9995C14.2719 20.0212 16.1173 19.3412 17.552 18.0892C18.9867 16.8372 19.9103 15.1008 20.1464 13.2113C20.3826 11.3218 19.9149 9.41147 18.8325 7.84481C17.7502 6.27814 16.1289 5.16479 14.2781 4.71718C12.4272 4.26956 10.4764 4.51901 8.79772 5.41794C7.44561 6.14199 6.34633 7.24658 5.62839 8.58361H8.72228C9.13649 8.58361 9.47228 8.91939 9.47228 9.33361C9.47228 9.74782 9.13649 10.0836 8.72228 10.0836H4.48963C4.47805 10.0839 4.46644 10.0839 4.4548 10.0836H4.00006C3.58584 10.0836 3.25006 9.74782 3.25006 9.33361V4.61139C3.25006 4.19717 4.00006 3.86139C4.41427 3.86139 4.75006 4.19717 4.75006 4.61139V7.1337C5.58912 5.86995 6.73269 4.82222 8.08961 4.0956Z"></path>
                    `;historyButton.addEventListener('click',function(){const isMac=navigator.platform.toUpperCase().indexOf('MAC')>=0;const event=new KeyboardEvent('keydown',{key:'H',code:'KeyH',keyCode:72,bubbles:true,cancelable:true,[isMac?'metaKey':'ctrlKey']:true,shiftKey:true,});document.dispatchEvent(event);});document.body.appendChild(historyButton);}
let cssButton=document.getElementById('css-button');if(!cssButton){cssButton=document.createElement('div');cssButton.id='css-button';cssButton.style.position='fixed';cssButton.style.top='9px';cssButton.style.left='280px';cssButton.style.backgroundColor='#0C0D0E';cssButton.style.border='none';cssButton.style.cursor='pointer';cssButton.style.padding='5px';cssButton.style.zIndex='9999';cssButton.style.width='30px';cssButton.style.height='30px';cssButton.style.display='flex';cssButton.style.alignItems='center';cssButton.style.justifyContent='center';cssButton.style.color='white';cssButton.style.fontSize='14px';cssButton.textContent='CSS';cssButton.addEventListener('click',function(){const isMac=navigator.platform.toUpperCase().indexOf('MAC')>=0;const event=new KeyboardEvent('keydown',{key:'K',code:'KeyK',keyCode:75,bubbles:true,cancelable:true,[isMac?'metaKey':'ctrlKey']:true,});document.dispatchEvent(event);setTimeout(()=>{const customCssButton=document.querySelector('.elementor-panel-menu-item-settings-custom-css');if(customCssButton){customCssButton.click();elementor.channels.editor.execute('custom-css:open');}else{console.error('Custom CSS button not found.');}},500);});document.body.appendChild(cssButton);}
let colorButton=document.getElementById('color-button');if(!colorButton){colorButton=document.createElement('div');colorButton.id='color-button';colorButton.style.position='fixed';colorButton.style.top='9px';colorButton.style.left='380px';colorButton.style.backgroundColor='#0C0D0E';colorButton.style.border='none';colorButton.style.cursor='pointer';colorButton.style.padding='5px';colorButton.style.zIndex='9999';colorButton.style.width='30px';colorButton.style.height='30px';colorButton.style.display='flex';colorButton.style.alignItems='center';colorButton.style.justifyContent='center';colorButton.style.color='white';colorButton.innerHTML=`
        <svg fill="#ffffff" height="20px" width="20px" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 218.166 218.166" xml:space="preserve" stroke="#ffffff" stroke-width="2">
            <g>
                <g>
                    <path d="M173.312,87.998c2.12-6.625,3.205-13.543,3.205-20.565C176.518,30.25,146.268,0,109.084,0S41.651,30.25,41.651,67.433 c0,7.035,1.137,13.922,3.257,20.546c-25.086,9.833-42.924,34.223-42.924,62.754c0,37.184,30.25,67.433,67.433,67.433 c14.28,0,28.219-4.622,39.702-12.994c11.14,8.133,24.813,12.994,39.631,12.994c37.184,0,67.433-30.25,67.433-67.433 C216.183,122.222,198.37,97.845,173.312,87.998z M109.084,7.933c32.808,0,59.5,26.69,59.5,59.5c0,6.192-0.956,12.288-2.821,18.126 c-5.446-1.424-11.127-2.259-17.013-2.259c-14.818,0-28.49,4.861-39.63,12.993C97.544,87.817,83.898,83.3,69.417,83.3 c-5.869,0-11.534,0.831-16.965,2.247c-1.867-5.839-2.869-11.908-2.869-18.114C49.584,34.623,76.276,7.933,109.084,7.933z M69.417,210.233c-32.808,0-59.5-26.69-59.5-59.5s26.692-59.5,59.5-59.5c12.097,0,23.547,3.545,33.401,10.269 c-13.193,12.317-21.501,29.801-21.501,49.231c0,19.433,8.311,36.92,21.506,49.237C93.021,206.617,81.342,210.233,69.417,210.233z M148.751,210.233c-13.43,0-25.792-4.525-35.76-12.058c-0.128-0.254-0.21-0.523-0.397-0.752c-0.587-0.717-1.388-1.116-2.228-1.302 c-12.895-10.922-21.115-27.204-21.115-45.388c0-32.81,26.692-59.5,59.5-59.5s59.5,26.69,59.5,59.5 S181.558,210.233,148.751,210.233z"></path>
                </g>
            </g>
        </svg>
    `;colorButton.addEventListener('click',function(){const isMac=navigator.platform.toUpperCase().indexOf('MAC')>=0;const event=new KeyboardEvent('keydown',{key:'K',code:'KeyK',keyCode:75,bubbles:true,cancelable:true,[isMac?'metaKey':'ctrlKey']:true,});document.dispatchEvent(event);setTimeout(()=>{const globalColorsButton=document.querySelector('.elementor-panel-menu-item-global-colors');if(globalColorsButton){globalColorsButton.click();}else{console.error('Global Colors button not found.');}},500);});document.body.appendChild(colorButton);}}else{console.log('Element #elementor-preview-responsive-wrapper not found.');}}
setInterval(updateUIWithButtons,200);})();</script>
    <?php
}
add_action('elementor/editor/after_enqueue_scripts', 'add_custom_script_with_history_and_width_to_elementor');
				
			

show-hide-click

				
					<style>.answer{max-height:0;overflow:hidden;opacity:0;transition:max-height 0.3s ease,opacity 0.2s ease;visibility:hidden;}.answer.expanded{max-height:500px;opacity:1;visibility:visible;}.question{cursor:pointer;outline:none;}.question:focus{outline:3px solid #000;}</style>


<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const question=document.querySelector(".question");const answer=document.querySelector(".answer");question.addEventListener("click",function(){const isExpanded=question.getAttribute("aria-expanded")==="true";question.setAttribute("aria-expanded",!isExpanded);answer.setAttribute("aria-hidden",isExpanded);answer.classList.toggle("expanded",!isExpanded);if(!isExpanded){answer.style.maxHeight=answer.scrollHeight+"px";}else{answer.style.maxHeight="0";}});question.addEventListener("keydown",function(event){if(event.key==="Enter"||event.key===" "){event.preventDefault();question.click();}});});</script>
				
			

tooltips

				
					<p>
  Transform your <span class="tooltip">CSS<span class="tooltiptext">CSS - Cascading Style Sheet</span></span> levels with the <span class="tooltip">Web Squadron<span class="tooltiptext">Web Agency, Content Creator, Pepsi-Max Lover</span></span> Course.
</p>

<style>.tooltip{position:relative;cursor:pointer;text-decoration:underline;}.tooltip .tooltiptext{visibility:hidden;background-color:#555;color:#fff;text-align:center;border-radius:5px;padding:5px 10px;position:absolute;z-index:1;bottom:125%;left:50%;transform:translateX(-50%);opacity:0;transition:opacity 0.3s;white-space:nowrap;}.tooltip:hover .tooltiptext{visibility:visible;opacity:1;}</style>
				
			

before-after-slider

				
					<div class="before-after-slider" aria-label="Before and After Image Slider">
  <div class="before-image" style="background-image: url('https://test.websquadron.co.uk/wp-content/uploads/2024/11/pxfuel.webp');"></div>
  <div class="after-image" style="background-image: url('https://test.websquadron.co.uk/wp-content/uploads/2024/11/arcane-season-2-first-look-trailer-netflix-2.webp');"></div>
  <div class="divider" tabindex="0" role="slider" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100">
    <button class="chevron chevron-left" aria-label="Move slider left">&lt;</button>
    <button class="chevron chevron-right" aria-label="Move slider right">&gt;</button>
  </div>
</div>

<style>.before-after-slider{position:relative;width:800px;height:400px;overflow:hidden;border-radius:10px;box-shadow:0 4px 10px rgba(0,0,0,0.25);}@media screen and (max-width:768px){.before-after-slider{width:85vw;height:300px;margin:0 auto;border-radius:10px;}}.before-image,.after-image{position:absolute;top:0;left:0;width:100%;height:100%;background-size:cover;background-position:center;border-radius:10px;}.after-image{clip-path:inset(0 50% 0 0);z-index:1;}.divider{position:absolute;top:0;left:50%;width:3px;height:100%;background:#FFF;border:1px solid #fff;transform:translateX(-50%);cursor:ew-resize;z-index:2;display:flex;align-items:center;justify-content:space-between;pointer-events:auto;}.chevron{position:absolute;font-size:20px;font-weight:500;color:#000;background:#ffffff99;border:none;border-radius:0px;padding:5px 5px 7px 5px;cursor:pointer;user-select:none;outline:none;z-index:3;}.chevron-left{left:-23px;}.chevron-right{right:-23px;}.chevron:focus{outline:2px solid #fff;}</style>

<script type="text/phast">const slider=document.querySelector('.before-after-slider');const afterImage=document.querySelector('.after-image');const divider=document.querySelector('.divider');const chevronLeft=document.querySelector('.chevron-left');const chevronRight=document.querySelector('.chevron-right');let isDragging=false;let sliderPercentage=50;const updateSliderPosition=(percentage)=>{sliderPercentage=Math.max(0,Math.min(100,percentage));afterImage.style.clipPath=`inset(0 ${100 - sliderPercentage}% 0 0)`;divider.style.left=`${sliderPercentage}%`;divider.setAttribute('aria-valuenow',sliderPercentage);};const startDragging=(event)=>{isDragging=true;updatePositionFromEvent(event);};const stopDragging=()=>{isDragging=false;};const handleDragging=(event)=>{if(!isDragging)return;updatePositionFromEvent(event);};const updatePositionFromEvent=(event)=>{const rect=slider.getBoundingClientRect();const clientX=event.touches?event.touches[0].clientX:event.clientX;const offsetX=clientX-rect.left;const percentage=(offsetX/rect.width)*100;updateSliderPosition(percentage);};chevronLeft.addEventListener('click',()=>{updateSliderPosition(sliderPercentage-5);});chevronRight.addEventListener('click',()=>{updateSliderPosition(sliderPercentage+5);});divider.addEventListener('keydown',(event)=>{if(event.key==='ArrowLeft'){updateSliderPosition(sliderPercentage-5);}else if(event.key==='ArrowRight'){updateSliderPosition(sliderPercentage+5);}});divider.addEventListener('mousedown',startDragging);divider.addEventListener('touchstart',(event)=>{startDragging(event);document.body.style.overflow='hidden';});window.addEventListener('mousemove',handleDragging);window.addEventListener('touchmove',(event)=>{handleDragging(event);event.preventDefault();},{passive:false});window.addEventListener('mouseup',stopDragging);window.addEventListener('touchend',()=>{stopDragging();document.body.style.overflow='';});</script>
				
			

remove-woocommerce-checkout-fields-2025

				
					/**
 * Customize WooCommerce checkout fields based on product types in the cart.
 */
add_filter('woocommerce_checkout_fields', 'intelligent_customize_checkout_fields');

function intelligent_customize_checkout_fields($fields) {
    // Fields to remove for Non-Virtual and Non-Downloadable products
    $non_virtual_remove = [
        'billing' => ['billing_company', 'billing_phone'],
        'shipping' => ['shipping_company'],
        'order' => ['order_comments']
    ];

    // Fields to remove for Virtual products
    $virtual_remove = [
        'billing' => [
            'billing_company', 'billing_address_1', 'billing_address_2',
            'billing_postcode', 'billing_country', 'billing_state', 'billing_city'
        ],
        'shipping' => [
            'shipping_company', 'shipping_address_1', 'shipping_address_2',
            'shipping_postcode', 'shipping_country', 'shipping_state', 'shipping_city', 'shipping_first_name', 'shipping_last_name'
        ],
        'order' => ['order_comments']
    ];

    // Fields to remove for Downloadable products
    $downloadable_remove = [
        'billing' => [
            'billing_company', 'billing_address_1', 'billing_address_2',
            'billing_postcode', 'billing_country', 'billing_state', 'billing_city', 'billing_phone'
        ],
        'shipping' => [
            'shipping_company', 'shipping_address_1', 'shipping_address_2',
            'shipping_postcode', 'shipping_country', 'shipping_state', 'shipping_city', 'shipping_first_name', 'shipping_last_name'
        ],
        'order' => ['order_comments']
    ];

    // Determine the product types in the cart
    $has_virtual = false;
    $has_downloadable = false;
    $has_non_virtual = false;

    foreach (WC()->cart->get_cart() as $cart_item) {
        $product = $cart_item['data'];
        if ($product->is_virtual()) {
            $has_virtual = true;
        }
        if ($product->is_downloadable()) {
            $has_downloadable = true;
        }
        if (!$product->is_virtual() && !$product->is_downloadable()) {
            $has_non_virtual = true;
        }
    }

    // Apply field removal logic based on cart contents
    if ($has_non_virtual) {
        foreach ($non_virtual_remove as $section => $fields_to_remove) {
            foreach ($fields_to_remove as $field) {
                unset($fields[$section][$field]);
            }
        }
    }

    if ($has_virtual) {
        foreach ($virtual_remove as $section => $fields_to_remove) {
            foreach ($fields_to_remove as $field) {
                unset($fields[$section][$field]);
            }
        }
    }

    if ($has_downloadable) {
        foreach ($downloadable_remove as $section => $fields_to_remove) {
            foreach ($fields_to_remove as $field) {
                unset($fields[$section][$field]);
            }
        }
    }

    // Disable order notes field for virtual or downloadable products
    if ($has_virtual || $has_downloadable) {
        add_filter('woocommerce_enable_order_notes_field', '__return_false');
    }

    return $fields;
}

// Remove shipping and additional fields sections for Virtual or Downloadable products
add_action('woocommerce_before_checkout_form', 'hide_unnecessary_sections', 10);

function hide_unnecessary_sections() {
    $has_virtual = false;
    $has_downloadable = false;

    // Check cart contents for product types
    foreach (WC()->cart->get_cart() as $cart_item) {
        $product = $cart_item['data'];
        if ($product->is_virtual()) {
            $has_virtual = true;
        }
        if ($product->is_downloadable()) {
            $has_downloadable = true;
        }
    }

    // Conditionally hide sections
    if ($has_virtual || $has_downloadable) {
        ?>
        <style>.woocommerce-shipping-fields,.woocommerce-additional-fields{display:none !important;}</style>
        <?php
    }
}
				
			

mega-menu-page-slug

				
					<style>.e-n-menu{visibility:hidden;}.e-n-menu .e-n-menu-title{display:none;}.e-n-menu .e-n-menu-title#keep{display:flex;}</style>

<script type="text/phast">document.addEventListener("DOMContentLoaded",function(){const pageSlug=window.location.pathname.split("/").filter(Boolean).pop();const menuContainer=document.querySelector(".e-n-menu");const menuItems=document.querySelectorAll(".e-n-menu .e-n-menu-title[id]");menuItems.forEach((menuItem)=>{const menuId=menuItem.id;if(menuId==="keep"||menuId===pageSlug){menuItem.style.display="flex";}else{menuItem.style.display="none";}});menuContainer.style.visibility="visible";});</script>
				
			

inverted-border-radius-css

				
					/* Ensure consistent rendering of elements */
*, *::before, *::after {
    box-sizing: border-box;
}

.c13, .c13::before,
.c23, .c23::before,
.c33, .c33::before,
.c43, .c43::before,
.c53, .c53::before,
.c63, .c63::before {
    backface-visibility: hidden;
    transform: translateZ(0) translate(0, 0); /* Ensures pixel snapping */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    will-change: transform, clip-path;
}

.c13, .c23, .c33, .c43, .c53, .c63 {
    clip-path: inset(0); /* Restricts content within the boundaries */
    will-change: transform, clip-path;
}

.c13::before {
    content: '';
    position: absolute;
    background-color: transparent; /* Ensures only shadows are visible */
    border-radius: 100px 0px 0px 100px;
    box-shadow: 
        0px 0px 0px 50px #FFF, /* Slight negative offset for top shadow to remove 1px gap */
        0px 0px 0px 0px #FFF;  /* No bottom shadow */
    pointer-events: none;
    clip-path: inset(0); /* Keeps everything confined */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.c23::before {
    content: '';
    position: absolute;
    background-color: transparent; /* Ensures only shadows are visible */
    border-radius: 0px 100px 0px 0px;
    box-shadow: 
        0px 0px 0px 50px #FFF, /* Slight negative offset for top shadow to remove 1px gap */
        0px 0px 0px 0px #FFF;  /* No bottom shadow */
    pointer-events: none;
    clip-path: inset(0); /* Keeps everything confined */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.c33 {
    background-color: #FFF;
    border-radius: 0 0 0 50px;
    will-change: transform, clip-path;
}

.c43 {
    background-color: #FFF;
    border-radius: 0 50px 0 0;
    will-change: transform, clip-path;
}

.c53::before {
    content: '';
    position: absolute;
    background-color: transparent; /* Ensures only shadows are visible */
    border-radius: 0px 0px 0px 100px;
    box-shadow: 
        0px 0px 0px 50px #FFF, /* Slight negative offset for top shadow to remove 1px gap */
        0px 0px 0px 0px #FFF;  /* No bottom shadow */
    pointer-events: none;
    clip-path: inset(0); /* Keeps everything confined */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.c63::before {
    content: '';
    position: absolute;
    background-color: transparent; /* Ensures only shadows are visible */
    border-radius: 0 100px 100px 0;
    box-shadow: 
        0px 0px 0px 50px #FFF, /* Slight negative offset for top shadow to remove 1px gap */
        0px 0px 0px 0px #FFF;  /* No bottom shadow */
    pointer-events: none;
    clip-path: inset(0); /* Keeps everything confined */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
				
			

image-mask-css

				
					/* Ensure consistent rendering of elements */
*, *::before, *::after {
    box-sizing: border-box;
}

.c1 {
    background-color: #FFF;
    border-radius: 0 0 100px 0;
    will-change: transform, clip-path;
}

.c4 {
    background-color: #FFF;
    border-radius: 100px 0 0 0;
    will-change: transform, clip-path;
}

.c1, .c1::before,
.c2, .c2::before,
.c3, .c3::before,
.c4, .c4::before {
    backface-visibility: hidden;
    transform: translateZ(0) translate(0, 0); /* Ensures pixel snapping */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.c1, .c2, .c3, .c4 {
    clip-path: inset(0); /* Restricts content within the boundaries */
    will-change: transform, clip-path;
}

.c2::before {
    content: '';
    position: absolute;
    background-color: transparent; /* Ensures only shadows are visible */
    border-radius: 50px 50px 50px 0px;
    box-shadow: 
        0px 0px 0px 50px #FFF, /* Slight negative offset for top shadow to remove 1px gap */
        0px 0px 0px 0px #FFF;  /* No bottom shadow */
    pointer-events: none;
    clip-path: inset(0); /* Keeps everything confined */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.c3::before {
    content: '';
    position: absolute;
    background-color: transparent; /* Ensures only shadows are visible */
    border-radius: 50px 0px 50px 50px;
    box-shadow: 
        0px 0px 0px 50px #FFF, /* Slight negative offset for top shadow */
        0px 0px 0px 0px #FFF;  /* No bottom shadow */
    pointer-events: none;
    clip-path: inset(0); /* Keeps everything confined */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
				
			

toggle-3-items-inside-alternate

				
					<div class="toggle-btn">
    
    <span class="toggle-text" tabindex="0" aria-label="Select Free Plan" role="button" onclick="setActiveItem(0)" onkeydown="handleKeyNavigation(event, 0)">Free</span>
    <span class="toggle-text" tabindex="0" aria-label="Select Plus Plan" role="button" onclick="setActiveItem(1)" onkeydown="handleKeyNavigation(event, 1)">Plus</span>
    <span class="toggle-text" tabindex="0" aria-label="Select Pro Plan" role="button" onclick="setActiveItem(2)" onkeydown="handleKeyNavigation(event, 2)">Pro</span>
    <div class="toggle-switch-container">
        
        <label class="switch" role="switch" aria-checked="false" id="toggle-switch" tabindex="0" onkeydown="handleSwitchKeyNavigation(event)">
            <span class="slider round" id="sliderKnob"></span>
        </label>
    </div>
    
    <span id="toggle-status" aria-live="polite" class="visually-hidden"></span>
</div>

<style>.toggle-btn .toggle-text{display:inline-block;font-size:1rem;font-weight:600;vertical-align:middle;margin:10px 10px -43px 10px;cursor:pointer;color:#FFF;position:relative;z-index:2;}.toggle-btn .toggle-text:first-child{margin-right:10px;}.toggle-btn .toggle-text:last-child{margin-left:10px;}.toggle-switch-container{display:flex;justify-content:center;align-items:center;}.switch{position:relative;display:inline-block;width:168px;height:33px;background:#444;border-radius:50px;outline:none;}.slider{position:absolute;cursor:pointer;top:24px;left:0px;height:4px;width:33px;background-color:#FF0050;transition:left 0.3s ease;z-index:1;}.switch:focus .slider{outline:2px solid #FF9900;}.visually-hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;}.content-item{display:none;visibility:hidden;}.content-item.active{display:block;visibility:visible;}</style>

<script type="text/phast">const positions=[9.5,67,120];const items=['item1','item2','item3'];let activeIndex=0;function updateDisplay(){items.forEach((item,index)=>{const element=document.getElementById(item);if(element){if(index===activeIndex){element.style.display='block';element.style.visibility='visible';}else{element.style.display='none';element.style.visibility='hidden';}}});const statusElement=document.getElementById("toggle-status");statusElement.textContent=`Switched to ${document.querySelectorAll('.toggle-text')[activeIndex].textContent}`;}
function setActiveItem(index){if(index>=0&&index<items.length){activeIndex=index;const slider=document.getElementById('sliderKnob');slider.style.left=positions[activeIndex]+'px';updateDisplay();document.getElementById('toggle-switch').setAttribute('aria-checked',index!==0);}}
function handleKeyNavigation(event,index){if(event.key===" "||event.key==="Enter"){event.preventDefault();setActiveItem(index);}}
function handleSwitchKeyNavigation(event){if(event.key==="ArrowLeft"){activeIndex=(activeIndex>0)?activeIndex-1:0;setActiveItem(activeIndex);}else if(event.key==="ArrowRight"){activeIndex=(activeIndex<positions.length-1)?activeIndex+1:positions.length-1;setActiveItem(activeIndex);}else if(event.key===" "||event.key==="Enter"){event.preventDefault();setActiveItem(activeIndex);}}
function onDragStart(e){e.preventDefault();document.addEventListener('mousemove',onDrag);document.addEventListener('mouseup',onDragEnd);}
function onDrag(e){const slider=document.getElementById('sliderKnob');const container=slider.parentElement;const rect=container.getBoundingClientRect();let offsetX=e.clientX-rect.left;offsetX=Math.max(0,Math.min(offsetX,rect.width-slider.offsetWidth));const closestIndex=positions.reduce((prevIndex,currentPos,index)=>{return Math.abs(currentPos-offsetX)<Math.abs(positions[prevIndex]-offsetX)?index:prevIndex;},0);slider.style.left=positions[closestIndex]+'px';activeIndex=closestIndex;updateDisplay();}
function onDragEnd(){document.removeEventListener('mousemove',onDrag);document.removeEventListener('mouseup',onDragEnd);}
function addClickListeners(){const switchContainer=document.querySelector('.switch');switchContainer.addEventListener('click',(e)=>{const rect=switchContainer.getBoundingClientRect();let offsetX=e.clientX-rect.left;const closestIndex=positions.reduce((prevIndex,currentPos,index)=>{return Math.abs(currentPos-offsetX)<Math.abs(positions[prevIndex]-offsetX)?index:prevIndex;},0);setActiveItem(closestIndex);});}
document.getElementById('sliderKnob').addEventListener('mousedown',onDragStart);document.addEventListener('DOMContentLoaded',()=>{setActiveItem(0);addClickListeners();});</script>
				
			

image-mask-css-2

				
					/* Ensure consistent rendering of elements */
*, *::before, *::after {
    box-sizing: border-box;
}

.c12 {
    background-color: #FFF;
    border-radius: 0 0 50px 0;
    will-change: transform, clip-path;
}

.c12, .c12::before,
.c22, .c22::before,
.c32, .c32::before,
.c42, .c42::before {
    backface-visibility: hidden;
    transform: translateZ(0) translate(0, 0); /* Ensures pixel snapping */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.c12, .c22, .c32, .c42 {
    clip-path: inset(0); /* Restricts content within the boundaries */
    will-change: transform, clip-path;
}

.c22::before {
    content: '';
    position: absolute;
    background-color: transparent; /* Ensures only shadows are visible */
    border-radius: 100px 100px 0px 0px;
    box-shadow: 
        0px 0px 0px 50px #FFF, /* Slight negative offset for top shadow to remove 1px gap */
        0px 0px 0px 0px #FFF;  /* No bottom shadow */
    pointer-events: none;
    clip-path: inset(0); /* Keeps everything confined */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.c32::before {
    content: '';
    position: absolute;
    background-color: transparent; /* Ensures only shadows are visible */
    border-radius: 100px 0px 0px 100px;
    box-shadow: 
        0px 0px 0px 50px #FFF, /* Slight negative offset for top shadow */
        0px 0px 0px 0px #FFF;  /* No bottom shadow */
    pointer-events: none;
    z-index: 1;
    clip-path: inset(0); /* Keeps everything confined */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.c42::before {
    content: '';
    position: absolute;
    background-color: transparent; /* Ensures only shadows are visible */
    border-radius: 0px 0px 100px 0px;
    box-shadow: 
        0px 0px 0px 50px #FFF, /* Slight negative offset for top shadow */
        0px 0px 0px 0px #FFF;  /* No bottom shadow */
    pointer-events: none;
    clip-path: inset(0); /* Keeps everything confined */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
				
			

toggle-3-items-inside

				
					<div class="toggle-btn">
    
    <span class="toggle-text" tabindex="0" aria-label="Select Free Plan" role="button" onclick="setActiveItem(0)" onkeydown="handleKeyNavigation(event, 0)">Free</span>
    <span class="toggle-text" tabindex="0" aria-label="Select Plus Plan" role="button" onclick="setActiveItem(1)" onkeydown="handleKeyNavigation(event, 1)">Plus</span>
    <span class="toggle-text" tabindex="0" aria-label="Select Pro Plan" role="button" onclick="setActiveItem(2)" onkeydown="handleKeyNavigation(event, 2)">Pro</span>
    <div class="toggle-switch-container">
        
        <label class="switch" role="switch" aria-checked="false" id="toggle-switch" tabindex="0" onkeydown="handleSwitchKeyNavigation(event)">
            <span class="slider round" id="sliderKnob"></span>
        </label>
    </div>
    
    <span id="toggle-status" aria-live="polite" class="visually-hidden"></span>
</div>

<style>.toggle-btn .toggle-text{display:inline-block;font-size:1rem;font-weight:600;vertical-align:middle;margin:10px 10px -43px 10px;cursor:pointer;color:#FFF;position:relative;z-index:2;}.toggle-btn .toggle-text:first-child{margin-right:10px;}.toggle-btn .toggle-text:last-child{margin-left:10px;}.toggle-switch-container{display:flex;justify-content:center;align-items:center;}.switch{position:relative;display:inline-block;width:168px;height:33px;background:#444;border-radius:50px;outline:none;}.slider{position:absolute;cursor:pointer;top:4px;left:0px;height:25px;width:25px;background-color:#FFFFFF00;transition:left 0.3s ease;border-radius:50%;border:2px solid #FF0050;z-index:1;}.switch:focus .slider{outline:2px solid #FF9900;}.visually-hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;}.content-item{display:none;visibility:hidden;}.content-item.active{display:block;visibility:visible;}</style>

<script type="text/phast">const positions=[13,71,125];const items=['item1','item2','item3'];let activeIndex=0;function updateDisplay(){items.forEach((item,index)=>{const element=document.getElementById(item);if(element){if(index===activeIndex){element.style.display='block';element.style.visibility='visible';}else{element.style.display='none';element.style.visibility='hidden';}}});const statusElement=document.getElementById("toggle-status");statusElement.textContent=`Switched to ${document.querySelectorAll('.toggle-text')[activeIndex].textContent}`;}
function setActiveItem(index){if(index>=0&&index<items.length){activeIndex=index;const slider=document.getElementById('sliderKnob');slider.style.left=positions[activeIndex]+'px';updateDisplay();document.getElementById('toggle-switch').setAttribute('aria-checked',index!==0);}}
function handleKeyNavigation(event,index){if(event.key===" "||event.key==="Enter"){event.preventDefault();setActiveItem(index);}}
function handleSwitchKeyNavigation(event){if(event.key==="ArrowLeft"){activeIndex=(activeIndex>0)?activeIndex-1:0;setActiveItem(activeIndex);}else if(event.key==="ArrowRight"){activeIndex=(activeIndex<positions.length-1)?activeIndex+1:positions.length-1;setActiveItem(activeIndex);}else if(event.key===" "||event.key==="Enter"){event.preventDefault();setActiveItem(activeIndex);}}
function onDragStart(e){e.preventDefault();document.addEventListener('mousemove',onDrag);document.addEventListener('mouseup',onDragEnd);}
function onDrag(e){const slider=document.getElementById('sliderKnob');const container=slider.parentElement;const rect=container.getBoundingClientRect();let offsetX=e.clientX-rect.left;offsetX=Math.max(0,Math.min(offsetX,rect.width-slider.offsetWidth));const closestIndex=positions.reduce((prevIndex,currentPos,index)=>{return Math.abs(currentPos-offsetX)<Math.abs(positions[prevIndex]-offsetX)?index:prevIndex;},0);slider.style.left=positions[closestIndex]+'px';activeIndex=closestIndex;updateDisplay();}
function onDragEnd(){document.removeEventListener('mousemove',onDrag);document.removeEventListener('mouseup',onDragEnd);}
function addClickListeners(){const switchContainer=document.querySelector('.switch');switchContainer.addEventListener('click',(e)=>{const rect=switchContainer.getBoundingClientRect();let offsetX=e.clientX-rect.left;const closestIndex=positions.reduce((prevIndex,currentPos,index)=>{return Math.abs(currentPos-offsetX)<Math.abs(positions[prevIndex]-offsetX)?index:prevIndex;},0);setActiveItem(closestIndex);});}
document.getElementById('sliderKnob').addEventListener('mousedown',onDragStart);document.addEventListener('DOMContentLoaded',()=>{setActiveItem(0);addClickListeners();});</script>
				
			

toggle-3-items-above-alternate

				
					<div class="toggle-btn">
    
    <span class="toggle-text" tabindex="0" aria-label="Select Free Plan" role="button" onclick="setActiveItem(0)" onkeydown="handleKeyNavigation(event, 0)">Free</span>
    <span class="toggle-text" tabindex="0" aria-label="Select Plus Plan" role="button" onclick="setActiveItem(1)" onkeydown="handleKeyNavigation(event, 2)">Plus</span>
    <span class="toggle-text" tabindex="0" aria-label="Select Pro Plan" role="button" onclick="setActiveItem(2)" onkeydown="handleKeyNavigation(event, 1)">Pro</span>
    <div class="toggle-switch-container">
        
        <label class="switch" role="switch" aria-checked="false" id="toggle-switch" tabindex="0" onkeydown="handleSwitchKeyNavigation(event)">
            <span class="slider round" id="sliderKnob"></span>
        </label>
    </div>
    
    <span id="toggle-status" aria-live="polite" class="visually-hidden"></span>
</div>

<style>.toggle-btn .toggle-text{display:inline-block;font-size:1rem;font-weight:600;vertical-align:middle;margin:10px;cursor:pointer;}.toggle-btn .toggle-text:first-child{margin-right:10px;}.toggle-btn .toggle-text:last-child{margin-left:10px;}.toggle-switch-container{margin-top:-3px;display:flex;justify-content:center;align-items:center;}.switch{position:relative;display:inline-block;width:168px;height:33px;background:#444;border-radius:50px;outline:none;}.slider{position:absolute;cursor:pointer;top:4px;left:0px;height:25px;width:25px;background-color:#FFF;transition:left 0.3s ease;border-radius:50%;border:2px solid #FFF;}.switch:focus .slider{outline:2px solid #FF9900;}.visually-hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;}.content-item{display:none;visibility:hidden;}.content-item.active{display:block;visibility:visible;}</style>

<script type="text/phast">const positions=[5,71,138];const items=['item1','item2','item3'];let activeIndex=0;function updateDisplay(){items.forEach((item,index)=>{const element=document.getElementById(item);if(element){if(index===activeIndex){element.style.display='block';element.style.visibility='visible';}else{element.style.display='none';element.style.visibility='hidden';}}});const statusElement=document.getElementById("toggle-status");statusElement.textContent=`Switched to ${document.querySelectorAll('.toggle-text')[activeIndex].textContent}`;}
function setActiveItem(index){if(index>=0&&index<items.length){activeIndex=index;const slider=document.getElementById('sliderKnob');slider.style.left=positions[activeIndex]+'px';updateDisplay();document.getElementById('toggle-switch').setAttribute('aria-checked',index!==0);}}
function handleKeyNavigation(event,index){if(event.key===" "||event.key==="Enter"){event.preventDefault();setActiveItem(index);}}
function handleSwitchKeyNavigation(event){if(event.key==="ArrowLeft"){activeIndex=(activeIndex>0)?activeIndex-1:0;setActiveItem(activeIndex);}else if(event.key==="ArrowRight"){activeIndex=(activeIndex<positions.length-1)?activeIndex+1:positions.length-1;setActiveItem(activeIndex);}else if(event.key===" "||event.key==="Enter"){event.preventDefault();setActiveItem(activeIndex);}}
function onDragStart(e){e.preventDefault();document.addEventListener('mousemove',onDrag);document.addEventListener('mouseup',onDragEnd);}
function onDrag(e){const slider=document.getElementById('sliderKnob');const container=slider.parentElement;const rect=container.getBoundingClientRect();let offsetX=e.clientX-rect.left;offsetX=Math.max(0,Math.min(offsetX,rect.width-slider.offsetWidth));const closestIndex=positions.reduce((prevIndex,currentPos,index)=>{return Math.abs(currentPos-offsetX)<Math.abs(positions[prevIndex]-offsetX)?index:prevIndex;},0);slider.style.left=positions[closestIndex]+'px';activeIndex=closestIndex;updateDisplay();}
function onDragEnd(){document.removeEventListener('mousemove',onDrag);document.removeEventListener('mouseup',onDragEnd);}
function addClickListeners(){const switchContainer=document.querySelector('.switch');switchContainer.addEventListener('click',(e)=>{const rect=switchContainer.getBoundingClientRect();let offsetX=e.clientX-rect.left;const closestIndex=positions.reduce((prevIndex,currentPos,index)=>{return Math.abs(currentPos-offsetX)<Math.abs(positions[prevIndex]-offsetX)?index:prevIndex;},0);setActiveItem(closestIndex);});}
document.getElementById('sliderKnob').addEventListener('mousedown',onDragStart);document.addEventListener('DOMContentLoaded',()=>{setActiveItem(0);addClickListeners();});</script>
				
			

elementor-history-top-bar

				
					// Add custom SVG icon to simulate CMD/CTRL + Shift + H on click
function add_custom_svg_icon_with_dual_key_simulation() {
    ?>
    <script data-phast-original-type="text/javascript" type="text/phast">(function(){function createSVGIcon(){var existingIcon=document.querySelector('.custom-svg-icon');if(!existingIcon){var svgContainer=document.createElement('div');svgContainer.className='custom-svg-icon';svgContainer.style.position='fixed';svgContainer.style.top='12px';svgContainer.style.left='250px';svgContainer.style.zIndex='9999';svgContainer.style.cursor='pointer';svgContainer.innerHTML=`
                    <svg class="MuiSvgIcon-root MuiSvgIcon-fontSizeMedium css-vubbuv" focusable="false" aria-hidden="true" viewBox="0 0 24 24" style="fill: white; transform: scale(0.8); transform-origin: center;">
                        <path fill-rule="evenodd" clip-rule="evenodd" d="M8.08961 4.0956C10.0932 3.02269 12.4216 2.72496 14.6307 3.25921C16.8397 3.79346 18.7748 5.1223 20.0667 6.99219C21.3585 8.86208 21.9168 11.1421 21.6349 13.3973C21.353 15.6525 20.2507 17.725 18.5383 19.2194C16.8259 20.7137 14.6233 21.5254 12.3506 21.4994C10.078 21.4734 7.89454 20.6117 6.21673 19.0786C4.53891 17.5456 3.48423 15.4484 3.25392 13.1874C3.21194 12.7753 3.51197 12.4072 3.92405 12.3652C4.33614 12.3233 4.70422 12.6233 4.7462 13.0354C4.93916 14.9298 5.82281 16.6868 7.22855 17.9713C8.63428 19.2558 10.4637 19.9777 12.3678 19.9995C14.2719 20.0212 16.1173 19.3412 17.552 18.0892C18.9867 16.8372 19.9103 15.1008 20.1464 13.2113C20.3826 11.3218 19.9149 9.41147 18.8325 7.84481C17.7502 6.27814 16.1289 5.16479 14.2781 4.71718C12.4272 4.26956 10.4764 4.51901 8.79772 5.41794C7.44561 6.14199 6.34633 7.24658 5.62839 8.58361H8.72228C9.13649 8.58361 9.47228 8.91939 9.47228 9.33361C9.47228 9.74782 9.13649 10.0836 8.72228 10.0836H4.48963C4.47805 10.0839 4.46644 10.0839 4.4548 10.0836H4.00006C3.58584 10.0836 3.25006 9.74782 3.25006 9.33361V4.61139C3.25006 4.19717 4.00006 3.86139C4.41427 3.86139 4.75006 4.19717 4.75006 4.61139V7.1337C5.58912 5.86995 6.73269 4.82222 8.08961 4.0956ZM12.4528 8.27753C12.867 8.27753 13.2028 8.61332 13.2028 9.02753V12.4946L14.872 14.1639C15.1649 14.4568 15.1649 14.9316 14.872 15.2245C14.5792 15.5174 14.1043 15.5174 13.8114 15.2245L11.9225 13.3356C11.7818 13.195 11.7028 13.0042 11.7028 12.8053V9.02753C11.7028 8.61332 12.0386 8.27753 12.4528 8.27753Z"></path>
                    </svg>
                `;svgContainer.addEventListener('click',function(){var isMac=navigator.platform.toUpperCase().indexOf('MAC')>=0;if(isMac){var cmdShiftHEvent=new KeyboardEvent('keydown',{key:'H',code:'KeyH',keyCode:72,metaKey:true,shiftKey:true,bubbles:true,cancelable:true});document.dispatchEvent(cmdShiftHEvent);}
var ctrlShiftHEvent=new KeyboardEvent('keydown',{key:'H',code:'KeyH',keyCode:72,ctrlKey:true,shiftKey:true,bubbles:true,cancelable:true});document.dispatchEvent(ctrlShiftHEvent);});document.body.appendChild(svgContainer);}}
document.addEventListener('DOMContentLoaded',createSVGIcon);})();</script>
    <?php
}
add_action('elementor/editor/after_enqueue_scripts', 'add_custom_svg_icon_with_dual_key_simulation');
// End custom SVG icon with dual key simulation
				
			

toggle-2-items-above

				
					<div class="toggle-btn">
    <span class="toggle-text" id="monthly-label">Monthly</span>
    
    <label class="switch" role="switch" aria-checked="false" id="toggle-switch" tabindex="0">
        
        <input type="checkbox" id="checkbox" onclick="toggleDisplay()" aria-labelledby="monthly-label annually-label"/>
        <span class="slider round"></span>
    </label>
    <span class="toggle-text" id="annually-label">Annually</span>
    
    <span id="toggle-status" aria-live="polite" class="visually-hidden"></span>
</div>

<style>.toggle-btn .toggle-text{display:inline-block;font-size:1.2rem;font-weight:600;vertical-align:middle;margin:10px;}.toggle-btn .toggle-text:first-child{margin-right:10px;}.toggle-btn .toggle-text:last-child{margin-left:10px;}.switch{position:relative;display:inline-block;width:60px;height:34px;outline:none;}.switch input{display:none;}.slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#5E00FF;transition:0.4s;border-radius:50px;}.slider:before{position:absolute;content:"";height:26px;width:26px;left:4px;bottom:4px;background-color:#FFF;transition:0.4s;border-radius:50px;}input:checked + .slider{background-color:#444;}input:checked + .slider:before{transform:translateX(26px);}.switch:focus{outline:2px solid #FF9900;outline-offset:4px;}.visually-hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;}#item2{display:none;}</style>

<script type="text/phast">function toggleDisplay(){const checkBox=document.getElementById("checkbox");const item1=document.getElementById("item1");const item2=document.getElementById("item2");const switchLabel=document.getElementById("toggle-switch");const statusElement=document.getElementById("toggle-status");if(checkBox.checked){item1.style.display='none';item2.style.display='flex';switchLabel.setAttribute("aria-checked","true");statusElement.textContent="Switched to Annually";}else{item2.style.display='none';item1.style.display='flex';switchLabel.setAttribute("aria-checked","false");statusElement.textContent="Switched to Monthly";}}
document.addEventListener('DOMContentLoaded',()=>{const checkBox=document.getElementById("checkbox");checkBox.checked=false;toggleDisplay();});document.getElementById("toggle-switch").addEventListener("keydown",(event)=>{if(event.key===" "||event.key==="Enter"){event.preventDefault();const checkBox=document.getElementById("checkbox");checkBox.checked=!checkBox.checked;toggleDisplay();}});</script>
				
			

toggle-3-items-above

				
					<div class="toggle-btn">
    
    <span class="toggle-text" tabindex="0" aria-label="Select Monthly" role="button" onclick="setActiveItem(0)" onkeydown="handleKeyNavigation(event, 0)">Monthly</span>
    <span class="toggle-text" tabindex="0" aria-label="Select Quarterly" role="button" onclick="setActiveItem(1)" onkeydown="handleKeyNavigation(event, 2)">Quarterly</span>
    <span class="toggle-text" tabindex="0" aria-label="Select Annually" role="button" onclick="setActiveItem(2)" onkeydown="handleKeyNavigation(event, 1)">Annually</span>
    <div class="toggle-switch-container">
        
        <label class="switch" role="switch" aria-checked="false" id="toggle-switch" tabindex="0" onkeydown="handleSwitchKeyNavigation(event)">
            <span class="slider round" id="sliderKnob"></span>
        </label>
    </div>
    
    <span id="toggle-status" aria-live="polite" class="visually-hidden"></span>
</div>

<style>.toggle-btn .toggle-text{display:inline-block;font-size:1rem;font-weight:600;vertical-align:middle;margin:10px;cursor:pointer;}.toggle-btn .toggle-text:first-child{margin-right:10px;}.toggle-btn .toggle-text:last-child{margin-left:10px;}.toggle-switch-container{margin-top:-3px;display:flex;justify-content:center;align-items:center;}.switch{position:relative;display:inline-block;width:200px;height:33px;background:#444;border-radius:50px;outline:none;}.slider{position:absolute;cursor:pointer;top:4px;left:0px;height:25px;width:25px;background-color:#FFF;transition:left 0.3s ease;border-radius:50%;border:2px solid #FFF;}.switch:focus .slider{outline:2px solid #FF9900;}.content-item{display:none;visibility:hidden;}.content-item.active{display:block;visibility:visible;}.visually-hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;}</style>

<script type="text/phast">const positions=[5,85,170];const items=['item1','item2','item3'];let activeIndex=0;function updateDisplay(){items.forEach((item,index)=>{const element=document.getElementById(item);if(element){if(index===activeIndex){element.style.display='block';element.style.visibility='visible';}else{element.style.display='none';element.style.visibility='hidden';}}});const statusElement=document.getElementById("toggle-status");statusElement.textContent=`Switched to ${document.querySelectorAll('.toggle-text')[activeIndex].textContent}`;}
function setActiveItem(index){if(index>=0&&index<items.length){activeIndex=index;const slider=document.getElementById('sliderKnob');slider.style.left=positions[activeIndex]+'px';updateDisplay();document.getElementById('toggle-switch').setAttribute('aria-checked',index!==0);}}
function handleKeyNavigation(event,index){if(event.key===" "||event.key==="Enter"){event.preventDefault();setActiveItem(index);}}
function handleSwitchKeyNavigation(event){if(event.key==="ArrowLeft"){activeIndex=(activeIndex>0)?activeIndex-1:0;setActiveItem(activeIndex);}else if(event.key==="ArrowRight"){activeIndex=(activeIndex<positions.length-1)?activeIndex+1:positions.length-1;setActiveItem(activeIndex);}else if(event.key===" "||event.key==="Enter"){event.preventDefault();setActiveItem(activeIndex);}}
function onDragStart(e){e.preventDefault();document.addEventListener('mousemove',onDrag);document.addEventListener('mouseup',onDragEnd);}
function onDrag(e){const slider=document.getElementById('sliderKnob');const container=slider.parentElement;const rect=container.getBoundingClientRect();let offsetX=e.clientX-rect.left;offsetX=Math.max(0,Math.min(offsetX,rect.width-slider.offsetWidth));const closestIndex=positions.reduce((prevIndex,currentPos,index)=>{return Math.abs(currentPos-offsetX)<Math.abs(positions[prevIndex]-offsetX)?index:prevIndex;},0);slider.style.left=positions[closestIndex]+'px';activeIndex=closestIndex;updateDisplay();}
function onDragEnd(){document.removeEventListener('mousemove',onDrag);document.removeEventListener('mouseup',onDragEnd);}
function addClickListeners(){const switchContainer=document.querySelector('.switch');switchContainer.addEventListener('click',(e)=>{const rect=switchContainer.getBoundingClientRect();let offsetX=e.clientX-rect.left;const closestIndex=positions.reduce((prevIndex,currentPos,index)=>{return Math.abs(currentPos-offsetX)<Math.abs(positions[prevIndex]-offsetX)?index:prevIndex;},0);setActiveItem(closestIndex);});}
document.getElementById('sliderKnob').addEventListener('mousedown',onDragStart);document.addEventListener('DOMContentLoaded',()=>{setActiveItem(0);addClickListeners();});</script>
				
			

delete-unused-images aka 'Media Scanner v3.2'

read-more-single-post

				
					<div id="post-content">
  <div id="read-more-btn" onclick="toggleReadMore()">Read More ></div>
</div>

<style>#long_content{max-height:200px;overflow:hidden;transition:max-height 0.5s ease;}#long_content.full{max-height:none;}#read-more-btn{display:inline-block;margin-top:10px;cursor:pointer;color:#0073e6;font-weight:bold;}</style>

<script type="text/phast">function toggleReadMore(){var content=document.getElementById('long_content');var btn=document.getElementById('read-more-btn');if(content.classList.contains('full')){content.classList.remove('full');btn.innerHTML='Read More';}else{content.classList.add('full');btn.innerHTML='Show Less';}}</script>
				
			

lms-course

				
					<style>.container{display:none;}#container001{display:flex;}</style>

<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const buttons=document.querySelectorAll('[id^=button]');buttons.forEach(button=>{button.addEventListener('click',function(){const buttonId=this.id;const containerId=buttonId.replace('button','container');document.querySelectorAll('.container').forEach(container=>{container.style.display='none';});const containerToShow=document.getElementById(containerId);if(containerToShow){containerToShow.style.display='flex';}});});document.querySelectorAll('.container').forEach(container=>{if(container.id!=='container001'){container.style.display='none';}});});</script>
				
			

auto-adjust-coupon

				
					// Function to apply a dynamic discount based on the days left until 11th November, only for a specific product and coupon code
function apply_dynamic_discount_with_coupon( $cart ) {
    // Set the start and end dates
    $start_date = strtotime('2024-10-09');
    $end_date = strtotime('2024-11-11');
    $current_date = time();

    // Get the applied coupons in the cart
    $applied_coupons = $cart->get_applied_coupons();

    // Check if the 'pepsimax' coupon is applied
    if ( in_array( 'pepsimax', $applied_coupons ) ) {

        // Check if the current date is between the start and end date
        if ( $current_date >= $start_date && $current_date <= $end_date ) {
            // Calculate the number of days left
            $days_left = ceil(($end_date - $current_date) / (60 * 60 * 24)); // Convert seconds to days

            // Calculate the discount percentage based on days left
            $discount_percentage = 1 - ($days_left / 100); // Calculate the percentage to apply

            // Loop through each cart item
            foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                // Check if the product ID is 5248
                if ( $cart_item['product_id'] == 5248 ) {
                    // Get the sale price if available, otherwise use the regular price
                    $original_price = $cart_item['data']->get_sale_price() ? $cart_item['data']->get_sale_price() : $cart_item['data']->get_regular_price();
                    
                    // Calculate the discounted price
                    $discounted_price = round($original_price * $discount_percentage, 1); // Round to 1 decimal place
                    
                    // Set the new discounted price
                    $cart_item['data']->set_price( $discounted_price );
                }
            }
        }
    }
}

// Ensure the cart totals are updated after calculating the discount
add_action( 'woocommerce_before_calculate_totals', 'apply_dynamic_discount_with_coupon', 10, 1 );
				
			

sliding-child-container-reveal

				
					<style>@media (max-width:767px){#moveme{margin-top:-400px;z-index:100;transition:margin-top 0.2s ease-in-out;will-change:margin-top;}.elementor-nav-menu--main ul{display:flex;flex-direction:column;}#openmenu{cursor:pointer;}}</style>

<script type="text/phast">jQuery(document).ready(function($){let isOpen=false;$('#openmenu').on('click',function(){if(!isOpen){$('#moveme').css('margin-top','0px');}else{$('#moveme').css('margin-top','-400px');}
isOpen=!isOpen;});});</script>
				
			

front-end-forms-custom-elementor

off-canvas-animated-toggle-one-line

				
					<style>:root{--bar-width:30px;--bar-height:3px;--bar-color:#000;--hover-color:#000;--active-color:#fff;--bar-gap:8px;--bg-normal:transparent;--bg-hover:transparent;--bg-active:transparent;}.elementor-menu-toggle{display:none !important;}.e-off-canvas{z-index:9000 !important;}.e-font-icon-svg{opacity:0;height:calc(3px * 3 + 8px * 2) !important;visibility:visible;font-size:var(--bar-width);padding:0px 20px;z-index:9500 !important;}#toggle-icon{z-index:9500 !important;position:relative;width:var(--bar-width);height:calc(var(--bar-height) * 3 + var(--bar-gap) * 2);cursor:pointer;background-color:var(--bg-normal);transition:background-color 0.3s ease;}#toggle-icon:before,#toggle-icon:after,#toggle-icon .middle-bar{content:'';display:block;width:100%;height:var(--bar-height);background-color:var(--bar-color);position:absolute;left:0;transition:all 0.2s ease;}#toggle-icon:before{top:0;}#toggle-icon .middle-bar{top:50%;transform:translateY(-50%);}#toggle-icon:after{bottom:0;}#toggle-icon:hover{background-color:var(--bg-hover);}#toggle-icon:hover:before,#toggle-icon:hover:after,#toggle-icon:hover .middle-bar{background-color:var(--hover-color);}#toggle-icon.elementor-active{background-color:var(--bg-active);}#toggle-icon.elementor-active:before{top:50%;transform:translateY(-50%);background-color:var(--active-color);}#toggle-icon.elementor-active:after{top:50%;transform:translateY(-50%);background-color:var(--active-color);}#toggle-icon.elementor-active .middle-bar{background-color:var(--active-color);}</style>

<script type="text/phast">jQuery(document).ready(function($){if($('#toggle-icon .middle-bar').length===0){$('#toggle-icon').append('<span class="middle-bar"></span>');}
$('#toggle-icon').on('click',function(){$(this).toggleClass('elementor-active');});});</script>
				
			

form-to-custom-fields

				
					add_action( 'elementor_pro/forms/new_record', function( $record, $handler ) {

    // Configuration Variables (Everything configurable is defined here)
    $form_name = 'review_form';  // Form name as used in Elementor
    $post_type = 'review';       // Post type where the form data will be saved

    // Define your field mappings: Elementor form field ID => ACF custom field name
    $field_mappings = array(
        'r_name'   => 'review_name',    // Form field 'r_name' => ACF field 'review_name'
        'r_review' => 'review_review',  // Form field 'r_review' => ACF field 'review_review'
        'r_image'  => 'review_image',   // Form field 'r_image' => ACF field 'review_image' (Image field)
    );

    // Specify which field from the mappings should be used as post title and content
    $post_title_field = 'r_name';      // This form field will be used for the post title
    $post_content_field = 'r_review';  // This form field will be used for the post content

    // END OF CONFIGURABLE SECTION

    // Check that it's the correct form
    $submitted_form_name = $record->get_form_settings( 'form_name' );
    if ( $submitted_form_name !== $form_name ) {
        return; // If it's not the correct form, do nothing
    }

    // Get submitted form data
    $raw_fields = $record->get( 'fields' );
    $uploaded_files = $record->get( 'files' ); // Handle file uploads

    // Prepare post title and content based on the field mappings
    $post_title = isset($raw_fields[$post_title_field]['value']) ? wp_strip_all_tags($raw_fields[$post_title_field]['value']) : 'Untitled';
    $post_content = isset($raw_fields[$post_content_field]['value']) ? $raw_fields[$post_content_field]['value'] : '';

    // Insert a new post into the specified post type
    $new_post = array(
        'post_title'    => $post_title,   // Use mapped field for the post title
        'post_content'  => $post_content, // Use mapped field for the post content
        'post_status'   => 'publish',
        'post_type'     => $post_type,    // Use configurable post type
    );
    $post_id = wp_insert_post( $new_post );  // Insert the post and get the post ID

    // Log post creation for debugging
    error_log( 'Post created with ID: ' . $post_id );

    // Handle all fields including the image
    if ( function_exists( 'update_field' ) ) {
        foreach ( $field_mappings as $form_field => $acf_field ) {
            // If it's a file (image) field, handle the upload
            if ( isset($uploaded_files[$form_field]['path'][0]) && !empty($uploaded_files[$form_field]['path'][0]) ) {
                // Get the file path and create an array for media upload
                $file_path = $uploaded_files[$form_field]['path'][0];
                $file_name = basename( $file_path );
                $file_array = array(
                    'name'     => $file_name,
                    'tmp_name' => $file_path,
                );

                // Upload the image into the WordPress media library
                $attachment_id = media_handle_sideload( $file_array, $post_id );

                // Check for errors during upload
                if ( is_wp_error( $attachment_id ) ) {
                    error_log( 'Image upload error: ' . $attachment_id->get_error_message() );
                } else {
                    // Attach the uploaded image to the custom field
                    update_field( $acf_field, $attachment_id, $post_id );
                    error_log( 'Image uploaded successfully with ID: ' . $attachment_id );
                }
            }
            // If it's a text or non-file field, just update it as usual
            elseif ( isset($raw_fields[$form_field]['value']) && !empty($raw_fields[$form_field]['value']) ) {
                update_field( $acf_field, $raw_fields[$form_field]['value'], $post_id );  // Update each ACF field
            }
        }
    }

}, 10, 2 );
				
			

off-canvas-animated-toggle-middle-bar

				
					<style>:root{--bar-width:30px;--bar-height:3px;--bar-color:#000;--hover-color:#000;--active-color:#fff;--bar-gap:8px;--move-middle:7px;--bg-normal:transparent;--bg-hover:transparent;--bg-active:transparent;}.elementor-menu-toggle{display:none !important;}.e-off-canvas{z-index:9000 !important;}#toggle-icon{z-index:9500 !important;}.e-font-icon-svg{opacity:0;height:calc(3px * 3 + 8px * 2) !important;visibility:visible;font-size:var(--bar-width);padding:0px 20px;z-index:9500 !important;}#toggle-icon{position:relative;width:var(--bar-width);height:calc(var(--bar-height) * 3 + var(--bar-gap) * 2);cursor:pointer;background-color:var(--bg-normal);transition:background-color 0.3s ease;}#toggle-icon:before,#toggle-icon:after,#toggle-icon .middle-bar{content:'';display:block;width:100%;height:var(--bar-height);background-color:var(--bar-color);position:absolute;left:0;transition:all 0.2s ease;}#toggle-icon:before{top:0;}#toggle-icon .middle-bar{top:50%;transform:translateY(-50%);}#toggle-icon:after{bottom:0;}#toggle-icon:hover{background-color:var(--bg-hover);}#toggle-icon:hover:before,#Icontoggle-icon333:hover:after,#toggle-icon:hover .middle-bar{background-color:var(--hover-color);}#toggle-icon.elementor-active{background-color:var(--bg-active);}#toggle-icon.elementor-active .middle-bar{transform:translateY(-50%) translateX(var(--move-middle));background-color:var(--active-color);}#toggle-icon.elementor-active:before,#toggle-icon.elementor-active:after{background-color:var(--active-color);}</style>

<script type="text/phast">jQuery(document).ready(function($){if($('#toggle-icon .middle-bar').length===0){$('#toggle-icon').append('<span class="middle-bar"></span>');}
$('#toggle-icon').on('click',function(){$(this).toggleClass('elementor-active');});});</script>
				
			

animated-nav-to-middle-slide

				
					<style>:root{--bar-width:30px;--bar-height:2px;--bar-color:#000;--hover-color:#ff0050;--active-color:#0000ff;--bar-gap:8px;--move-middle:5px;--bg-normal:#fff;--bg-hover:#fff;--bg-active:#fff;}.elementor-menu-toggle__icon--open,.elementor-menu-toggle__icon--close{display:none;}.elementor-menu-toggle{position:relative;width:var(--bar-width);height:calc(var(--bar-height) * 3 + var(--bar-gap) * 2);cursor:pointer;background-color:var(--bg-normal);transition:background-color 0.3s ease;}.elementor-menu-toggle:before,.elementor-menu-toggle:after,.elementor-menu-toggle .middle-bar{content:'';display:block;width:100%;height:var(--bar-height);background-color:var(--bar-color);position:absolute;left:0;transition:all 0.3s ease;}.elementor-menu-toggle:before{top:0;}.elementor-menu-toggle .middle-bar{top:50%;transform:translateY(-50%);}.elementor-menu-toggle:after{bottom:0;}.elementor-menu-toggle:hover{background-color:var(--bg-hover);}.elementor-menu-toggle:hover:before,.elementor-menu-toggle:hover:after,.elementor-menu-toggle:hover .middle-bar{background-color:var(--hover-color);}.elementor-menu-toggle.elementor-active{background-color:var(--bg-active);}.elementor-menu-toggle.elementor-active:before,.elementor-menu-toggle.elementor-active:after{transform:translateY(0);background-color:var(--active-color);}.elementor-menu-toggle.elementor-active .middle-bar{transform:translateY(-50%) translateX(var(--move-middle));background-color:var(--active-color);}</style>

<script type="text/phast">jQuery(document).ready(function($){if($('.elementor-menu-toggle').length){$('.elementor-menu-toggle').append('<span class="middle-bar"></span>');}});</script>
				
			

elementor-top-bar-pixel-width

				
					// Description: Displays the responsive width of the preview in the Elementor editor
// Author: Carlos Béjinha
// Author URI: https://binformatica.pt
// ------------------------------------
// Info Width In Elementor Editor
function add_custom_script_to_elementor() {
    ?>
    <script data-phast-original-type="text/javascript" type="text/phast">(function(){function updateWidth(){var preview=document.getElementById('elementor-preview-responsive-wrapper');if(preview){var width=preview.offsetWidth||0;width=width-40;var displayWidth=document.getElementById('width');if(!displayWidth){displayWidth=document.createElement('div');displayWidth.id='width';displayWidth.style.position='fixed';displayWidth.style.top='10px';displayWidth.style.left='300px';displayWidth.style.color='white';displayWidth.style.backgroundColor='rgba(0, 0, 0, 0.7)';displayWidth.style.padding='5px 10px';displayWidth.style.zIndex='9999';displayWidth.style.fontSize='14px';document.body.appendChild(displayWidth);}
displayWidth.textContent='Width: '+width+'px';}else{console.log('Element #elementor-preview-responsive-wrapper not found.');}}
setInterval(function(){try{updateWidth();}catch(e){console.error('Error updating width: ',e);}},200);})();</script>
    <?php
}
add_action('elementor/editor/after_enqueue_scripts', 'add_custom_script_to_elementor');
// End Info Width In Elementor Editor
				
			

Multiple-Reveal-Select-Taxonomy-Filter

				
					<script type="text/phast">(function($){$(document).ready(function(){$('.e-filter-item[data-filter^="child-"]').hide();$('.e-filter-item[data-filter^="parent"]').each(function(){var parentSlug=$(this).attr('data-filter').split('-')[1];if($('.e-filter-item[data-filter^="child-'+parentSlug+'"]').length>0){$(this).addClass('has-children');}});$('.e-filter-item').on('click',function(){var selectedFilter=$(this).attr('data-filter');console.log("Selected Filter:",selectedFilter);if(!selectedFilter.startsWith('child-')){var parentSlug=selectedFilter.split('-')[1];console.log("Extracted Parent Slug:",parentSlug);TaxonomyFilter.toggleChildrenVisibility(parentSlug);}
filterLoopGrid(selectedFilter);});});var TaxonomyFilter={toggleChildrenVisibility:function(parentSlug){var children=$('.e-filter-item[data-filter^="child-'+parentSlug+'"]');if(children.is(':visible')){children.removeClass('force-show').hide();console.log("Children hidden for parentSlug:",parentSlug);}else{children.addClass('force-show').show();console.log("Children shown for parentSlug:",parentSlug);}}};function filterLoopGrid(filter){$('.elementor-loop-container .elementor-grid-item').hide();if(filter==='all'){$('.elementor-loop-container .elementor-grid-item').show();}else if(filter.startsWith('child-')){$('.elementor-loop-container .elementor-grid-item[data-category="'+filter+'"]').show();}else{$('.elementor-loop-container .elementor-grid-item').filter(function(){var itemCategory=$(this).attr('data-category');return itemCategory===filter||itemCategory.startsWith('child-'+filter.split('-')[1]);}).show();}}})(jQuery);</script>
				
			

multiple-source-loop-grid

				
					add_action( 'elementor/query/multiple_source', function( $query ) {
    $query->set( 'post_type', ['post', 'team'] );
});
				
			

Hide-Child-Taxonomy-Until-Parent-Clicked

				
					<script type="text/phast">(function($){var TaxonomyFilter={toggleChildrenVisibility:function(parentSlug){$('.e-filter-item[data-filter^="child-"]').removeClass('force-show').hide();console.log("Parent Slug:",parentSlug);var children=$('.e-filter-item[data-filter^="child-'+parentSlug+'"]');children.each(function(){console.log("Child Filter Found:",$(this).attr('data-filter'));});if(children.length>0){children.addClass('force-show').show();console.log("Children to Show:",children);}else{console.log("No children found for parentSlug:",parentSlug);}}};function filterLoopGrid(filter){$('.elementor-loop-container .elementor-grid-item').hide();if(filter==='all'){$('.elementor-loop-container .elementor-grid-item').show();}else if(filter.startsWith('child-')){$('.elementor-loop-container .elementor-grid-item[data-category="'+filter+'"]').show();}else{$('.elementor-loop-container .elementor-grid-item').filter(function(){var itemCategory=$(this).attr('data-category');return itemCategory===filter||itemCategory.startsWith('child-'+filter.split('-')[1]);}).show();}}
$(document).ready(function(){$('.e-filter-item[data-filter^="child-"]').hide();$('.e-filter-item').on('click',function(){var selectedFilter=$(this).attr('data-filter');console.log("Selected Filter:",selectedFilter);if(!selectedFilter.startsWith('child-')){var parentSlug=selectedFilter.split('-')[1];console.log("Extracted Parent Slug:",parentSlug);TaxonomyFilter.toggleChildrenVisibility(parentSlug);}
filterLoopGrid(selectedFilter);});});})(jQuery);</script>
				
			

Elementor-Dynamic-Pop-Up-Loop

				
					<style>.container{display:none;}.button_style{pointer-events:auto;cursor:pointer;}</style>

<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const buttons=document.querySelectorAll('[id^=button]');buttons.forEach(button=>{button.addEventListener('click',function(){const postID=button.id.replace('button','');const containerID='container'+postID;document.querySelectorAll('.container').forEach(container=>{container.style.display='none';});const containerToShow=document.getElementById(containerID);if(containerToShow){containerToShow.style.display='block';}});});document.querySelectorAll('.close-icon').forEach(icon=>{icon.addEventListener('click',function(){document.querySelectorAll('.container').forEach(container=>{container.style.display='none';});});});});</script>
				
			

Elementor-Loop-Current-Query-Sort

				
					add_action( 'elementor/query/customorder', function( $query ) {
    $query->set( 'orderby', 'date' );
    // $query->set( 'orderby', 'title' );
    // $query->set( 'orderby', 'menu_order' );
    $query->set( 'order', 'ASC' );
});
				
			

text-colour-palette

				
					function my_custom_colors($init) {
    // Define the custom colors: color code, description (as displayed in TinyMCE)
    $custom_colors = '
        "1C1C1B", "Black",
        "4D4D4D", "Gray",
        "F96966", "Red",
        "2081A4", "Blue"
    ';
    // Add the colors to the textcolor_map setting of TinyMCE
    $init['textcolor_map'] = '[' . $custom_colors . ']';
    // Set the number of rows in the TinyMCE color picker
    $init['textcolor_rows'] = 2; 
    return $init;
}
add_filter('tiny_mce_before_init', 'my_custom_colors');
				
			

Just-Child-Taxonomy-Elementor

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){var filter=document.querySelector('.Child_Filter .e-filter');if(filter){var buttons=filter.querySelectorAll('.e-filter-item');buttons.forEach(function(button){if(button.textContent.trim().toLowerCase().includes('parent')){button.style.display='none';}});}});</script>
				
			

Email-Verfication

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){var emailField=document.getElementById('form-field-email');var emailCheckField=document.getElementById('form-field-email_check');var htmlFields=document.querySelectorAll('.elementor-field-type-html');var emailConfirmField=htmlFields[0];var submitButton=document.querySelector('.elementor-button');function validateEmails(){if(emailField.value===emailCheckField.value){emailConfirmField.innerHTML="<span style='color: green;'>Email entered successfully.</span>";submitButton.disabled=false;}else{emailConfirmField.innerHTML="<span style='color: red;'>Emails must match.</span>";submitButton.disabled=true;}}
emailField.addEventListener('input',validateEmails);emailCheckField.addEventListener('input',validateEmails);submitButton.disabled=true;});</script>
				
			

animated-nav-to-middle-line

				
					<style>:root{--bar-width:30px;--bar-height:2px;--bar-color:#000;--hover-color:#ff0050;--active-color:#0000ff;--bar-gap:6px;--bg-normal:#fff;--bg-hover:#fff;--bg-active:#fff;}.elementor-menu-toggle__icon--open,.elementor-menu-toggle__icon--close{display:none;}.elementor-menu-toggle{position:relative;width:var(--bar-width);height:calc(var(--bar-height) * 3 + var(--bar-gap) * 2);cursor:pointer;background-color:var(--bg-normal);transition:background-color 0.3s ease;}.elementor-menu-toggle:before,.elementor-menu-toggle:after,.elementor-menu-toggle .middle-bar{content:'';display:block;width:100%;height:var(--bar-height);background-color:var(--bar-color);position:absolute;left:0;transition:all 0.3s ease;}.elementor-menu-toggle:before{top:0;}.elementor-menu-toggle .middle-bar{top:calc(var(--bar-gap) + var(--bar-height));background-color:var(--bar-color);}.elementor-menu-toggle:after{bottom:0;}.elementor-menu-toggle:hover{background-color:var(--bg-hover);}.elementor-menu-toggle:hover:before,.elementor-menu-toggle:hover:after,.elementor-menu-toggle:hover .middle-bar{background-color:var(--hover-color);}.elementor-menu-toggle.elementor-active{background-color:var(--bg-active);}.elementor-menu-toggle.elementor-active:before{top:50%;transform:translateY(-50%);background-color:var(--active-color);}.elementor-menu-toggle.elementor-active:after{bottom:50%;transform:translateY(50%);background-color:var(--active-color);}.elementor-menu-toggle.elementor-active .middle-bar{background-color:var(--active-color);}</style>

<script type="text/phast">jQuery(document).ready(function($){if($('.elementor-menu-toggle').length){$('.elementor-menu-toggle').append('<span class="middle-bar"></span>');}});</script>
				
			

animated-nav-to-cross

				
					<style>:root{--bar-width:30px;--bar-height:2px;--bar-color:#000;--hover-color:#ff0050;--active-color:#0000ff;--bar-gap:8px;--bg-normal:#fff;--bg-hover:#fff;--bg-active:#fff;}.elementor-menu-toggle__icon--open,.elementor-menu-toggle__icon--close{display:none;}.elementor-menu-toggle{position:relative;width:var(--bar-width);height:calc(var(--bar-height) * 3 + var(--bar-gap) * 2);cursor:pointer;background-color:var(--bg-normal);transition:background-color 0.3s ease;}.elementor-menu-toggle:before,.elementor-menu-toggle:after,.elementor-menu-toggle .middle-bar{content:'';display:block;width:100%;height:var(--bar-height);background-color:var(--bar-color);position:absolute;left:0;transition:all 0.3s ease;}.elementor-menu-toggle:before{top:0;}.elementor-menu-toggle .middle-bar{top:50%;transform:translateY(-50%);}.elementor-menu-toggle:after{bottom:0;}.elementor-menu-toggle:hover{background-color:var(--bg-hover);}.elementor-menu-toggle:hover:before,.elementor-menu-toggle:hover:after,.elementor-menu-toggle:hover .middle-bar{background-color:var(--hover-color);}.elementor-menu-toggle.elementor-active{background-color:var(--bg-active);}.elementor-menu-toggle.elementor-active:before{transform:translateY(calc(var(--bar-gap) + var(--bar-height))) rotate(45deg);background-color:var(--active-color);}.elementor-menu-toggle.elementor-active:after{transform:translateY(calc(-1 * (var(--bar-gap) + var(--bar-height)))) rotate(-45deg);background-color:var(--active-color);}.elementor-menu-toggle.elementor-active .middle-bar{opacity:0;}</style>

<script type="text/phast">jQuery(document).ready(function($){if($('.elementor-menu-toggle').length){$('.elementor-menu-toggle').append('<span class="middle-bar"></span>');}});</script>
				
			

Form-PayPal-Many-Select

				
					
<form id="paypal-form" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
    <input type="hidden" name="cmd" value="_xclick">
    <input type="hidden" name="business" value="imp78@outlook.com">
    <input type="hidden" id="paypal-item-name" name="item_name" value="Purchase">
    <input type="hidden" name="currency_code" value="USD">
    <input type="hidden" id="paypal-amount" name="amount" value="">
    <input type="submit" id="paypal-submit" value="Pay with PayPal">
</form>

<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const nameField=document.getElementById('form-field-name');const emailField=document.getElementById('form-field-email');const submitButton=document.getElementById('paypal-submit');function checkFields(){if(nameField.value.trim()!==''&&emailField.value.trim()!==''){submitButton.disabled=false;}else{submitButton.disabled=true;}}
nameField.addEventListener('input',checkFields);emailField.addEventListener('input',checkFields);checkFields();});</script>
				
			

Form-PayPal

				
					
<form id="paypal-form" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
    <input type="hidden" name="cmd" value="_xclick">
    <input type="hidden" name="business" value="imp78@outlook.com">
    <input type="hidden" id="paypal-item-name" name="item_name" value="Purchase">
    <input type="hidden" name="currency_code" value="USD">
    <input type="hidden" id="paypal-amount" name="amount" value="">
    <input type="submit" id="paypal-submit" value="Pay with PayPal">
</form>

<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const nameField=document.getElementById('form-field-name');const emailField=document.getElementById('form-field-email');const submitButton=document.getElementById('paypal-submit');function checkFields(){if(nameField.value.trim()!==''&&emailField.value.trim()!==''){submitButton.disabled=false;}else{submitButton.disabled=true;}}
nameField.addEventListener('input',checkFields);emailField.addEventListener('input',checkFields);checkFields();});</script>
				
			

Calculated-Checkbox-PayPal

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const optionsField=document.querySelectorAll('input[name="form_fields[options][]"]');const totalField=document.getElementById('form-field-total');const paypalAmountInput=document.getElementById('paypal-amount');const paypalItemNameInput=document.getElementById('paypal-item-name');const form=document.getElementById('paypal-form');function getOptionPrice(option){switch(option){case'Option 1 - $1':return 1;case'Option 2 - $1':return 1;case'Option 3 - $15':return 15;case'Option 4 - $20':return 20;case'Option 5 - $25':return 25;default:return 0;}}
function calculateTotalAndItemName(){let total=0;let selectedOptions=[];optionsField.forEach(function(option){if(option.checked){total+=getOptionPrice(option.value);selectedOptions.push(option.value.split(' - ')[0]);}});totalField.value=`$${total.toFixed(2)}`;paypalAmountInput.value=total.toFixed(2);paypalItemNameInput.value=selectedOptions.join(', ');}
optionsField.forEach(function(option){option.addEventListener('change',calculateTotalAndItemName);});calculateTotalAndItemName();form.addEventListener('keypress',function(event){if(event.key==='Enter'){event.preventDefault();}});});</script>
				
			

pop-up-day

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){function controlPopup(){const popup=document.getElementById('elementor-popup-modal-8118');const overlay=document.querySelector('.elementor-popup-modal-overlay');if(popup){const currentDay=new Date().getDay();if(currentDay!==2){hidePopup(popup,overlay);}else{showPopup(popup,overlay);}}}
function hidePopup(popup,overlay){if(popup){popup.style.display='none';popup.classList.remove('elementor-popup-modal-open');}
if(overlay){overlay.style.display='none';overlay.classList.remove('elementor-popup-modal-overlay');}
document.body.classList.remove('elementor-popup-active');const dialogElements=document.querySelectorAll('.dialog-widget, .dialog-lightbox-widget, .dialog-type-buttons, .dialog-type-lightbox, .elementor-popup-modal, .elementor-popup-modal-open');dialogElements.forEach(element=>{element.style.display='none';element.style.visibility='hidden';element.classList.remove('elementor-popup-modal-open');element.classList.remove('elementor-popup-modal');});if(typeof jQuery!=='undefined'){jQuery(popup).trigger('elementor/popup/hide');}}
function showPopup(popup,overlay){if(popup){popup.style.display='flex';popup.classList.add('elementor-popup-modal-open');}
if(overlay){overlay.style.display='block';overlay.classList.add('elementor-popup-modal-overlay');}
document.body.classList.add('elementor-popup-active');}
controlPopup();const observer=new MutationObserver(function(){controlPopup();});observer.observe(document.body,{childList:true,subtree:true});setTimeout(controlPopup,1000);setTimeout(controlPopup,3000);document.addEventListener('click',function(event){const popup=document.getElementById('elementor-popup-modal-8118');const overlay=document.querySelector('.elementor-popup-modal-overlay');if(event.target.closest('.dialog-close-button')||event.target===overlay){hidePopup(popup,overlay);}});});</script>
				
			

off-canvas-animated-toggle-cross

				
					<style>:root{--bar-width:30px;--bar-height:3px;--bar-color:#000;--hover-color:#000;--active-color:#fff;--bar-gap:8px;--bg-normal:transparent;--bg-hover:transparent;--bg-active:transparent;}.elementor-menu-toggle{display:none !important;}.e-off-canvas{z-index:9000 !important;}.e-font-icon-svg{opacity:0;height:calc(3px * 3 + 8px * 2) !important;visibility:visible;font-size:var(--bar-width);padding:0px 20px;z-index:9500 !important;}#toggle-icon{z-index:9500 !important;position:relative;width:var(--bar-width);height:calc(var(--bar-height) * 3 + var(--bar-gap) * 2);cursor:pointer;background-color:var(--bg-normal);transition:background-color 0.3s ease;}#toggle-icon:before,#toggle-icon:after,#toggle-icon .middle-bar{content:'';display:block;width:100%;height:var(--bar-height);background-color:var(--bar-color);position:absolute;left:0;transition:all 0.2s ease;}#toggle-icon:before{top:0;}#toggle-icon .middle-bar{top:50%;transform:translateY(-50%);}#toggle-icon:after{bottom:0;}#toggle-icon:hover{background-color:var(--bg-hover);}#toggle-icon:hover:before,#toggle-icon:hover:after,#toggle-icon:hover .middle-bar{background-color:var(--hover-color);}#toggle-icon.elementor-active{background-color:var(--bg-active);}#toggle-icon.elementor-active:before{transform:translateY(calc(var(--bar-gap) + var(--bar-height))) rotate(45deg);background-color:var(--active-color);}#toggle-icon.elementor-active:after{transform:translateY(calc(-1 * (var(--bar-gap) + var(--bar-height)))) rotate(-45deg);background-color:var(--active-color);}#toggle-icon.elementor-active .middle-bar{opacity:0;}</style>

<script type="text/phast">jQuery(document).ready(function($){if($('#toggle-icon .middle-bar').length===0){$('#toggle-icon').append('<span class="middle-bar"></span>');}
$('#toggle-icon').on('click',function(){$(this).toggleClass('elementor-active');});});</script>
				
			

Calculated-Dropdown

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const quantityField=document.getElementById('form-field-quantity');const priceField=document.getElementById('form-field-price');const totalField=document.getElementById('form-field-total');const optionsField=document.getElementById('form-field-options');function getPrice(option){switch(option){case'Option A':return 5.99;case'Option B':return 9.99;case'Option C':return 19.99;default:return 0;}}
function updatePrice(){const selectedOption=optionsField.value;const price=getPrice(selectedOption);priceField.value=`$${price.toFixed(2)}`;return price;}
function calculateTotal(){let quantity=parseFloat(quantityField.value)||0;const price=parseFloat(priceField.value.replace('$',''))||0;if(quantity<1){quantity=1;quantityField.value=1;}
const total=quantity*price;totalField.value=`$${total.toFixed(2)}`;}
updatePrice();calculateTotal();quantityField.addEventListener('input',calculateTotal);optionsField.addEventListener('change',function(){updatePrice();calculateTotal();});});</script>
				
			

Calculated-Many-Selects

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const optionsQuantityField=document.getElementById('form-field-quantity_options');const servicesQuantityField=document.getElementById('form-field-quantity_services');const optionsPriceField=document.getElementById('form-field-price_options');const servicesPriceField=document.getElementById('form-field-price_services');const totalField=document.getElementById('form-field-total');const optionsField=document.getElementById('form-field-options');const servicesField=document.getElementById('form-field-services');function getPrice(option){switch(option){case'Option A - $1':return 1;case'Option B - $1':return 1;case'Option C - $1':return 1;default:return 0;}}
function getServicePrice(service){switch(service){case'Service 1 - $1':return 1;case'Service 2 - $1':return 1;case'Service 3 - $1':return 1;default:return 0;}}
function updatePrices(){const selectedOption=optionsField.value;const selectedService=servicesField.value;const optionPrice=getPrice(selectedOption);const servicePrice=getServicePrice(selectedService);const optionsQuantity=parseFloat(optionsQuantityField.value)||0;const servicesQuantity=parseFloat(servicesQuantityField.value)||0;const optionsTotalPrice=optionsQuantity*optionPrice;const servicesTotalPrice=servicesQuantity*servicePrice;optionsPriceField.value=`$${optionsTotalPrice.toFixed(2)}`;servicesPriceField.value=`$${servicesTotalPrice.toFixed(2)}`;return{optionsTotalPrice,servicesTotalPrice};}
function calculateTotal(){const{optionsTotalPrice,servicesTotalPrice}=updatePrices();const total=optionsTotalPrice+servicesTotalPrice;totalField.value=`$${total.toFixed(2)}`;}
calculateTotal();optionsQuantityField.addEventListener('input',calculateTotal);servicesQuantityField.addEventListener('input',calculateTotal);optionsField.addEventListener('change',calculateTotal);servicesField.addEventListener('change',calculateTotal);});</script>
				
			

Calculated-Checkbox

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const optionsField=document.querySelectorAll('input[name="form_fields[options][]"]');const totalField=document.getElementById('form-field-total');function getOptionPrice(option){switch(option){case'Option 1 - $5':return 5;case'Option 2 - $10':return 10;case'Option 3 - $15':return 15;case'Option 4 - $20':return 20;case'Option 5 - $25':return 25;default:return 0;}}
function calculateTotal(){let total=0;optionsField.forEach(function(option){if(option.checked){total+=getOptionPrice(option.value);}});totalField.value=`$${total.toFixed(2)}`;}
optionsField.forEach(function(option){option.addEventListener('change',calculateTotal);});calculateTotal();});</script>
				
			

Calculated-Basic

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const quantityField=document.getElementById('form-field-quantity');const priceField=document.getElementById('form-field-price');const totalField=document.getElementById('form-field-total');const initialPrice=19.99;priceField.value=`$${initialPrice.toFixed(2)}`;function calculateTotal(){let quantity=parseFloat(quantityField.value)||0;let price=parseFloat(priceField.value.replace('$',''))||0;if(quantity<1){quantity=1;quantityField.value=1;}
const total=quantity*price;totalField.value=`$${total.toFixed(2)}`;}
quantityField.addEventListener('input',calculateTotal);});</script>
				
			

Colour-Transition

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const heading=document.querySelector('.color-change-1 .elementor-heading-title');const headingOffsetTop=heading.getBoundingClientRect().top+window.pageYOffset;const headingHeight=heading.offsetHeight;window.addEventListener('scroll',function(){const scrollPosition=window.pageYOffset+(window.innerHeight*0.85);const distanceFromHeading=scrollPosition-headingOffsetTop;const percentage=Math.min(Math.max((distanceFromHeading/((window.innerHeight+headingHeight)/5)),0),1);heading.style.backgroundPosition=`${100 - (percentage * 100)}% 0`;});});</script>

<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const heading=document.querySelector('.color-change-2 .elementor-heading-title');const headingOffsetTop=heading.getBoundingClientRect().top+window.pageYOffset;const headingHeight=heading.offsetHeight;window.addEventListener('scroll',function(){const scrollPosition=window.pageYOffset+(window.innerHeight*0.70);const distanceFromHeading=scrollPosition-headingOffsetTop;const percentage=Math.min(Math.max((distanceFromHeading/((window.innerHeight+headingHeight)/5)),0),1);heading.style.backgroundPosition=`${100 - (percentage * 100)}% 0`;});});</script>
				
			

Password-Protect-Page-Style

				
					function customize_password_protected_page() {
    // Add Custom CSS
    echo '<style>.post-password-form-wrapper{display:flex;justify-content:center;width:100%;box-sizing:border-box;padding:200px 20px 0 20px;}.post-password-form{width:700px;max-width:90vw;text-align:left;}.password-protected-title{font-size:24px;font-weight:600;margin-bottom:20px;}.post-password-form p{font-size:18px;margin-bottom:20px;}.post-password-form input[type="password"]{padding:10px;font-size:16px;flex:1;margin-right:10px;box-sizing:border-box;height:40px;}.post-password-form input[type="submit"]{padding:7px 20px 10px 20px;font-size:16px;font-weight:600;background-color:#FF0050;color:white;border:none;cursor:pointer;box-sizing:border-box;height:40px;display:flex;align-items:center;}.post-password-form input[type="submit"]:hover{background-color:#000000;}.password-input-container{display:flex;align-items:center;margin-bottom:20px;}.additional-info{margin-top:20px;font-size:18px;}.additional-info a{color:#FF0050;text-decoration:none;}.additional-info a:hover{text-decoration:underline;}</style>';

    // Add Custom JavaScript for Message
    echo '<script data-phast-original-type="text/javascript" type="text/phast">document.addEventListener("DOMContentLoaded",function(){var protectedMessage=document.querySelector(".post-password-form p");if(protectedMessage){protectedMessage.textContent="You are not allowed here.";}});</script>';
}

add_action('wp_head', 'customize_password_protected_page');

// Add the Title Header and Additional Text with Link
function add_custom_password_title($content) {
    if (post_password_required()) {
        $title = '<div class="post-password-form-wrapper"><div class="post-password-form"><h1 class="password-protected-title">Login to Access</h1>';
        $additional_info = '<div class="additional-info">If you do not have a password then go here: <a href="https://learn.websquadron.co.uk">learn.websquadron.co.uk</a></div>';
        $content = $title . '<div class="password-input-container">' . $content . '</div>' . $additional_info . '</div></div>';
    }
    return $content;
}
add_filter('the_content', 'add_custom_password_title');
				
			

Stop-FOUC

				
					add_action( 'wp_enqueue_scripts', function() {
	if ( ! class_exists( '\Elementor\Core\Files\CSS\Post' ) ) {
		return;
	}
	$template_id = 4040;
	$css_file = new \Elementor\Core\Files\CSS\Post( $template_id );
	$css_file->enqueue();
}, 500 );
				
			

Text-Background

				
					/* Add this HTML firsy */
<p>I am <span class="highlighted-text">&nbsp;coloured text&nbsp;</span> in a line.</p>

/*Add this CSS */
 .highlighted-text {
    position: relative;
    display: inline-block;
    }

.highlighted-text::before {
    content: '';
    position: absolute;
    top: 45%;
    left: 0%;
    right: 0%;
    height: 60%;
    background-color: #fac000;
    transform: rotate(-1.5deg);
    z-index: -1;
    border-radius: 100px;
}
				
			

Highlight-Text

				
					<p style="font-family: 'Merriweather', sans-serif; 
font-size: clamp(1.20rem, 0.52759rem + 2.86897vw, 2.50rem);
font-weight: 600; color: #222222;">I am <span class="highlighted-text2">&nbsp;coloured text&nbsp;</span> in a line.</p>
				
			

Reduce-Cart-based-on-Items

				
					add_action('woocommerce_before_calculate_totals', 'apply_discount_based_on_item_count', 10, 1);

function apply_discount_based_on_item_count($cart) {
    // Only run this in the frontend and make sure we're not in the admin or doing ajax
    if (is_admin() && !defined('DOING_AJAX')) return;

    // Check if the action has already been fired to prevent multiple discount applications
    if (did_action('woocommerce_before_calculate_totals') >= 2) return;

    // Count the number of items in the cart
    $item_count = $cart->get_cart_contents_count();

    // Apply a $100 discount if there are 3 or more items
    if ($item_count >= 3) {
        $discount = 100;

        // Add a negative fee to the cart to apply the discount
        $cart->add_fee('Bulk Discount', -$discount, true);
    }
}
				
			

Restrict-Course-Pages

				
					function restrict_page_access() {
    // Configuration
    $access_rules = [
        'course-1' => [
            'product_ids' => [183],
            'redirect'    => 'https://websquadron.s3-tastewp.com/shop',
        ],
        'course-2' => [
            'product_ids' => [183, 186],
            'redirect'    => 'https://websquadron.s3-tastewp.com/contact',
        ],
        'course-3' => [
            'product_ids' => [190, 191],
            'redirect'    => 'https://websquadron.s3-tastewp.com/home',
        ],
    ];

    // Get current user ID and check if the user is an administrator
    $user_id = get_current_user_id();
    $is_admin = current_user_can('administrator');

    // If user is an administrator, skip restriction checks
    if ($is_admin) {
        return;
    }

    // Get the current page
    $current_page = get_queried_object();

    // Ensure $current_page is a WP_Post object
    if (!($current_page instanceof WP_Post)) {
        return;
    }

    // Iterate through access rules and apply restrictions
    foreach ($access_rules as $slug => $rule) {
        if ($current_page->post_name === $slug) {
            // Check if user has purchased any of the required products
            $has_purchased = false;
            foreach ($rule['product_ids'] as $product_id) {
                if (wc_customer_bought_product($user_id, $user_id, $product_id)) {
                    $has_purchased = true;
                    break;
                }
            }

            // Redirect if the user hasn't purchased the required products
            if (!$has_purchased) {
                wp_redirect($rule['redirect']);
                exit;
            }
        }
    }
}
add_action('template_redirect', 'restrict_page_access');
				
			

Add-to-Cart-JS-Variation

				
					<script type="text/phast">jQuery(function($){$('.variation-changes-container').on('change','input[type="radio"]',function(){var radioName=$(this).attr('name');var radioValue=$(this).val();$('select[name="'+radioName+'"]').val(radioValue).trigger('change');});});</script>
				
			

Show-Page-Title-WordPress-Menu

				
					function custom_page_title_shortcode() {
    return get_the_title();
}
add_shortcode('current_page_title', 'custom_page_title_shortcode');

function execute_shortcodes_in_menus($menu_item) {
    if (strpos($menu_item->title, '[') !== false && strpos($menu_item->title, ']') !== false) {
        $menu_item->title = do_shortcode($menu_item->title);
    }
    return $menu_item;
}
add_filter('wp_nav_menu_objects', 'execute_shortcodes_in_menus');
				
			

css-radio-variation

				
					/* Hide the select dropdowns for product variations */
.woocommerce div.product form.cart .variations select {
display: none;
}

selector label {
display: flex;
align-items: center;
margin-bottom: 5px; /* Adjust spacing between each option */
text-transform: capitalize; /* Converts text to uppercase */
}

selector input[type=radio] {
appearance: none;
margin-right: 10px; /* Space between circle and label text */
width: 20px; height: 20px;
border-radius: 50%; /* circle */
border: 2px solid #ccc;
outline: none;
align-self: center; /* Aligns the radio button vertically */
}

selector input[type=radio]:checked {
border-color: #FF0050;
background-color: #FF0050;
}

/* Background color adjustments for add-to-cart and variations */
selector .elementor-product-variable,
.woocommerce div.product form.cart .variations th,
.woocommerce div.product form.cart .variations td {
background-color: #ffffff; /* Set background to white */
}

/* Adjusting label margin in specific Elementor & WooCommerce contexts */
selector form.cart table.variations label {
margin-bottom: -20px; /* Adjust based on your layout needs */
}
				
			

CSS-Inline-Radio-Variation

				
					/* Hide the select dropdowns for product variations */
.woocommerce div.product form.cart .variations select {
display: none;
}

/* Container for radio buttons and labels */
.variation-changes-container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to next line as needed */
gap: 15px; /* Space between items */
}

/* Attribute Title alignemnt*/
.woocommerce div.product form.cart .variations th {
text-align: left;
align-items: center;
}

/* Style for labels */
.variation-changes-container label {
display: flex;
align-items: center;
margin-bottom: 0px; /* Adjust spacing between each option, if necessary */
text-transform: capitalize; /* Converts text to uppercase */
}

/* Style for radio buttons */
.variation-changes-container input[type=radio] {
appearance: none;
margin-right: 7px; /* Space between circle and label text */
width: 20px; height: 20px;
border-radius: 50%; /* Circle */
border: 2px solid #ccc;
outline: none;
}

/* Style for checked radio buttons */
.variation-changes-container input[type=radio]:checked {
border-color: #FF0050;
background-color: #FF0050;
}

/* Background color adjustments for add-to-cart and variations */
.variation-changes-container .elementor-product-variable,
.woocommerce div.product form.cart .variations th,
.woocommerce div.product form.cart .variations td {
background-color: #ffffff; /* Set background to white */
}
				
			

Add-Product-on-Cart-Page

				
					function cart_add() {
    $product_id = 380; // Set the product ID you want to add to the cart
    $add_to_cart_url = wc_get_cart_url() . '?add-to-cart=' . $product_id; // Construct the add-to-cart URL

    echo '<style>#cart-add a{display:block;width:100%;background-color:#222222;color:#FFFFFF;text-align:center;padding:10px 0;font-size:16px;font-weight:500;text-transform:uppercase;text-decoration:none;border:none;cursor:pointer;}#cart-add a:hover{background-color:#FF0050;}</style>';

    // Change the href attribute to the $add_to_cart_url
    echo '<div id="cart-add"><br><a href="' . esc_url( $add_to_cart_url ) . '">Add Product to Cart</a></div>';
}
add_action('woocommerce_after_cart_totals', 'cart_add', 10, 0);
				
			

Off-Canvas-Widget-Anchors

				
					<style>@keyframes slideInLeft{from{transform:translateX(-100%);}to{transform:translateX(0);}}@keyframes slideOutLeft{from{transform:translateX(0);}to{transform:translateX(-100%);}}.e-off-canvas-hidden{animation:slideOutLeft 1s forwards;}.e-off-canvas-visible{animation:slideInLeft 0.5s forwards;}.e-off-canvas-overlay-hidden{display:none !important;}</style>
<script type="text/phast">jQuery(function($){function hideOffCanvas(){$('[class^="e-off-canvas"]').removeClass('e-off-canvas-visible').addClass('e-off-canvas-hidden');$('.e-off-canvas__overlay').addClass('e-off-canvas-overlay-hidden');$('body').removeClass('e-off-canvas__no-scroll');}
function showOffCanvas(){$('[class^="e-off-canvas"]').removeClass('e-off-canvas-hidden').addClass('e-off-canvas-visible');$('.e-off-canvas__overlay').removeClass('e-off-canvas-overlay-hidden');$('body').addClass('e-off-canvas__no-scroll');}
$(document).on('click','[class^="e-off-canvas"] a',function(event){var target=$(this).attr("href");if(target.includes('elementor-action%3Aaction%3Doff_canvas%3Aclose')){event.preventDefault();hideOffCanvas();return;}
var split_url=target.split('#');if(split_url.length>1&&(window.location.pathname==split_url[0]||split_url[0]=='')){event.preventDefault();$('html, body').animate({scrollTop:$('#'+split_url[1]).offset().top},1000);hideOffCanvas();}else{hideOffCanvas();}});$(document).on('click','.off-canvas-toggle-button',function(event){showOffCanvas();});});</script>
				
			

Colour-Circle-Radio-Variation

				
					/* Hide the select dropdowns for product variations */
.woocommerce div.product form.cart .variations select {
display: none;
}

/* Container for radio buttons and labels */
.variation-changes-container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to next line as needed */
gap: 15px; /* Space between items */
}

/* Attribute Title alignment */
.woocommerce div.product form.cart .variations th {
text-align: left;
align-items: center;
}

/* Style for labels, indicating option colors */
.variation-changes-container label {
display: flex;
align-items: center;
margin-bottom: 0px; /* Adjust spacing between each option, if necessary */
text-transform: capitalize; /* Converts text to uppercase */
cursor: pointer;
}

/* Style for radio buttons */
.variation-changes-container input[type=radio] {
appearance: none;
margin-right: 7px; /* Space between circle and label text */
width: 20px; height: 20px;
border-radius: 50%; /* Circle */
border: 2px solid #CCC; /* Light grey border by default */
outline: none;
background-color: #FFF; /* Default background for unspecified options */
}

/* Style for checked radio buttons */
.variation-changes-container input[type=radio]:checked {
border-color: #000; /* Border color when selected */
background-color: #000;
}

/* Applying specific background colors for checked states */
.variation-changes-container label.red input[type=radio] {
background-color: #FF0050; /* Red background color when selected */
border: 0px solid #FF0050;
}

.variation-changes-container label.red input[type=radio]:checked {
background-color: #FF0050; /* Red background color when selected */
border: 4px solid #000;
}

.variation-changes-container label.blue input[type=radio] {
background-color: #0000FF; /* Red background color when selected */
border: 0px solid #0000FF;
}

.variation-changes-container label.blue input[type=radio]:checked {
background-color: #0000FF; /* Blue background color when selected */
border: 4px solid #000;
}

/* Background color adjustments for add-to-cart and variations */
.variation-changes-container .elementor-product-variable,
.woocommerce div.product form.cart .variations th,
.woocommerce div.product form.cart .variations td {
background-color: #ffffff; /* Set background to white */
}
				
			

Woocommerce-Single-Product-Variation-Radio

				
					add_filter('woocommerce_dropdown_variation_attribute_options_html', 'variation_changes', 20, 2);
function variation_changes($html, $args) {
    if (empty($args['options']) || !$args['product']) {
        return $html; // Return original HTML if no options or product is provided
    }

    $name = !empty($args['name']) ? $args['name'] : 'attribute_' . sanitize_title($args['attribute']);

    // Start the radio button markup
    $radios = '<div class="variation-changes-container">';

    // Loop through each option
    foreach ($args['options'] as $option) {
        // Generate a class name based on the option for specific styling
        $class = sanitize_title($option); // Creates a valid HTML class from the option value

        // Determine if the option is selected
        $checked = checked($args['product']->get_variation_default_attribute($args['attribute']), $option, false);

        // Create the radio button with a class for the label based on the option
        $radios .= sprintf('<label class="%1$s"><input type="radio" name="%2$s" value="%3$s" %4$s class="%1$s"> %5$s</label><br>',
            esc_attr($class),
            esc_attr($name),
            esc_attr($option),
            $checked,
            esc_html(apply_filters('woocommerce_variation_option_name', $option))
        );
    }

    $radios .= '</div>'; // End the radio button markup

    return $html . $radios;
}
				
			

search-full-screen

				
					<style>.fullscreen-search{position:fixed;top:0;left:0;width:100vw;height:100vh;background:#000000D9;display:flex;flex-direction:row;align-items:center;justify-content:center;opacity:0;visibility:hidden;transition:opacity 0.3s ease-in-out,visibility 0.3s ease-in-out;z-index:9999;}.fullscreen-search .elementor-widget-container{display:flex;justify-content:center;align-items:center;flex:0 1 auto;}.fullscreen-search .elementor-search-form{display:flex;align-items:center;flex-wrap:nowrap;}.fullscreen-search .elementor-search-form input{padding:15px;font-size:18px;border:none;outline:none;}.fullscreen-search .elementor-search-form button[type="submit"]{padding:15px;font-size:18px;background:none;border:none;cursor:pointer;}.fullscreen-search .close-search{font-size:18px;color:white;cursor:pointer;background:none;border:none;display:flex;align-items:center;margin-left:10px;}@media (max-width:720px){.fullscreen-search .elementor-search-form{flex-wrap:wrap;width:90%;max-width:100%;justify-content:center;}.fullscreen-search .elementor-search-form input{flex:1 0 100%;margin-bottom:10px;}.fullscreen-search .elementor-search-form button[type="submit"]{margin-right:10px;}.fullscreen-search .close-search{margin-left:0;}.fullscreen-search{align-content:center;}}</style>

<script type="text/phast">document.addEventListener("DOMContentLoaded",function(){console.log("JavaScript running");let searchToggle=document.querySelector(".search-toggle");let searchBox=document.querySelector(".fullscreen-search");console.log("Toggle:",searchToggle);console.log("Search Box:",searchBox);if(!searchToggle){console.error("Toggle not found. Add class 'search-toggle' to a button/icon.");return;}
if(!searchBox){console.error("Search box not found. Add class 'fullscreen-search' to Search Form widget.");return;}
let closeBtn=document.createElement("button");closeBtn.className="close-search";closeBtn.innerHTML="X";closeBtn.setAttribute("aria-label","Close search");searchBox.appendChild(closeBtn);searchToggle.addEventListener("click",function(){console.log("Toggle clicked - opening");searchBox.style.opacity="1";searchBox.style.visibility="visible";});closeBtn.addEventListener("click",function(){console.log("Close clicked - hiding");searchBox.style.opacity="0";searchBox.style.visibility="hidden";});});</script>
				
			

Calculated-Many-Selects-PayPal

				
					<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){const optionsQuantityField=document.getElementById('form-field-quantity_options');const servicesQuantityField=document.getElementById('form-field-quantity_services');const optionsPriceField=document.getElementById('form-field-price_options');const servicesPriceField=document.getElementById('form-field-price_services');const totalField=document.getElementById('form-field-total');const optionsField=document.getElementById('form-field-options');const servicesField=document.getElementById('form-field-services');const paypalAmountInput=document.getElementById('paypal-amount');const paypalItemNameInput=document.getElementById('paypal-item-name');const form=document.getElementById('paypal-form');function getPrice(option){switch(option){case'Option A - $1':return 1;case'Option B - $1':return 1;case'Option C - $1':return 1;default:return 0;}}
function getServicePrice(service){switch(service){case'Service 1 - $1':return 1;case'Service 2 - $1':return 1;case'Service 3 - $1':return 1;default:return 0;}}
function updatePrices(){const selectedOption=optionsField.value;const selectedService=servicesField.value;const optionPrice=getPrice(selectedOption);const servicePrice=getServicePrice(selectedService);const optionsQuantity=parseFloat(optionsQuantityField.value)||0;const servicesQuantity=parseFloat(servicesQuantityField.value)||0;const optionsTotalPrice=optionsQuantity*optionPrice;const servicesTotalPrice=servicesQuantity*servicePrice;optionsPriceField.value=`$${optionsTotalPrice.toFixed(2)}`;servicesPriceField.value=`$${servicesTotalPrice.toFixed(2)}`;return{selectedOption,optionsQuantity,selectedService,servicesQuantity,optionsTotalPrice,servicesTotalPrice};}
function calculateTotal(){const{selectedOption,optionsQuantity,selectedService,servicesQuantity,optionsTotalPrice,servicesTotalPrice}=updatePrices();const total=optionsTotalPrice+servicesTotalPrice;totalField.value=`$${total.toFixed(2)}`;paypalAmountInput.value=total.toFixed(2);paypalItemNameInput.value=`Options: ${optionsQuantity} x ${selectedOption}, Services: ${servicesQuantity} x ${selectedService}`;}
calculateTotal();optionsQuantityField.addEventListener('input',calculateTotal);servicesQuantityField.addEventListener('input',calculateTotal);optionsField.addEventListener('change',calculateTotal);servicesField.addEventListener('change',calculateTotal);form.addEventListener('keypress',function(event){if(event.key==='Enter'){event.preventDefault();}});});</script>
				
			

apple-dock

				
					<script type="text/phast">document.addEventListener("DOMContentLoaded",()=>{const icons=document.querySelectorAll(".dock-icon");const container=document.querySelector(".dock-container");let resetTimeout;function applyHover(index){clearTimeout(resetTimeout);icons.forEach((icon,i)=>{icon.classList.remove("level-0","level-1","level-2");if(i===index){icon.classList.add("level-0");}else if(i===index-1||i===index+1){icon.classList.add("level-1");}else if(i===index-2||i===index+2){icon.classList.add("level-2");}});}
function resetDock(){icons.forEach(icon=>{icon.classList.remove("level-0","level-1","level-2");});}
icons.forEach((icon,i)=>{icon.addEventListener("mouseenter",()=>{applyHover(i);});icon.addEventListener("mouseleave",()=>{resetTimeout=setTimeout(resetDock,100);});});container.addEventListener("mouseleave",()=>{resetTimeout=setTimeout(resetDock,100);});container.addEventListener("mouseenter",()=>{clearTimeout(resetTimeout);});});</script>
				
			

text-reveal-swap

				
					
<h2 id="fixed-heading" class="locked-fixed"></h2>

<style>.locked-fixed{position:fixed;display:flex;justify-content:center;width:90%;top:50%;left:50%;transform:translate(-50%,-50%);font-family:'Merriweather',sans-serif;font-size:clamp(1.80rem,0.66207rem + 4.85517vw,4.00rem);font-weight:900;color:#FFFFFF;z-index:10;opacity:0;transition:opacity 0.3s ease;pointer-events:none;text-align:center;}.section-heading{visibility:hidden;height:0;margin:0;padding:0;}.section-cta{position:fixed;display:flex;justify-content:center;width:90%;bottom:35%;left:50%;transform:translateX(-50%) translateY(30px);opacity:0;transition:opacity 0.25s ease-in,transform 0.25s ease-in;pointer-events:none;z-index:9;}.section-cta.cta-visible{opacity:1;transform:translateX(-50%) translateY(0);pointer-events:auto;}</style>



<script type="text/phast">document.addEventListener("DOMContentLoaded",function(){const fixedHeading=document.getElementById("fixed-heading");const sections=document.querySelectorAll(".scroll-section");const observer=new IntersectionObserver((entries)=>{entries.forEach(entry=>{if(entry.isIntersecting){const heading=entry.target.querySelector(".section-heading");if(heading){fixedHeading.textContent=heading.textContent;fixedHeading.style.opacity=1;}
const cta=entry.target.querySelector(".section-cta");if(cta){cta.classList.add("cta-visible");}}else{const cta=entry.target.querySelector(".section-cta");if(cta){cta.classList.remove("cta-visible");}}});},{threshold:0.5});sections.forEach(section=>observer.observe(section));});</script>
				
			

text-rotate

				
					<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.css" />


<div class="swiper looping-words">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Get noticed fast</div>
    <div class="swiper-slide">Win more leads</div>
    <div class="swiper-slide">Sell with ease</div>
    <div class="swiper-slide">Build real trust</div>
    <div class="swiper-slide">Grow every day</div>
  </div>
</div>


<script type="text/phast" src="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.js"></script>
<script type="text/phast">document.addEventListener("DOMContentLoaded",()=>{const swiper=new Swiper('.swiper',{direction:'vertical',loop:true,slidesPerView:3,centeredSlides:true,autoplay:{delay:1000,disableOnInteraction:false,},});setTimeout(()=>{swiper.update();swiper.autoplay.start();},100);});</script>


<style>:root{--slide-height:clamp(3.30rem,2.16207rem + 4.85517vw,5.50rem);--font-size:clamp(1.80rem,0.66207rem + 4.85517vw,4.00rem);--font-family:'Merriweather',serif;--font-weight:900;--highlight-color:#FFFFFF;--default-color:#FFFFFF5B;--slides-visible:3;--carousel-width:95%;--autoplay-delay:1000ms;}html{font-size:16px;}body{background:black;margin:0;padding:0;}.looping-words{height:calc(var(--slides-visible) * var(--slide-height));max-width:var(--carousel-width);margin:auto;font-family:var(--font-family);font-size:var(--font-size);font-weight:var(--font-weight);}.swiper-wrapper{align-items:center;}.swiper-slide{height:var(--slide-height) !important;display:flex;justify-content:center;align-items:center;color:var(--default-color);transition:opacity 0.4s ease,color 0.4s ease;line-height:1.1;white-space:nowrap;padding:0 20px;}.swiper-slide.swiper-slide-active{opacity:1;color:var(--highlight-color);}</style>
				
			

proportion-image-grow

				
					<script type="text/phast">document.addEventListener("DOMContentLoaded",function(){if(window.innerWidth<=768)return;const containers=document.querySelectorAll(".growimage");containers.forEach(container=>{const img=container.querySelector("img");if(img){img.setAttribute("loading","eager");}});let imagesLoaded=0;containers.forEach(container=>{const img=container.querySelector("img");function setHoverWidth(){const naturalWidth=img.naturalWidth;const naturalHeight=img.naturalHeight;const fixedHeight=container.clientHeight;const ratioWidth=(naturalWidth/naturalHeight)*fixedHeight;container.dataset.hoverWidth=ratioWidth.toFixed(2);}
function handleImageLoad(){setHoverWidth();imagesLoaded++;if(imagesLoaded===containers.length){setupHoverEvents();}}
if(img.complete&&img.naturalWidth){handleImageLoad();}else{img.addEventListener("load",handleImageLoad);}});function setupHoverEvents(){containers.forEach(container=>{container.addEventListener("mouseenter",()=>{const targetWidth=container.dataset.hoverWidth;if(targetWidth){container.style.width=`${targetWidth}px`;}});container.addEventListener("mouseleave",()=>{container.style.width=`100px`;});});}});</script>
				
			

animated-border-css

				
					.box {
  border: 10px solid transparent;
   border-radius: 15px; 
  background: 
    linear-gradient(#fff, #fff) padding-box, 
    conic-gradient(
      from var(--angle),
      transparent 70%,     
      #ffa500 80%,    
      #ff4500 90%,   
      #ff0050 100%    
    ) border-box;
  animation: rotate 12s linear infinite;
  /*animation-delay: 1s;*/
}

@keyframes rotate {
  to { --angle: 360deg; }
}

@property --angle {
  syntax: "<angle>";
  initial-value: 0deg;
  inherits: false;
}
				
			

author-dynamic-acf

				
					function ws_get_author_term_id_for_post($post_id = null) {
  $post_id = $post_id ?: get_the_ID();
  if (!$post_id) return 0;

  // Add the field used for selecting the taxonomy
  $val = get_field('author_details', $post_id);
  if (is_numeric($val)) return (int) $val;

  // Soft fallbacks if Return Value wasn't set to ID
  if (is_object($val) && !empty($val->term_id)) return (int) $val->term_id;
  if (is_array($val) && isset($val['term_id'])) return (int) $val['term_id'];

  // Last resort: first assigned term in the taxonomy on this post
  $terms = wp_get_post_terms($post_id, 'author_taxonomy');
  if (!is_wp_error($terms) && !empty($terms[0]->term_id)) return (int) $terms[0]->term_id;

  return 0;
}

/** [author_term_name] — the taxonomy title. */
add_shortcode('author_term_name', function () {
  $term_id = ws_get_author_term_id_for_post();
  if (!$term_id) return '';
  $term = get_term($term_id, 'author_taxonomy');
  return ($term && !is_wp_error($term)) ? esc_html($term->name) : '';
});

/** [author_title] — ACF term field "author_title". */
add_shortcode('author_title', function () {
  $term_id = ws_get_author_term_id_for_post();
  if (!$term_id) return '';
  $title = get_field('author_title', 'term_' . $term_id);
  return $title ? esc_html($title) : '';
});

/** [author_bio] — ACF term field "author_bio" (plain text). */
add_shortcode('author_bio', function () {
  $term_id = ws_get_author_term_id_for_post();
  if (!$term_id) return '';
  $bio = get_field('author_bio', 'term_' . $term_id);
  return $bio ? esc_html($bio) : '';
});

/** [author_bio2] — ACF term field "author_bio2" (WYSIWYG → allow HTML). */
add_shortcode('author_bio2', function () {
  $term_id = ws_get_author_term_id_for_post();
  if (!$term_id) return '';
  $bio2 = get_field('author_bio2', 'term_' . $term_id);
  if (!$bio2) return '';
  // Keep author-entered formatting; sanitize through wp_kses_post
  return wp_kses_post($bio2);
});

/** [author_link] — ACF term field "author_link" (prints the URL). */
add_shortcode('author_link', function () {
  $term_id = ws_get_author_term_id_for_post();
  if (!$term_id) return '';
  $url = get_field('author_link', 'term_' . $term_id);
  return $url ? esc_url($url) : '';
});

/** [author_image] — ACF term field "author_image" (prints an <img>). */
add_shortcode('author_image', function () {
  $term_id = ws_get_author_term_id_for_post();
  if (!$term_id) return '';
  $img = get_field('author_image', 'term_' . $term_id); // image array expected
  if (!empty($img['ID'])) {
    $term  = get_term($term_id, 'author_taxonomy');
    $alt   = get_field('author_title', 'term_' . $term_id) ?: ($term && !is_wp_error($term) ? $term->name : '');
    return wp_get_attachment_image((int) $img['ID'], 'medium', false, ['alt' => esc_attr($alt)]);
  }
  return '';
});
				
			

aeo-ai-visibility-booster

				
					
/**
 * AEO AI Visibility Booster - from Imran Siddiq - https://learn.websquadron.co.uk
 */

if ( ! defined('ABSPATH') ) exit;

class AIV_Clarity_Ultra {
    const OPTION = 'aiv_ultra_settings';
    const NONCE  = 'aiv_ultra_nonce';

public function __construct() {
    // 1) Disable WordPress core sitemaps entirely (/wp-sitemap.xml and friends)
    add_filter('wp_sitemaps_enabled', '__return_false');

    // 2) Kill canonical redirects for our virtual endpoints so WP (or plugins)
    //    won’t bounce /sitemap.xml or /llms.txt anywhere else.
    add_filter('redirect_canonical', [$this, 'bypass_canonical_for_virtual'], 0, 2);

    // (Extra belt & braces) If the core redirect helper is present, remove it.
    add_action('init', function () {
        if (function_exists('wp_sitemaps_redirect')) {
            remove_action('template_redirect', 'wp_sitemaps_redirect');
        }
    }, 9);

    add_action('admin_menu',        [$this, 'menu']);
    add_action('admin_init',        [$this, 'maybe_save']);

    // 3) Serve virtual files at the earliest possible moment on template_redirect.
    add_action('template_redirect', [$this, 'serve_virtual_files'], 0);

    add_filter('robots_txt',        [$this, 'extend_robots_txt'], 99, 2);
    add_action('wp_head',           [$this, 'maybe_output_faq_schema'], 1);
	add_action('wp_head', [$this, 'maybe_output_org_schema'], 2);
}

    /* ---------------- Defaults & Settings ---------------- */

    private function defaults() {
        return [
            // Business basics
            'business_name' => '',
            'phone'         => '',
            'logo_url'      => '',
            'locality'      => '',
            'country'       => '',
            'area_served'   => 'Global',
			'entity_type'   => 'Organization', // or 'LocalBusiness'

            // Key page paths (used in llms.txt) — “Updates” renamed to “Blog”
            'path_services' => '/services',
            'path_pricing'  => '/pricing',
            'path_faq'      => '/faq',
            'path_contact'  => '/contact',
            'path_blog'     => '/blog',    // rename from updates → blog

            // Per-path descriptions (appear in llms.txt)
            'desc_services' => 'Our main services.',
            'desc_pricing'  => 'Pricing & packages.',
            'desc_faq'      => 'Common questions & answers.',
            'desc_contact'  => 'How to reach us.',
            'desc_blog'     => 'Recent updates & wins.',

            // Extra LLMS lines (path or full URL + 2+ spaces + description)
            'extra_llms'    => "",

            // Sitemaps
			'post_types'        => [],          // post types to include if we serve a sitemap
			'sitemap_max_items' => 'all',       // per type: number or "all"
			'extra_urls'        => '',          // one per line (absolute or relative)
			'exclude_urls'      => '',          // one per line (absolute or relative; supports trailing * for prefix)
			'existing_sitemap'  => '',          // URL from SEO plugin (Yoast/RankMath/etc.)

            // Virtual serving toggles
            'serve_llms'    => '1',             // /llms.txt
            'serve_sitemap' => '1',             // /sitemap.xml
            'extend_robots' => '1',             // append guidance to virtual robots

            // FAQ – Manual Q&A
            'faq_text'      => "Q: Do you offer free quotes?\nA: Yes, we reply within 24 hours.\n\nQ: Do you work evenings/weekends?\nA: We can arrange this by request.\n",
            'faq_page_ids'  => '',              // inject manual JSON-LD on these page IDs

            // FAQ – Auto from page content
            'faq_auto_enable'    => '0',        // read on-page FAQ and build schema
            'faq_mode'           => 'preset_elementor', // elementor, gutenberg, simple, custom
            'faq_container_class'=> 'aiv-faq',  // class on the FAQ section (no dot)
            'faq_q_selector'     => 'h3',       // for simple/custom
            'faq_a_selector'     => 'next',     // 'next' = next paragraph after the question (for simple/custom)
            'faq_auto_pages_ids' => '',         // limit auto injection (blank = any page containing the class)
        ];
    }

    private function get_settings() {
        $saved = get_option(self::OPTION, []);
        $defs  = $this->defaults();

        // Back-compat: if an older option used path_updates, map it to blog
        if (!empty($saved['path_updates']) && empty($saved['path_blog'])) {
            $saved['path_blog'] = $saved['path_updates'];
        }
        if (!isset($saved['post_types']) || !is_array($saved['post_types'])) $saved['post_types'] = [];

        return wp_parse_args($saved, $defs);
    }

    private function sanitize($in) {
        $out = [];
$txt = [
  // basics
  'business_name','phone','logo_url','locality','country','area_served','entity_type',
  // key paths
  'path_services','path_pricing','path_faq','path_contact','path_blog',
  // per-path descriptions
  'desc_services','desc_pricing','desc_faq','desc_contact','desc_blog',
  // extras
  'extra_llms','extra_urls','exclude_urls','existing_sitemap','faq_text','faq_page_ids',
  // faq auto
  'faq_container_class','faq_q_selector','faq_a_selector','faq_auto_pages_ids',
  'sitemap_max_items','faq_mode'
];
        foreach ($txt as $k) {
            if (!isset($in[$k])) { $out[$k] = ''; continue; }
            if (in_array($k, ['extra_urls','exclude_urls','faq_text','extra_llms'], true)) {
                $out[$k] = trim(str_replace("\r", '', $in[$k]));
            } elseif (in_array($k, ['logo_url', 'existing_sitemap'], true)) {
                $out[$k] = esc_url_raw($in[$k]);
            } else {
                $out[$k] = sanitize_text_field($in[$k]);
            }
        }
		$allowed_types = ['Organization','LocalBusiness'];
$out['entity_type'] = in_array(($in['entity_type'] ?? 'Organization'), $allowed_types, true)
    ? $in['entity_type']
    : 'Organization';
		
        $out['post_types'] = isset($in['post_types']) && is_array($in['post_types'])
            ? array_values(array_unique(array_map('sanitize_key',$in['post_types']))) : [];

        foreach (['serve_llms','serve_sitemap','extend_robots','faq_auto_enable'] as $k) {
            $out[$k] = !empty($in[$k]) ? '1' : '0';
        }

        $out['faq_container_class'] = ltrim($out['faq_container_class'], '. ');
        return $out;
    }

    /* ---------------- Admin UI ---------------- */

    public function menu() {
        add_management_page(
            'AI Visibility',
            'AI Visibility',
            'manage_options',
            'aiv-ultra',
            [$this, 'render']
        );
    }

    private function seo_plugin_notes() {
        $notes = [];
        if (defined('WPSEO_VERSION'))     $notes[] = 'Yoast SEO detected';
        if (defined('RANK_MATH_VERSION')) $notes[] = 'RankMath detected';
        if (defined('SLIM_SEO_VERSION'))  $notes[] = 'Slim SEO detected';
        return $notes;
    }

    public function maybe_save() {
        if (!current_user_can('manage_options')) return;
        if (empty($_POST[self::NONCE]) || !wp_verify_nonce($_POST[self::NONCE], self::NONCE)) return;
        if (!isset($_POST['aiv_save'])) return;
        update_option(self::OPTION, $this->sanitize($_POST));
        add_action('admin_notices', function(){
            echo '<div class="notice notice-success is-dismissible"><p><strong>AI Visibility:</strong> Settings saved.</p></div>';
        });
    }

    public function render() {
        if (!current_user_can('manage_options')) return;

        $s        = $this->get_settings();
        $home     = rtrim(site_url(), '/');
        $robots   = $this->generate_robots_txt($s, $home);
        $llms     = $this->generate_llms_txt($s, $home);
        $__groups = $this->gather_urls_by_type($s, $home);
		$sitemap  = $this->generate_sitemap_index_xml_from_groups($__groups, $home);
        $faq_prev = $this->generate_faq_jsonld_preview($s); // preview of MANUAL pairs

        $all_pts  = get_post_types(['public' => true], 'objects');
        unset($all_pts['attachment']);

        $physical_robots_exists = file_exists(ABSPATH.'robots.txt');
        $seo_notes = $this->seo_plugin_notes();

        // Inline CSS: white panel, blue headers, 40px section spacing, 1.3em line-height, accordion styling
        ?>
        <style>.aiv-helper{background:#eef6ff;border:1px solid #e6e6e6;padding:10px 12px;border-radius:0px;margin-top:10px;}.aiv-helper code{background:#eef6ff;}.aiv-helper pre{background:#fff;border:1px solid #e6e6e6;padding:10px;overflow:auto;margin:8px 0 0 0;}.aiv-wrap{background:#fff;padding:22px 24px;border:1px solid #e6e6e6;border-radius:0px;}.aiv-wrap *{line-height:1.3em;}.aiv-wrap h1,.aiv-wrap h2,.aiv-wrap h3{color:#0a66cc;}.aiv-wrap h2{margin-top:10px;}.aiv-wrap h3{margin-top:26px;}.aiv-wrap .description{color:#333;}.aiv-quicklinks{margin:10px 0 18px;padding:10px 12px;background:#f6fbff;border:1px solid #d8ecff;border-radius:0px;}.aiv-decision{padding:10px 14px;margin-top:0px;margin-bottom:18px;background:#f8faff;border:1px solid #e4eaff;border-radius:0px;}.aiv-note{font-size:12px;color:#444;}.aiv-wrap{font-size:13px;}.aiv-wrap h1{font-size:21px;}.aiv-wrap h2{font-size:17px;}.aiv-wrap h3{font-size:15px;}.aiv-wrap .description,.aiv-note{font-size:13px;}.aiv-acc{margin:0;border:1px solid #e6e6e6;border-radius:0;background:#fff;}.aiv-acc + .aiv-acc{border-top:0;}.aiv-acc:first-of-type{border-top-left-radius:0px;border-top-right-radius:0px;}.aiv-acc:last-of-type{border-bottom-left-radius:0px;border-bottom-right-radius:0px;}.aiv-acc > summary{cursor:pointer;list-style:none;padding:12px 14px 12px 34px;margin:0;font-weight:600;color:#0a66cc;position:relative;background:#eef6ff;}.aiv-acc > summary::-webkit-details-marker{display:none;}.aiv-acc > summary::before{content:"▸";position:absolute;left:12px;top:50%;transform:translateY(-50%);font-size:14px;line-height:1;color:#0a66cc;}.aiv-acc[open] > summary::before{content:"▾";}.aiv-acc[open] > summary{background:#e3f0ff;border-bottom:1px solid #e6e6e6;}.aiv-acc .aiv-acc-body{padding:14px;background:#fff;}.aiv-acc .form-table th{width:220px;}.aiv-acc .form-table td .description{margin-top:6px;display:block;}.aiv-acc .desc-list{margin:6px 0 10px 18px;}.aiv-acc code{background:transparent}.aiv-acc summary:focus{outline:2px solid transparent;outline-offset:2px;border-radius:0px;}.aiv-path-row{display:flex;align-items:center;gap:10px;}.aiv-path-row input.path-input{width:180px;}.aiv-path-row input.desc-input{flex:1;min-width:400px;}.aiv-wrap .donate-btn{background:#f4f4f4;color:#000;border:1px solid #d0d0ce;text-decoration:none;padding:0 12px;transition:background-color .12s ease,border-color .12s ease;}.aiv-wrap .donate-btn:hover,.aiv-wrap .donate-btn:focus{background:#e9e9e7;border-color:#c6c6c3;color:#000;text-decoration:none;}</style>

        <div class="wrap aiv-wrap">
            <h1>AEO AI-Visibility Booster</h1>

<div class="aiv-quicklinks">
    <strong>Quick test links:</strong>
    <a href="<?php echo esc_url($home.'/robots.txt'); ?>" target="_blank" rel="noopener">robots.txt</a> •
    <a href="<?php echo esc_url($home.'/sitemap.xml'); ?>" target="_blank" rel="noopener">sitemap.xml</a> •
    <a href="<?php echo esc_url($home.'/llms.txt'); ?>" target="_blank" rel="noopener">llms.txt</a>
    <?php
    // Also show per-type sitemap links (e.g., page-sitemap.xml, post-sitemap.xml)
    if ($s['serve_sitemap'] === '1' && !empty($__groups) && is_array($__groups)) {
        $links = [];
        foreach ($__groups as $type => $items) {
            $slug = sanitize_key($type);
            $links[] = '<a href="' . esc_url(trailingslashit($home) . $slug . '-sitemap.xml') . '" target="_blank" rel="noopener">'
                     . esc_html($slug . '-sitemap.xml') . '</a>';
        }
        if (!empty($links)) {
            echo ' • ' . implode(' • ', $links);
        }
    }
    ?>
</div>
	
           <?php if (!empty($seo_notes)): ?>
                <div class="notice notice-info"><p><strong>Heads-up:</strong> <?php echo esc_html(implode(' / ', $seo_notes)); ?>. We’ll explain what to do if your SEO plugin also creates a robots.txt or sitemap.</p></div>
            <?php endif; ?>

            
<?php if (false): ?>
<div class="aiv-decision">
    <p style="margin:.4em 0;"><strong>Decision Helper (what to pick):</strong></p>
    <ul style="margin:.2em 0 .6em 1.2em;">
        <li><strong>Sitemap:</strong> If your SEO plugin gives you a sitemap URL, paste it below and <em>UNcheck</em> “Serve /sitemap.xml”. If you don’t have one, <em>keep it checked</em> so we provide it.</li>
        <li><strong>robots.txt:</strong> SEO plugins usually output <em>virtual</em> robots.txt and not a physical file in your site. If you leave “Extend robots.txt” <em>checked</em>, it will add AI tool lines and will ensure no duplicate lines occur.</li>
        <li><strong>FAQ Schema:</strong> You can use <em>Manual</em> (paste Q&A here) and/or <em>Auto</em> (we read your on-page FAQ accordion). If both are present on the same page, they’ll combine. Try not to duplicate the same questions.</li>
    </ul>
</div>
<?php endif; ?>

            <form method="post">
                <?php wp_nonce_field(self::NONCE, self::NONCE); ?>

                
                <details class="aiv-acc" open>
                    <summary>1) Site Basics <em>(recommended)</em></summary>
                    <div class="aiv-acc-body">
                        <ul class="description" style="max-width:880px;">
                            <li><strong>What:</strong> Your business details (who/where).</li>
                            <li><strong>Why:</strong> Used in helper files so crawlers connect your brand to your pages.</li>
                            <li><strong>How:</strong> Fill once; you can edit anytime.</li>
                        </ul>
                        <table class="form-table">
                            <tr><th>Business Name</th><td><input class="regular-text" name="business_name" value="<?php echo esc_attr($s['business_name']); ?>"></td></tr>
						<tr>
  <th>Entity Type</th>
  <td>
    <select name="entity_type">
      <option value="Organization"  <?php selected($s['entity_type'],'Organization');  ?>>Organization (default)</option>
      <option value="LocalBusiness" <?php selected($s['entity_type'],'LocalBusiness'); ?>>Local Business</option>
    </select>
    <p class="description">
      Choose <strong>Local Business</strong> if you serve a specific locality (shop, clinic, trades, agency, etc.).  
      Otherwise use <strong>Organization</strong>.
    </p>
  </td>
</tr>
                            <tr><th>Phone</th><td><input class="regular-text" name="phone" value="<?php echo esc_attr($s['phone']); ?>"></td></tr>
                            <tr><th>Logo URL</th><td><input class="regular-text" name="logo_url" value="<?php echo esc_attr($s['logo_url']); ?>" placeholder="https://example.com/logo.png"></td></tr>
                            <tr><th>Town/City</th><td><input class="regular-text" name="locality" value="<?php echo esc_attr($s['locality']); ?>"></td></tr>
                            <tr><th>Country</th><td><input class="regular-text" name="country" value="<?php echo esc_attr($s['country']); ?>"></td></tr>
                            <tr><th>Area Served</th><td><input class="regular-text" name="area_served" value="<?php echo esc_attr($s['area_served']); ?>" placeholder="Global or City/Region"></td></tr>
                        </table>
                    </div>
                </details>


<details class="aiv-acc" open>
    <summary>2) LLMS.txt for AI Tools <em>(recommended)</em></summary>
    <div class="aiv-acc-body">
        <ul class="description" style="max-width:880px;">
            <li><strong>What:</strong> Your “answer” pages, key resources, and brand context.</li>
            <li><strong>Why:</strong> Listed in <code>/llms.txt</code> so AI crawlers can understand your expertise and link directly to the most helpful content.</li>
        </ul>

        <h3 style="margin-top:20px;">LLMS items</h3>
        <p class="description" style="max-width:880px;">
            Paste or edit your structured list below. Use natural sentences and organized sections like “Core Pages,” “Tools,” “Courses,” and “Reviews.”  
            You can include headings (starting with <code>#</code> or <code>##</code>) and any mix of full URLs or relative paths.
        </p>

<textarea 
  name="extra_llms" 
  rows="6" 
  style="width:100%;max-width:900px;min-height:240px;height:auto;resize:vertical;line-height:1.5em;font-family:monospace;"><?php echo esc_textarea($s['extra_llms']); ?></textarea>

        <div class="aiv-helper" style="margin-top:10px;">
            <strong>Example (Web Squadron)</strong>
<pre><code># Web Squadron

Web Squadron empowers web designers, freelancers, and agencies to build faster, smarter, and more profitable websites using WordPress, Elementor, and modern web tools.  
Founded by Imran Siddiq, Web Squadron provides practical training, tools, and business strategies that help designers stay relevant in an AI-driven world.

## Core Pages

/home   Our main landing page introducing the benefits of working with Imran Siddiq, including courses, services, and community links.
/services   Our main services, including web design, optimization, business consulting, video collaboration, and 1-to-1 coaching with Imran Siddiq.
/pricing   Pricing and package details for courses, consultations, and client projects.
/faq   Common questions and answers about our services, courses, and training approach.
/contact   How to reach us for support, collaboration, or consultancy.
/blog   Tutorials, insights, and case studies on WordPress, web design, and digital business growth.
/codes   A list of code snippets (HTML, JS, and CSS) for enhancing website functionality and Elementor builds.

## Courses & Learning

/product/the-elementor-website-course/   The Elementor Mastery Course – build beautiful, fast, and scalable WordPress sites from scratch.
/product/the-css-course/   Modern CSS for Web Designers – learn practical CSS for Elementor and WordPress customization.

## Reviews & Case Studies

/reviews   Client testimonials and social proof from businesses we have helped.
/reviews#client1   Client testimonial – 60% faster load times after our performance optimization.
/reviews#client2   Case study – boosting conversions with custom WordPress builds.
/reviews#client3   Client feedback – improved SEO rankings and usability after redesign.
/case-studies   Library of in-depth success stories and before/after project breakdowns.

## Community & Media

https://www.meetup.com/the-elementor-and-wordpress-leicester-group   Elementor & WordPress Leicester Group – local face-to-face events for designers and developers, hosted by Web Squadron.
https://www.youtube.com/@websquadron   Web Squadron YouTube Channel – weekly tutorials, strategy videos, and training for WordPress and Elementor professionals.
https://www.facebook.com/groups/websquadron   Facebook Group for web designers – a supportive space to engage, learn, and problem-solve together.

## Entity Attribution

Imran Siddiq – Founder and Creator of Web Squadron.  
Official Channels: https://learn.websquadron.co.uk | https://youtube.com/@websquadron | https://facebook.com/groups/websquadron  
Focus Topics: WordPress, Elementor, AI in Web Design, Freelancing, and Productivity.
</code></pre>
        </div>
    </div>
</details>

                
                <details class="aiv-acc" open>
                    <summary>3) Sitemap Options <em>(recommended)</em></summary>
                    <div class="aiv-acc-body">
                        <ul class="description" style="max-width:880px;">
                            <li><strong>What:</strong> A list of URLs with last modified date (helps tools to see current information).</li>
                            <li><strong>Why:</strong> Google/Bing (and AI that use them) rely on sitemaps to discover your pages.</li>
                            <li><strong>How:</strong> Choose which content types to include (Pages, Posts, Products, Custom). Set how many per type "all" or a number).</li>
                            <li><strong>Pick this if:</strong> You don’t have an SEO plugin sitemap. If you do have one, paste it below and uncheck the “Serve /sitemap.xml” in Section 4).</li>
                        </ul>
                        <table class="form-table">
                            <tr>
                                <th>Include Post Types</th>
                                <td>
                                    <?php foreach ($all_pts as $slug => $obj): ?>
                                        <label style="display:inline-block;margin-right:16px;">
                                            <input type="checkbox" name="post_types[]" value="<?php echo esc_attr($slug); ?>" <?php checked(in_array($slug, $s['post_types'], true)); ?>>
                                            <?php echo esc_html($obj->labels->name . " ($slug)"); ?>
                                        </label>
                                    <?php endforeach; ?>
                                    <p class="description">
                                        <strong>Check</strong> to include (e.g., <strong>page</strong>, <strong>post</strong>, <strong>product</strong>).  
                                        <strong>Uncheck</strong> to exclude (useful if you don’t want blog posts in your sitemap).
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th>Max items per type</th>
                                <td>
                                    <input class="small-text" name="sitemap_max_items" value="<?php echo esc_attr($s['sitemap_max_items']); ?>">
                                    <span class="description">Use <code>all</code> for all published items, or a number like <code>1000</code>.</span>
                                </td>
                            </tr>
                            <tr>
                                <th>Extra URLs (one per line)</th>
                                <td>
                                    <textarea name="extra_urls" rows="4" style="width:100%;max-width:700px;"><?php echo esc_textarea($s['extra_urls']); ?></textarea>
                                    <p class="description">Add important URLs not covered above. Use full URLs (<code>https://…</code>) or paths (<code>/my-page</code>).</p>
                                </td>
                            </tr>
							<tr>
    <th>Exclude URLs (one per line)</th>
    <td>
        <textarea name="exclude_urls" rows="4" style="width:100%;max-width:700px;"><?php echo esc_textarea($s['exclude_urls']); ?></textarea>
        <p class="description">
            Use full URLs (<code>https://…</code>) or paths (<code>/private</code>).<br>
            Supports trailing <code>*</code> for prefix matches (e.g., <code>/category/*</code> or <code>/thank-you/*</code>).<br>
            Exact matches exclude a single URL; prefixes exclude everything under that path.
        </p>
    </td>
</tr>
                            <tr>
                                <th>Sitemap URL (from SEO plugin)</th>
                                <td>
                                    <input class="regular-text" name="existing_sitemap" value="<?php echo esc_attr($s['existing_sitemap']); ?>" placeholder="e.g., https://example.com/sitemap_index.xml">
                                    <p class="description">
                                        If an SEO plugin creates a sitemap like /sitemap_index.xml or sitemap.xml then paste that URL here otherwise leave blank.  
                                        <strong>Then UNcheck “Serve /sitemap.xml” in Section 4)</strong> to avoid duplication.
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </div>
                </details>

                
                <details class="aiv-acc" open>
                    <summary>4) Virtual Serving of Robots, Sitemap, and LLMS <em>(recommended)</em></summary>
                    <div class="aiv-acc-body">
                        <ul class="description" style="max-width:880px;">
                            <li><strong>What:</strong> “Serve” creates the file at that web address automatically—no FTP or File Manager.</li>
                            <li><strong>Why:</strong> Easiest way to make these files exist at the correct URLs.</li>
                            <li><strong>How:</strong> Check to use virtual files. Uncheck if you prefer a physical file or your SEO plugin’s version.</li>
                        </ul>
                        <table class="form-table">
                            <tr>
                                <th>Virtual files</th>
                                <td>
                                    <label style="display:block;margin-bottom:8px;">
                                        <input type="checkbox" name="serve_llms" <?php checked($s['serve_llms'],'1'); ?>>
                                        Serve <code><?php echo esc_html($home); ?>/llms.txt</code> (Recommended).  
                                        <em>Uncheck if you’ll upload a physical <code>llms.txt</code> to your site root instead.</em>
                                        <div class="description aiv-note" style="margin-top:6px;"><strong>Pick this if:</strong> you don’t already have an LLMS from an SEO plugin or you will not add a LLMS.txt file.</div>
                                    </label>
                                    <label style="display:block;margin-bottom:8px;">
                                        <input type="checkbox" name="serve_sitemap" <?php checked($s['serve_sitemap'],'1'); ?>>
                                        Serve <code><?php echo esc_html($home); ?>/sitemap.xml</code>.  
                                        <strong>If your SEO plugin already has a sitemap and you filled “Existing sitemap URL”, UNcheck this</strong> and submit the plugin’s sitemap instead.
                                        <div class="description aiv-note" style="margin-top:6px;"><strong>Pick this if:</strong> you don’t already have a sitemap from an SEO plugin.</div>
                                    </label>
                                    <label style="display:block;margin-bottom:0;">
                                        <input type="checkbox" name="extend_robots" <?php checked($s['extend_robots'],'1'); ?>>
                                        Extend virtual <code>/robots.txt</code> with GPTBot/PerplexityBot/CommonCrawl + sitemap line.
                                        <div class="description aiv-note" style="margin-top:6px;">
                                            <strong>Pick this if:</strong> you want to welcome AI crawlers and link your sitemap. Safe with SEO plugins; we remove duplicate <code>Sitemap:</code> lines automatically.
                                        </div>
                                    </label>
                                    <p class="description" style="margin-top:8px;">
                                        <?php
                                        $robots_link = '<a href="'.esc_url($home.'/robots.txt').'" target="_blank" rel="noopener">'.$home.'/robots.txt</a>';
                                        if ($physical_robots_exists) {
                                            echo '<strong>Physical robots.txt detected.</strong><br>';
                                            echo '- Your server serves the physical file first. View it at '.$robots_link.'.<br>';
                                            echo '- Our extension affects ONLY WordPress’ virtual robots, not the physical file.<br>';
                                            echo '- To match our advice, copy the suggested lines into your physical <code>robots.txt</code> (usually <code>public_html/robots.txt</code>).';
                                        } else {
                                            echo '<strong>No physical robots.txt detected (this is OK).</strong><br>';
                                            echo '- WordPress and many SEO plugins output a <em>virtual</em> robots.txt (not a file on disk). That’s why no physical file is found — this is normal.<br>';
                                            echo '- We add our lines after your SEO plugin’s lines, and automatically remove duplicate <code>Sitemap:</code> entries. If you later add a physical file, it will override the virtual one.';
                                        }
                                        ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </div>
                </details>

                
                <details class="aiv-acc">
                    <summary>5) FAQ Schema – Manual Q&amp;A <em>(optional)</em></summary>
                    <div class="aiv-acc-body">
                        <ul class="description" style="max-width:880px;">
                            <li><strong>What:</strong> Paste Q/A pairs; we convert them to invisible FAQ JSON-LD.</li>
                            <li><strong>Why:</strong> AI/Google can reuse your answers and cite you.</li>
                            <li><strong>How:</strong> Use the format below. Choose: auto-inject on specific pages (by page ID) OR copy the JSON into a Custom HTML block.</li>
                            <li><strong>Use with Auto FAQ?</strong> Yes — Manual and Auto can both run. They simply combine on the page. Try not to repeat the same questions.</li>
                        </ul>
                        <p><strong>Format</strong>: <code>Q: …</code> on one line, then <code>A: …</code> on the next. Blank line between pairs.</p>
                        <textarea name="faq_text" rows="8" style="width:100%;max-width:900px;"><?php echo esc_textarea($s['faq_text']); ?></textarea>
                        <p>
                            <label>Auto-inject JSON-LD on page IDs (comma-separated): 
                                <input name="faq_page_ids" class="regular-text" value="<?php echo esc_attr($s['faq_page_ids']); ?>" placeholder="e.g., 12,34">
                            </label>
                        </p>
                        <p class="description" style="max-width:880px;">
                            <strong>“Auto-inject”</strong> = this tool inserts the JSON-LD into the page’s &lt;head&gt; for you (no copying).  
                            <strong>Find a page ID:</strong> Pages → hover the page → see <code>post=123</code> in the URL.
                        </p>
                    </div>
                </details>

                
                <details class="aiv-acc">
                    <summary>6) FAQ Schema – Auto from Page Content <em>(optional)</em></summary>
                    <div class="aiv-acc-body">
                        <ul class="description" style="max-width:880px;">
                            <li><strong>What:</strong> If you already built an FAQ on the page (e.g., an <em>accordion</em> in Elementor or a <em>Details/Accordion</em> block in Gutenberg), we read those visible questions/answers and generate matching JSON-LD automatically.</li>
                            <li><strong>Why:</strong> When you edit your accordion content, the schema updates itself.</li>
                            <li><strong>How:</strong> Add a CSS class to your FAQ section (e.g., <code>aiv-faq</code>), pick a preset that matches your builder, then turn it on.</li>
                            <li><strong>Works with:</strong> Elementor Accordion, Gutenberg Details/Accordion, or simple headings where an <code>H3</code> is followed by a paragraph answer.</li>
                        </ul>
                        <table class="form-table">
                            <tr>
                                <th>Read my on-page FAQ and build schema</th>
                                <td>
                                    <label><input type="checkbox" name="faq_auto_enable" <?php checked($s['faq_auto_enable'],'1'); ?>> Yes (enable auto)</label>
                                    <p class="description">
                                        <strong>ON (checked):</strong> We scan your FAQ section (like your accordion) and add JSON-LD that matches what visitors can read.<br>
                                        <strong>OFF (unchecked):</strong> We don’t scan your page. Only the Manual Q&A above applies (if you listed page IDs or paste JSON yourself).
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th>Preset</th>
                                <td>
                                    <select name="faq_mode">
                                        <option value="preset_elementor" <?php selected($s['faq_mode'],'preset_elementor'); ?>>Elementor Accordion (Title = Q, Content = A)</option>
                                        <option value="preset_gutenberg"  <?php selected($s['faq_mode'],'preset_gutenberg');  ?>>Gutenberg Details/Accordion</option>
                                        <option value="simple_headings"   <?php selected($s['faq_mode'],'simple_headings');   ?>>Simple Headings (H3 = Q, next paragraph = A)</option>
                                        <option value="custom_selectors"  <?php selected($s['faq_mode'],'custom_selectors');  ?>>Custom selectors (advanced)</option>
                                    </select>
                                    <p class="description" style="margin-top:6px;">
                                        <strong>Elementor:</strong> Uses the Accordion widget (title = question; content = answer).<br>
                                        <strong>Gutenberg:</strong> Uses the native “Details/Accordion” block (summary = question; inner content = answer).<br>
                                        <strong>Simple Headings:</strong> Each <code>&lt;h3&gt;</code> is the question; the <em>very next paragraph</em> is the answer.<br>
                                        <strong>Custom (only if needed):</strong> Point us to your question and answer elements.  
                                        Example — Question selector: <code>.my-accordion .question</code> | Answer selector: <code>.my-accordion .answer</code>.  
                                        If your answer is simply the next paragraph after the question heading, set Answer selector to <code>next</code>.
                                    </p>
								<div class="aiv-helper">
    <strong>Example (Custom HTML layout)</strong>
    <p style="margin:.4em 0 0 0;">
        Add a container for your FAQ on the page (give it the class you set in “FAQ container CSS class”, e.g. <code>aiv-faq</code>), then mark your questions and answers:
    </p>
    <pre><code>&lt;div class="my-accordion"&gt;
  &lt;div class="question"&gt;Do you offer free quotes?&lt;/div&gt;
  &lt;div class="answer"&gt;Yes, we reply within 24 hours.&lt;/div&gt;

  &lt;div class="question"&gt;Can I cancel anytime?&lt;/div&gt;
  &lt;div class="answer"&gt;Yes, there are no contracts.&lt;/div&gt;
&lt;/div&gt;</code></pre>
    <p style="margin:.6em 0 0 0;">
        Then in this panel set:
        <br>Question selector: <code>.my-accordion .question</code>
        <br>Answer selector: <code>.my-accordion .answer</code>
    </p>
    <p class="aiv-note" style="margin:.6em 0 0 0;">
        If your answer is simply the next paragraph after each question heading, set “Answer selector” to <code>next</code> and leave the default “Simple Headings” preset instead.
    </p>
</div>
                                </td>
                            </tr>
                            <tr>
                                <th>FAQ container CSS class</th>
                                <td>
                                    <input class="regular-text" name="faq_container_class" value="<?php echo esc_attr($s['faq_container_class']); ?>">
                                    <p class="description">Add this to your FAQ section/container (no dot). Elementor: Edit Section → Advanced → CSS Classes.</p>
                                </td>
                            </tr>
                            <tr>
                                <th>Only on these page IDs</th>
                                <td>
                                    <input class="regular-text" name="faq_auto_pages_ids" value="<?php echo esc_attr($s['faq_auto_pages_ids']); ?>" placeholder="e.g., 42,108">
                                    <p class="description">Leave blank = auto on any page that contains that CSS class. Add IDs if you want to limit where auto runs.</p>
                                </td>
                            </tr>
                            <tr>
                                <th>Question selector (custom/simple)</th>
                                <td>
                                    <input class="regular-text" name="faq_q_selector" value="<?php echo esc_attr($s['faq_q_selector']); ?>">
                                    <p class="description"><strong>Simple mode:</strong> keep <code>h3</code>.  <strong>Custom mode:</strong> e.g., <code>.faq .question</code></p>
                                </td>
                            </tr>
                            <tr>
                                <th>Answer selector (custom/simple)</th>
                                <td>
                                    <input class="regular-text" name="faq_a_selector" value="<?php echo esc_attr($s['faq_a_selector']); ?>">
                                    <p class="description"><strong>If answer follows the question directly:</strong> set to <code>next</code>.  <strong>Otherwise (custom):</strong> e.g., <code>.faq .answer</code></p>
                                </td>
                            </tr>
                        </table>
                    </div>
                </details>

                
                <details class="aiv-acc">
                    <summary>7) Generated Outputs <em>(copy-paste if you prefer physical files instead of 4) Virtual)</em></summary>
                    <div class="aiv-acc-body">
                        <h3>robots.txt (we append this to WordPress’ virtual robots)</h3>
                        <textarea readonly rows="9" style="width:100%;max-width:900px;"><?php echo esc_textarea($robots); ?></textarea>
                        <ul class="description" style="max-width:880px;">
                            <li><strong>What:</strong> Invites GPTBot/PerplexityBot/CommonCrawl and links your sitemap.</li>
                            <li><strong>Where (physical):</strong> <code>public_html/robots.txt</code> (site root). View at <a href="<?php echo esc_url($home.'/robots.txt'); ?>" target="_blank" rel="noopener"><?php echo esc_html($home); ?>/robots.txt</a>.</li>
                            <li><strong>SEO plugin note:</strong> With virtual robots (no physical file), WordPress merges plugin output and our additions; we also remove duplicate <code>Sitemap:</code> lines. A physical file overrides virtual output.</li>
                        </ul>

                        <h3>llms.txt</h3>
                        <textarea readonly rows="8" style="width:100%;max-width:900px;"><?php echo esc_textarea($llms); ?></textarea>
                        <ul class="description" style="max-width:880px;">
                            <li><strong>What:</strong> Optional “cheat sheet” for AI listing your best pages and highlights.</li>
                            <li><strong>Where (physical):</strong> <code>public_html/llms.txt</code>. View at <a href="<?php echo esc_url($home.'/llms.txt'); ?>" target="_blank" rel="noopener"><?php echo esc_html($home); ?>/llms.txt</a>.</li>
                            <li><strong>Recommended:</strong> Keep “Serve /llms.txt” checked (easiest).</li>
                        </ul>

                        <h3>sitemap.xml</h3>
                        <textarea readonly rows="12" style="width:100%;max-width:900px;"><?php echo esc_textarea($sitemap); ?></textarea>
                        <ul class="description" style="max-width:880px;">
                            <li><strong>What:</strong> Index of your URLs for Google/Bing.</li>
                            <li><strong>Serve ours vs SEO plugin’s:</strong>
                                If your SEO plugin already has a sitemap (paste it above), <strong>UNcheck “Serve /sitemap.xml”</strong> and submit your plugin’s sitemap instead.
                            </li>
                            <li><strong>Submit to Google:</strong> <a href="https://search.google.com/search-console" target="_blank" rel="noopener">Search Console</a> → Sitemaps → paste URL.</li>
                            <li><strong>Submit to Bing:</strong> <a href="https://www.bing.com/webmasters/" target="_blank" rel="noopener">Bing Webmaster Tools</a> → Sitemaps → paste URL.</li>
                        </ul>

                        <h3>FAQ Schema JSON-LD (Manual preview)</h3>
                        <textarea readonly rows="14" style="width:100%;max-width:900px;"><?php echo esc_textarea($faq_prev); ?></textarea>
                        <ul class="description" style="max-width:880px;">
                            <li><strong>What:</strong> JSON-LD for your manual Q/As above.</li>
                            <li><strong>Auto-inject =</strong> this snippet inserts it (if you listed page IDs in “Auto-inject on page IDs”).</li>
                            <li><strong>Not auto-injecting:</strong> Edit your FAQ page → add a “Custom HTML” block at the bottom → paste this → Update.</li>
                            <li><strong>Test:</strong> Google Rich Results Test <a href="https://search.google.com/test/rich-results" target="_blank" rel="noopener">https://search.google.com/test/rich-results</a> → paste your page URL → it should detect “FAQ”; click and expand to see the questions and answers.</li>
                        </ul>
                    </div>
                </details>

<p style="display:flex; align-items:center; gap:10px; margin-top:20px;">
    <button class="button button-primary" name="aiv_save" value="1">Save Settings</button>
    <a href="https://paypal.com/paypalme/iamimransiddiq" target="_blank" class="button button-secondary donate-btn" rel="noopener">
        Donate to Support Web Squadron
    </a>
</p>
                <hr>
                <h2>What To Do Next (step-by-step)</h2>
                <ol style="max-width:1080px;">
				<li><strong>Basic SEO:</strong>
                       Add keywords/key-phrases naturally into H1, H2, body text, alt-image text descriptions. Do not repeat the same keywords on multiple pages/posts.</li>
				<li><strong>Check visibility to search engines:</strong>
                        Go to Settings → Reading → Make sure "Discourage search engines from indexing this site" IS NOT ticked.</li>
                    <li><strong>Check if live helpers exist:</strong>
                        open
                        <a href="<?php echo esc_url($home.'/robots.txt'); ?>" target="_blank" rel="noopener"><?php echo esc_html($home); ?>/robots.txt</a>,
                        <a href="<?php echo esc_url($home.'/sitemap.xml'); ?>" target="_blank" rel="noopener"><?php echo esc_html($home); ?>/sitemap.xml</a>,
                        <a href="<?php echo esc_url($home.'/llms.txt'); ?>" target="_blank" rel="noopener"><?php echo esc_html($home); ?>/llms.txt</a>
                        </li>
						
				<li><strong>Section 1 with info about the site:</strong>
                        Build your Organization/LocalBusiness schema so Google, AI crawlers, and assistants know who runs the website.</li>				
						
			<li><strong>Section 2 for LLMS: </strong>
                        List core pages and key resources in friendly sentences. This guides AI crawlers to your best content for brand understanding and attribution.</li>
						
                    <li><strong>Section 3 for Sitemap options:</strong>  
                        Choose which content types and URLS to include/exclude/add manually, for search engines and AI to understand site structure.</li>
						
                    <li><strong>Section 4 to decide on serving of robots, sitemap, and LLMS:</strong> Toggle whether to generate virtual files (recommended), or to use plugin or files.</li>

                    <li><strong>Submit sitemap to Google:</strong> 
    <a href="https://search.google.com/search-console/sitemaps" target="_blank" rel="noopener">
        Google Search Console Sitemaps
    </a> → paste your sitemap URL (e.g. /sitemap.xml) → click <em>Submit</em>.
</li>
<li><strong>Submit sitemap to Bing:</strong> 
    <a href="https://www.bing.com/webmasters/sitemaps" target="_blank" rel="noopener">
        Bing Webmaster Tools Sitemaps
    </a> → paste your sitemap URL (e.g. /sitemap.xml) → click <em>Submit</em>.
</li>

                    <li><strong>Section 5 (optional) for Manual-FAQ:</strong> Write Q and A pairs. List page IDs to auto-insert the JSON-LD to display in rich results. Avoid duplicate questions if using the Auto-FAQ.</li>
					
                    <li><strong>Section 6 (optional) for Auto-FAQ:</strong> If you have an accordion or FAQ section, add the CSS class (aiv-faq) to that container. Pick builder presets to feed the FAQ schema.</li>
					
                    <li><strong>Section 7 (optional) for using Generated Ouputs:</strong>Preview for assessment/checking, or copy your robots.txt/llms.txt as files into public_html, but only if you are not using virtual.</li>
					
                    <li><strong>KEEP AEO ALIVE:</strong> Every 2–4 weeks publish an update (recent results, helped client, installed 30m² patio, saved on tax, etc). Add a new Q&A inside the manual or auto-FAQ.</li>
                </ol>
            </form>

            
            <script type="text/phast">document.addEventListener('DOMContentLoaded',function(){document.querySelectorAll('.aiv-acc[open]').forEach(function(d){d.removeAttribute('open');});});</script>

        </div>
        <?php
    }

    /* ---------------- Generators ---------------- */

    private function norm_path($p) {
        $p = trim($p);
        if ($p === '') return '';
        if ($p[0] !== '/') $p = '/'.$p;
        return rtrim($p, '/');
    }

    private function important_urls($s, $home) {
        $paths = [];
        foreach (['path_services','path_pricing','path_faq','path_contact','path_blog'] as $k) {
            if (!empty($s[$k])) $paths[] = $home . $this->norm_path($s[$k]);
        }
        $extra = [];
        if (!empty($s['extra_urls'])) {
            foreach (array_filter(array_map('trim', explode("\n", $s['extra_urls']))) as $line) {
                if (preg_match('#^https?://#i', $line)) $extra[] = $line;
                else $extra[] = $home . $this->norm_path($line);
            }
        }
        return array_values(array_unique(array_merge($paths, $extra)));
    }

private function site_urls_for_sitemap($s, $home) {
    $urls = [ trailingslashit($home) ];

    $max = strtolower(trim($s['sitemap_max_items'])) === 'all' ? -1 : max(1, (int)$s['sitemap_max_items']);
    if (!empty($s['post_types'])) {
        foreach ($s['post_types'] as $pt) {
            $args = [
                'post_type'      => $pt,
                'post_status'    => 'publish',
                'posts_per_page' => ($max === -1 ? -1 : $max),
                'orderby'        => 'date',
                'order'          => 'DESC',
                'fields'         => 'ids'
            ];
            $ids = get_posts($args);
            foreach ($ids as $id) $urls[] = get_permalink($id);
        }
    }

    // Add “important” and “extra” URLs
    $urls = array_merge($urls, $this->important_urls($s, $home));

    // De-dup + tidy
    $urls = array_values(array_unique(array_filter(array_map(function($u){
        return rtrim(trim($u));
    }, $urls))));

    // Compile exclude regexes and filter
    $exclude_regexes = $this->compile_exclude_patterns($s, $home);
    if (!empty($exclude_regexes)) {
        $urls = array_values(array_filter($urls, function($u) use ($exclude_regexes) {
            return !$this->should_exclude_url($u, $exclude_regexes);
        }));
    }

    return $urls;
}

    private function parse_pairs_block($text) {
        $pairs = [];
        $text = trim($text);
        if ($text === '') return $pairs;
        $blocks = preg_split("/\n{2,}/", $text);
        foreach ($blocks as $b) {
            $q = $a = '';
            foreach (preg_split("/\n/", trim($b)) as $line) {
                if (stripos($line,'Q:')===0) $q = trim(substr($line,2));
                if (stripos($line,'A:')===0) $a = trim(substr($line,2));
            }
            if ($q && $a) $pairs[] = ['q'=>$q,'a'=>$a];
        }
        return $pairs;
    }

    private function xml_escape($s) {
        return htmlspecialchars($s, ENT_XML1|ENT_QUOTES, 'UTF-8');
    }

// === NEW: group URLs by post type (and extras) ===
private function gather_urls_by_type($s, $home) {
    $out = [];
    $home_url = trailingslashit($home);

    $max = strtolower(trim($s['sitemap_max_items'])) === 'all' ? -1 : max(1, (int)$s['sitemap_max_items']);
    foreach ((array) $s['post_types'] as $pt) {
        $args = [
            'post_type'      => $pt,
            'post_status'    => 'publish',
            'posts_per_page' => ($max === -1 ? -1 : $max),
            'orderby'        => 'date',
            'order'          => 'DESC',
            'fields'         => 'ids'
        ];
        $ids = get_posts($args);

        $items = [];
        foreach ($ids as $id) {
            $u = get_permalink($id);
            if (!$u) continue;
            $items[] = [
                'loc'     => $u,
                'lastmod' => get_post_modified_time('c', true, $id) ?: current_time('c'),
            ];
        }

        // Include homepage under "page" (optional)
        if ($pt === 'page') {
            $items[] = ['loc' => $home_url, 'lastmod' => current_time('c')];
        }

        // Apply your existing exclude rules
        $exclude_regexes = $this->compile_exclude_patterns($s, $home);
        if (!empty($exclude_regexes)) {
            $items = array_values(array_filter($items, function($row) use ($exclude_regexes) {
                return !$this->should_exclude_url($row['loc'], $exclude_regexes);
            }));
        }

        // De-dup
        $seen = [];
        $items = array_values(array_filter($items, function($row) use (&$seen){
            $k = rtrim($row['loc'], '/');
            if (isset($seen[$k])) return false;
            $seen[$k] = true;
            return true;
        }));

        if (!empty($items)) $out[$pt] = $items;
    }

    // Add “important/extra” URLs as their own bucket
    $extras = array_map(function($u) {
        return ['loc'=>$u, 'lastmod'=>current_time('c')];
    }, $this->important_urls($s, $home));

    if (!empty($extras)) {
        $out['extra'] = isset($out['extra']) ? array_merge($out['extra'],$extras) : $extras;
    }

    return $out;
}

// === NEW: build the XML index that points to /<type>-sitemap.xml
private function generate_sitemap_index_xml_from_groups(array $groups, $home) {
    $xml  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    $xml .= "<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";

    foreach ($groups as $type => $items) {
        $child = trailingslashit($home) . sanitize_key($type) . "-sitemap.xml";
        $last  = '1970-01-01T00:00:00+00:00';
        foreach ($items as $row) {
            if (!empty($row['lastmod']) && $row['lastmod'] > $last) $last = $row['lastmod'];
        }
        $xml .= "  <sitemap>\n";
        $xml .= "    <loc>".$this->xml_escape($child)."</loc>\n";
        $xml .= "    <lastmod>{$last}</lastmod>\n";
        $xml .= "  </sitemap>\n";
    }

    $xml .= "</sitemapindex>\n";
    return $xml;
}

// === NEW: build a per-type URLset
private function generate_type_sitemap_xml($type, array $items) {
    $xml  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    $xml .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
    foreach ($items as $row) {
        $loc = $this->xml_escape($row['loc']);
        $lm  = $row['lastmod'] ?: current_time('c');
        $xml .= "  <url>\n";
        $xml .= "    <loc>{$loc}</loc>\n";
        $xml .= "    <lastmod>{$lm}</lastmod>\n";
        $xml .= "  </url>\n";
    }
    $xml .= "</urlset>\n";
    return $xml;
}

// === NEW: optional human-friendly text outputs
private function generate_sitemap_index_txt_from_groups(array $groups, $home) {
    $lines = [];
    foreach ($groups as $type => $items) {
        $child = trailingslashit($home) . sanitize_key($type) . "-sitemap.xml";
        $last  = '1970-01-01T00:00:00+00:00';
        foreach ($items as $row) if (!empty($row['lastmod']) && $row['lastmod'] > $last) $last = $row['lastmod'];
        $lines[] = sprintf("%s\t%s\t%s", $type, $child, $last);
    }
    return implode("\n", $lines) . "\n";
}

private function generate_type_sitemap_txt($type, array $items) {
    $lines = [];
    foreach ($items as $row) {
        $lines[] = sprintf("%s\t%s", $row['loc'], $row['lastmod'] ?: '');
    }
    return implode("\n", $lines) . "\n";
}
																 
private function compile_exclude_patterns($s, $home) {
    $patterns = [];
    $src = trim((string)($s['exclude_urls'] ?? ''));
    if ($src === '') return $patterns;

    $lines = array_filter(array_map('trim', explode("\n", str_replace("\r", '', $src))));
    foreach ($lines as $p) {
        // Make absolute (normalize everything)
        if (!preg_match('#^https?://#i', $p)) {
            $p = $home . $this->norm_path($p);
        } else {
            $p = rtrim($p, '/');
        }

        $is_prefix = substr($p, -1) === '*';
        if ($is_prefix) $p = rtrim(substr($p, 0, -1), '/');

        $quot = preg_quote($p, '#');
        if ($is_prefix) {
            // Match the URL itself or anything under it
            $patterns[] = "#^{$quot}(?:/.*)?$#i";
        } else {
            // Exact URL, allow optional trailing slash
            $patterns[] = "#^{$quot}/?$#i";
        }
    }
    return $patterns;
}

private function should_exclude_url($url, array $regexes) {
    $u = rtrim(trim($url), '/');
    foreach ($regexes as $rx) {
        if (@preg_match($rx, $u) && preg_match($rx, $u)) return true;
    }
    return false;
}																 
																 
public function generate_robots_txt($s, $home) {
    // pick ONE sitemap URL by precedence:
    // 1) Existing sitemap (from SEO plugin) if provided
    // 2) Our virtual /sitemap.xml if enabled
    // 3) Core WP sitemap as a safe fallback
    if (!empty($s['existing_sitemap'])) {
        $map = trim($s['existing_sitemap']);
    } elseif ($s['serve_sitemap'] === '1') {
        $map = trailingslashit($home) . 'sitemap.xml';
    } else {
        $map = trailingslashit($home) . 'wp-sitemap.xml';
    }

    return
        "User-agent: GPTBot\nAllow: /\n\n" .
        "User-agent: PerplexityBot\nAllow: /\n\n" .
        "User-agent: CCBot\nAllow: /\n\n" .
        "User-agent: AnthropicBot\nAllow: /\n\n" .
        "User-agent: Google-Extended\nAllow: /\n\n" .
        "User-agent: Applebot-Extended\nAllow: /\n\n" .
        "Sitemap: {$map}\n";
}

public function generate_llms_txt($s, $home) {
    $out = [];

    // helper to add a path+desc line safely
    $add = function($path, $desc) use (&$out) {
        $path = rtrim(trim($path));
        $desc = trim((string)$desc);

        if ($path === '') return;

        // leave headings alone (shouldn't get here, but guard anyway)
        if (preg_match('/^\s*#{1,6}\s+/', $path)) {
            $out[] = ltrim($path);
            return;
        }

        // if not absolute URL and not starting with '/', prefix it
        if ($path[0] !== '/' && !preg_match('#^https?://#i', $path)) {
            $path = '/'.$path;
        }

        $out[] = rtrim($path . ($desc !== '' ? "   {$desc}" : ''));
    };

    // keep the 5 key paths at the top (if provided)
    $add($s['path_services'], $s['desc_services']);
    $add($s['path_pricing'],  $s['desc_pricing']);
    $add($s['path_faq'],      $s['desc_faq']);
    $add($s['path_contact'],  $s['desc_contact']);
    $add($s['path_blog'],     $s['desc_blog']);

    // Now process the free-form "extra_llms" block
    if (!empty($s['extra_llms'])) {
        $raw = str_replace("\r", '', (string)$s['extra_llms']);
        $lines = explode("\n", $raw); // DO NOT trim/filter — preserves blank lines

        foreach ($lines as $line) {
            // preserve completely blank lines
            if ($line === '') { $out[] = ''; continue; }

            $r = rtrim($line);

            // headings (e.g. "# Title", "## Section")
            if (preg_match('/^\s*#{1,6}\s+/', $r)) {
                $out[] = ltrim($r);
                continue;
            }

            // path-or-url  ␠␠  description  (or tabs)
            if (preg_match('/^\s*(\S+)\s{2,}(.+)\s*$/u', $r, $m) || preg_match('/^\s*(\S+)\t+(.+)\s*$/u', $r, $m)) {
                $add($m[1], $m[2]);
                continue;
            }

            // otherwise treat as a bare path/URL (no description)
            $add($r, '');
        }
    }

    // join with newlines; keep a trailing newline
    return implode("\n", $out) . "\n";
}

public function generate_sitemap_xml($s, $home) {
    $urls = $this->site_urls_for_sitemap($s, $home);
    $xml  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    $xml .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";

    foreach ($urls as $u) {
        // Try to find the post ID for this URL so we can use its last modified date
        $post_id = url_to_postid($u);
        if ($post_id) {
            $lastmod = get_post_modified_time('c', true, $post_id);
        } else {
            // fallback: current time if not a post (e.g., static URL)
            $lastmod = current_time('c');
        }

        $xml .= "  <url>\n";
        $xml .= "    <loc>" . $this->xml_escape($u) . "</loc>\n";
        $xml .= "    <lastmod>{$lastmod}</lastmod>\n";
        $xml .= "  </url>\n";
    }

    $xml .= "</urlset>\n";
    return $xml;
}

    /* ---------------- FAQ Auto from Page Content ---------------- */

private function get_preset_selectors($mode) {
    // Returns [q_selector, strategy, a_selector]
    // strategy: 'next' | 'css' | 'elementor_nested' | 'gutenberg_details'
    switch ($mode) {
        case 'preset_elementor':
            // Try the modern Nested Accordion first; fallback handled in extractor.
            // elementor_nested strategy ignores these selectors and uses structure.
            return [null, 'elementor_nested', null];

        case 'preset_gutenberg':
            // Gutenberg Details: <details class="wp-block-details"><summary>Q</summary> ...A...</details>
            return ['.wp-block-details summary', 'gutenberg_details', null];

        case 'simple_headings':
            // <h3>Q</h3><p>A</p>
            return ['h3', 'next', 'p'];

        case 'custom_selectors':
        default:
            // User provides selectors; 'css' means "find Q by CSS; find A by CSS after Q"
            return [null, 'css', null];
    }
}

private function auto_faq_pairs_from_content($s, $content_html) {
    $pairs = [];
    if ($s['faq_auto_enable'] !== '1') return $pairs;
	if (!class_exists('DOMDocument') || !class_exists('DOMXPath')) return $pairs; // Guard if ext-dom missing

    $container_class = trim($s['faq_container_class']);
    if ($container_class === '') return $pairs;

    libxml_use_internal_errors(true);
    $dom = new DOMDocument('1.0', 'UTF-8');
    $html = '<!DOCTYPE html><html><head></head><body>'.$content_html.'</body></html>';
    $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();
    $xpath = new DOMXPath($dom);

    // Find the first container matching the CSS class token
    $class_token = trim(preg_split('/\s+/', $container_class)[0]);
    $container_nodes = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' " . $class_token . " ')]");
    if (!$container_nodes || $container_nodes->length === 0) return $pairs;
    $container = $container_nodes->item(0);

    list($preset_q, $strategy, $preset_a) = $this->get_preset_selectors($s['faq_mode']);

    // Helper to normalize inner text (strip tags, collapse whitespace)
    $text_of = function(DOMNode $node) {
        $txt = trim(preg_replace('/\s+/', ' ', $node->textContent ?? ''));
        return $txt;
    };

    // ---------- ELEMENTOR NESTED ----------
    if ($strategy === 'elementor_nested') {
        // Try new Nested Accordion structure first
        // details.e-n-accordion-item > summary.e-n-accordion-item-title
        $details_nodes = $xpath->query('.//details[contains(concat(" ", normalize-space(@class), " "), " e-n-accordion-item ")]', $container);

        if ($details_nodes && $details_nodes->length) {
            foreach ($details_nodes as $det) {
                // QUESTION: prefer inner .e-n-accordion-item-title-text if present
                $sum = $xpath->query('./summary[contains(concat(" ", normalize-space(@class), " "), " e-n-accordion-item-title ")]', $det)->item(0);
                if (!$sum) continue;

                // Some Elementor skins wrap the title in .e-n-accordion-item-title-text
                $title_text_node = $xpath->query('.//*[contains(concat(" ", normalize-space(@class), " "), " e-n-accordion-item-title-text ")]', $sum)->item(0);
                $q_text = $text_of($title_text_node ?: $sum);
                if ($q_text === '') continue;

                // ANSWER: the sibling region inside the same <details>
                $region = $xpath->query('./*[@role="region"]', $det)->item(0);
                if ($region) {
                    $a_text = $text_of($region);
                    if ($a_text !== '') $pairs[] = ['q' => $q_text, 'a' => $a_text];
                }
            }
        }

        // If nothing was found with nested, fallback to classic Elementor
        if (empty($pairs)) {
            $q_nodes = $xpath->query('.//div[contains(concat(" ", normalize-space(@class), " "), " elementor-accordion-title ")]', $container);
            $a_nodes = $xpath->query('.//div[contains(concat(" ", normalize-space(@class), " "), " elementor-accordion-content ")]', $container);
            if ($q_nodes && $a_nodes && $q_nodes->length && $a_nodes->length) {
                $len = min($q_nodes->length, $a_nodes->length);
                for ($i = 0; $i < $len; $i++) {
                    $q_text = $text_of($q_nodes->item($i));
                    $a_text = $text_of($a_nodes->item($i));
                    if ($q_text !== '' && $a_text !== '') $pairs[] = ['q' => $q_text, 'a' => $a_text];
                }
            }
        }
        return $pairs;
    }

    // ---------- GUTENBERG DETAILS ----------
    if ($strategy === 'gutenberg_details') {
        // Each .wp-block-details contains a <summary> and arbitrary content as the answer
        $blocks = $xpath->query('.//details[contains(concat(" ", normalize-space(@class), " "), " wp-block-details ")]', $container);
        if ($blocks && $blocks->length) {
            foreach ($blocks as $det) {
                $sum = $xpath->query('./summary', $det)->item(0);
                if (!$sum) continue;
                $q_text = $text_of($sum);
                if ($q_text === '') continue;

                // Answer: everything inside details except the summary
                $answer_txt = '';
                foreach (iterator_to_array($det->childNodes) as $child) {
                    if ($child->nodeType === XML_ELEMENT_NODE && strtolower($child->nodeName) === 'summary') continue;
                    $answer_txt .= ' ' . $text_of($child);
                }
                $answer_txt = trim($answer_txt);
                if ($answer_txt !== '') $pairs[] = ['q' => $q_text, 'a' => $answer_txt];
            }
        }
        return $pairs;
    }

    // ---------- SIMPLE HEADINGS (h3 + next p) ----------
    if ($strategy === 'next') {
        $q_sel = ($s['faq_mode']==='custom_selectors' ? trim($s['faq_q_selector']) : 'h3');
        $a_sel = ($s['faq_mode']==='custom_selectors' ? trim(strtolower($s['faq_a_selector'])) : 'p');
        if ($q_sel === '') $q_sel = 'h3';

        $q_nodes = $xpath->query('.//'.$q_sel, $container);
        if ($q_nodes && $q_nodes->length) {
            foreach ($q_nodes as $qnode) {
                $q_text = $text_of($qnode);
                if ($q_text === '') continue;

                $a_text = '';
                $next = $qnode->nextSibling;
                while ($next && $next->nodeType !== XML_ELEMENT_NODE) { $next = $next->nextSibling; }
                if ($next && strtolower($next->nodeName) === $a_sel) $a_text = $text_of($next);

                if ($a_text !== '') $pairs[] = ['q'=>$q_text, 'a'=>$a_text];
            }
        }
        return $pairs;
    }

    // ---------- CUSTOM / GENERIC CSS PAIRING ----------
    // Find Q nodes by CSS; find the first A node that appears after each Q
    if ($strategy === 'css') {
        $q_sel = trim($s['faq_q_selector']);
        $a_sel = trim($s['faq_a_selector']);
        if ($q_sel === '' || $a_sel === '') return $pairs;

        $q_nodes = $xpath->query('.//'.$q_sel, $container);
        $a_nodes = $xpath->query('.//'.$a_sel, $container);
        if ($q_nodes && $q_nodes->length && $a_nodes && $a_nodes->length) {
            foreach ($q_nodes as $qnode) {
                $q_text = $text_of($qnode);
                if ($q_text === '') continue;

                $found_a = '';
                foreach ($a_nodes as $cand) {
                    if ($this->node_is_after($cand, $qnode)) { $found_a = $text_of($cand); break; }
                }
                if ($found_a !== '') $pairs[] = ['q'=>$q_text, 'a'=>$found_a];
            }
        }
        return $pairs;
    }

    return $pairs;
}

    private function node_is_after(DOMNode $a, DOMNode $b) {
        $pos = $b;
        while ($pos = $pos->nextSibling) {
            if ($pos->isSameNode($a)) return true;
            if ($pos->hasChildNodes()) {
                $stack = [$pos];
                while ($stack) {
                    $n = array_pop($stack);
                    if ($n->isSameNode($a)) return true;
                    if ($n->hasChildNodes()) foreach (iterator_to_array($n->childNodes) as $ch) $stack[] = $ch;
                }
            }
        }
        return false;
    }

    private function build_faq_jsonld_from_pairs($pairs) {
        $entities = [];
        foreach ($pairs as $p) {
            $q = wp_strip_all_tags($p['q']);
            $a = wp_strip_all_tags($p['a']);
            if ($q === '' || $a === '') continue;
            $entities[] = [
                "@type" => "Question",
                "name"  => $q,
                "acceptedAnswer" => [
                    "@type" => "Answer",
                    "text"  => $a
                ]
            ];
        }
        return [
            "@context"   => "https://schema.org",
            "@type"      => "FAQPage",
            "mainEntity" => $entities
        ];
    }

    public function generate_faq_jsonld_preview($s) {
        $pairs_manual = $this->parse_pairs_block($s['faq_text']);
        $data = $this->build_faq_jsonld_from_pairs($pairs_manual);
        return "<script type=\"application/ld+json\">\n". wp_json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT) ."\n</script>";
    }

    /* ---------------- Output & Serving ---------------- */

public function bypass_canonical_for_virtual($redirect_url, $requested_url) {
    $path = parse_url($requested_url ?: '', PHP_URL_PATH);
    if (!$path && !empty($_SERVER['REQUEST_URI'])) {
        $path = parse_url(home_url($_SERVER['REQUEST_URI']), PHP_URL_PATH);
    }
    $path = rtrim($path ?: '', '/');

    $skip = [
        '/sitemap.xml','/sitemap.txt','/llms.txt',
        '/sitemap_index.xml','/sitemap-index.xml'
    ];

    if (preg_match('#^/([a-z0-9_\-]+)-sitemap\.(xml|txt)$#i', $path)) {
        return false; // don't canonical-redirect per-type sitemaps either
    }
    if (in_array($path, $skip, true)) {
        return false;
    }
    return $redirect_url;
}

public function serve_virtual_files() {
    $s    = $this->get_settings();
    $uri  = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);
    $home = rtrim(site_url(), '/');

    // llms.txt
    if ($s['serve_llms']==='1' && rtrim($uri,'/') === '/llms.txt') {
        nocache_headers();
        header('Content-Type: text/plain; charset=utf-8');
        echo $this->generate_llms_txt($s, $home);
        exit;
    }

    if ($s['serve_sitemap'] === '1') {
        $path = rtrim($uri, '/');
        $groups = $this->gather_urls_by_type($s, $home);

        // XML index
        if ($path === '/sitemap.xml') {
            nocache_headers();
            header('Content-Type: application/xml; charset=utf-8');
            echo $this->generate_sitemap_index_xml_from_groups($groups, $home);
            exit;
        }

        // TXT index (human readable)
        if ($path === '/sitemap.txt') {
            nocache_headers();
            header('Content-Type: text/plain; charset=utf-8');
            echo $this->generate_sitemap_index_txt_from_groups($groups, $home);
            exit;
        }

        // Per-type XML: /<type>-sitemap.xml
        if (preg_match('#^/([a-z0-9_\-]+)-sitemap\.xml$#i', $path, $m)) {
            $type = sanitize_key($m[1]);
            if (isset($groups[$type])) {
                nocache_headers();
                header('Content-Type: application/xml; charset=utf-8');
                echo $this->generate_type_sitemap_xml($type, $groups[$type]);
                exit;
            }
        }

        // Per-type TXT: /<type>-sitemap.txt
        if (preg_match('#^/([a-z0-9_\-]+)-sitemap\.txt$#i', $path, $m)) {
            $type = sanitize_key($m[1]);
            if (isset($groups[$type])) {
                nocache_headers();
                header('Content-Type: text/plain; charset=utf-8');
                echo $this->generate_type_sitemap_txt($type, $groups[$type]);
                exit;
            }
        }

        // RankMath-style aliases → redirect to our index
        if (in_array($path, ['/sitemap_index.xml','/sitemap-index.xml'], true)) {
            wp_redirect(trailingslashit($home).'sitemap.xml', 301);
            exit;
        }
    }
}

public function extend_robots_txt($existing, $public) {
    $s = $this->get_settings();
    if ($s['extend_robots'] !== '1') return $existing;

    // If a physical robots.txt exists, don't touch it
    if (file_exists(ABSPATH.'robots.txt')) return $existing;

    $home = rtrim(site_url(), '/');

    // Build our custom block (already contains ONE Sitemap with the chosen URL)
    $custom = $this->generate_robots_txt($s, $home);

    // Normalize newlines
    $out = preg_replace("/\r\n?/", "\n", trim((string) $existing));

    // Remove ALL existing 'Sitemap:' lines so we can add exactly one
    $out = preg_replace('/^\s*Sitemap:\s*\S+.*$/mi', '', $out);
    $out = trim(preg_replace("/\n{2,}/", "\n\n", $out)); // collapse extra blanks

    // Append our block
    if ($out !== '') $out .= "\n\n";
    $out .= trim($custom) . "\n";

    // Final tidy
    $out = preg_replace("/\n{3,}/", "\n\n", $out);
    return rtrim($out) . "\n";
}

    public function maybe_output_faq_schema() {
        if (is_admin()) return;

        $s = $this->get_settings();
        $entities = [];

        $manual_pairs = $this->parse_pairs_block($s['faq_text']);
        $inject_ids = array_filter(array_map('absint', explode(',', $s['faq_page_ids'])));
        if (!empty($inject_ids) && is_page() && in_array(get_queried_object_id(), $inject_ids, true)) {
            $entities = array_merge($entities, $this->build_faq_jsonld_from_pairs($manual_pairs)['mainEntity']);
        }

        $auto_enabled = ($s['faq_auto_enable'] === '1' && class_exists('DOMDocument') && class_exists('DOMXPath'));
        $limit_ids    = array_filter(array_map('absint', explode(',', $s['faq_auto_pages_ids'])));
        $auto_here    = $auto_enabled && (empty($limit_ids) ? true : (is_page() && in_array(get_queried_object_id(), $limit_ids, true)));

        if ($auto_here && is_singular()) {
            global $post;
            if ($post) {
                $content   = apply_filters('the_content', $post->post_content);
                $auto_pairs= $this->auto_faq_pairs_from_content($s, $content);
                if (!empty($auto_pairs)) {
                    $entities = array_merge($entities, $this->build_faq_jsonld_from_pairs($auto_pairs)['mainEntity']);
                }
            }
        }

        if (empty($entities)) return;

        $json = [
            "@context"   => "https://schema.org",
            "@type"      => "FAQPage",
            "mainEntity" => $entities
        ];
        echo "\n<script type=\"application/ld+json\">\n". wp_json_encode($json, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT) ."\n</script>\n";
    }
public function maybe_output_org_schema() {
    if (is_admin() || wp_doing_ajax() || wp_doing_cron()) return;

    $s = $this->get_settings();
    if (empty($s['business_name'])) return;

    // Use the chosen type
    $type = ($s['entity_type'] === 'LocalBusiness') ? 'LocalBusiness' : 'Organization';

    $data = [
        "@context" => "https://schema.org",
        "@type"    => $type,
        "name"     => $s['business_name'],
        "url"      => home_url('/'),
    ];

    if (!empty($s['logo_url'])) $data['logo'] = esc_url($s['logo_url']);
    if (!empty($s['phone']))    $data['telephone'] = $s['phone'];

    if (!empty($s['locality']) || !empty($s['country'])) {
        $data['address'] = ["@type" => "PostalAddress"];
        if (!empty($s['locality'])) $data['address']['addressLocality'] = $s['locality'];
        if (!empty($s['country']))  $data['address']['addressCountry']  = $s['country'];
    }

    if (!empty($s['area_served'])) $data['areaServed'] = $s['area_served'];

    echo "\n<script type=\"application/ld+json\">\n" .
         wp_json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT) .
         "\n</script>\n";
}
}

new AIV_Clarity_Ultra();
				
			

calendly-popup

				
					<link href="https://assets.calendly.com/assets/external/widget.css" rel="stylesheet">
<script type="text/phast" src="https://assets.calendly.com/assets/external/widget.js" async></script>
<script type="text/phast">document.addEventListener('DOMContentLoaded',function(){document.querySelectorAll('.calendly-btn').forEach(function(btn){btn.addEventListener('click',function(e){e.preventDefault();Calendly.initPopupWidget({url:'https://calendly.com/websquadron/appointment'});});});});</script>
				
			

tags-list

				
					/**
 * Woo Product Tags — replace default tag box with a row-wrap checkbox picker
 * - Hides the core "Product tags" meta box
 * - Adds a custom meta box with wrap layout (pills)
 * - Saves to the real product_tag taxonomy
 */

add_action('add_meta_boxes', function () {
    // Remove the default WP tag meta box for product tags
    remove_meta_box('tagsdiv-product_tag', 'product', 'side');

    // Add our custom one
    add_meta_box(
        'ws_product_tag_checklist',
        'Product tags',
        'ws_render_product_tag_wrap_metabox',
        'product',
        'side',
        'default'
    );
}, 20);

function ws_render_product_tag_wrap_metabox($post) {
    wp_nonce_field('ws_save_product_tag_checklist', 'ws_product_tag_checklist_nonce');

    $taxonomy = 'product_tag';

    $terms = get_terms([
        'taxonomy'   => $taxonomy,
        'hide_empty' => false,
        'orderby'    => 'name',
        'order'      => 'ASC',
        'number'     => 500,
    ]);

    if (is_wp_error($terms) || empty($terms)) {
        echo '<p>No tags found.</p>';
        return;
    }

    $selected_ids = wp_get_object_terms($post->ID, $taxonomy, ['fields' => 'ids']);
    if (is_wp_error($selected_ids)) $selected_ids = [];
    $selected_ids = array_map('intval', $selected_ids);

    echo '
    <style>#ws-product-tag-wrap{display:flex;flex-wrap:wrap;gap:10px 14px;max-height:240px;overflow:auto;border:1px solid #ddd;padding:10px;background:#fff;border-radius:6px;align-content:flex-start;}.ws-tag-item{display:inline-flex;align-items:center;gap:6px;margin:0;}.ws-tag-item input{margin:0;}</style>
    ';

    echo '<div id="ws-product-tag-wrap">';

    foreach ($terms as $t) {
        $checked = in_array((int)$t->term_id, $selected_ids, true) ? 'checked' : '';
        printf(
            '<label class="ws-tag-item">
                <input type="checkbox" name="ws_product_tag_ids[]" value="%d" %s>
                <span>%s</span>
            </label>',
            (int) $t->term_id,
            $checked,
            esc_html($t->name)
        );
    }

    echo '</div>';
    echo '<p style="margin-top:8px; font-size:12px; color:#666;">Ticking here updates the real WooCommerce product tags.</p>';
}

add_action('save_post_product', function ($post_id) {
    if (!isset($_POST['ws_product_tag_checklist_nonce']) ||
        !wp_verify_nonce($_POST['ws_product_tag_checklist_nonce'], 'ws_save_product_tag_checklist')) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    $ids = isset($_POST['ws_product_tag_ids']) ? array_map('intval', (array) $_POST['ws_product_tag_ids']) : [];

    // Set the REAL product_tag terms:
    wp_set_object_terms($post_id, $ids, 'product_tag', false);
});
				
			

in-stock-name-change

				
					/* Scope to ONLY Stock Status filter */
.ws-wc-filter-multiselect[data-query-arg="stock-status"]
.ws-wc-filter-multiselect-option span {
  font-size: 0;            /* hides the original text */
  line-height: 0;
}

/* Recreate the visible label */
.ws-wc-filter-multiselect[data-query-arg="stock-status"]
.ws-wc-filter-multiselect-option span::before {
  font-size: 16px;         /* set to match your UI */
  line-height: 1;
  display: inline-block;
  color: inherit;          /* inherits normal text color */
}

/* INSTOCK -> Available */
.ws-wc-filter-multiselect[data-query-arg="stock-status"]
input[value="instock"] + span::before {
  content: "Available";
}

/* OUTOFSTOCK -> Out of Stock */
.ws-wc-filter-multiselect[data-query-arg="stock-status"]
input[value="outofstock"] + span::before {
  content: "Out of Stock";
}

/* Optional: keep ALL as "All" (or remove this if you want to rename it too) */
.ws-wc-filter-multiselect[data-query-arg="stock-status"]
input[value=""] + span::before {
  content: "All";
}
				
			

off-canvas-filter-reopen

				
					<script type="text/phast">(function(){const OFF_CANVAS_ID='881889e';const KEY_REOPEN='ws_oc_reopen_next';const KEY_CLOSED='ws_oc_user_closed';const PANEL_SEL=`#off-canvas-${OFF_CANVAS_ID}`;const OPEN_SEL=`a.elementor-icon[aria-controls="off-canvas-${OFF_CANVAS_ID}"][href*="off_canvas%3Aopen"]`;const CLOSE_SEL=`#off-canvas-${OFF_CANVAS_ID} a.elementor-icon[aria-controls="off-canvas-${OFF_CANVAS_ID}"][href*="off_canvas%3Aclose"]`;const INTERACTION_SEL=[`${PANEL_SEL} .ws-wc-filter-form`,`${PANEL_SEL} .ws-wc-sort-form`,`${PANEL_SEL} .ws-wc-filter-reset`,`${PANEL_SEL} .ws-wc-filter-reset-all`,`${PANEL_SEL} .ws-custom-select-option`,`${PANEL_SEL} .ws-custom-select-trigger`,`${PANEL_SEL} .ws-wc-filter-multiselect-toggle`,`${PANEL_SEL} .ws-wc-filter-multiselect-done`,`${PANEL_SEL} .ws-wc-filter-multiselect-clear`,`${PANEL_SEL} input`,`${PANEL_SEL} select`,`${PANEL_SEL} button`,`${PANEL_SEL} a`].join(',');function ssGet(k){try{return sessionStorage.getItem(k);}catch(e){return null;}}
function ssSet(k,v){try{return sessionStorage.setItem(k,v);}catch(e){}}
function ssDel(k){try{return sessionStorage.removeItem(k);}catch(e){}}
function markShouldReopen(){ssSet(KEY_REOPEN,'1');ssDel(KEY_CLOSED);}
function markUserClosed(){ssDel(KEY_REOPEN);ssSet(KEY_CLOSED,'1');}
function shouldReopen(){return ssGet(KEY_REOPEN)==='1'&&ssGet(KEY_CLOSED)!=='1';}
(function injectCSS(){if(document.getElementById('ws-oc-focusfix-css'))return;const style=document.createElement('style');style.id='ws-oc-focusfix-css';style.textContent=`
      html.ws-oc-reopening ${CLOSE_SEL}:focus,
      html.ws-oc-reopening ${CLOSE_SEL}:focus-visible {
        outline: none !important;
        box-shadow: none !important;
      }
    `;document.head.appendChild(style);})();document.addEventListener('click',(e)=>{if(e.target.closest(INTERACTION_SEL))markShouldReopen();},true);document.addEventListener('change',(e)=>{if(e.target.closest(INTERACTION_SEL))markShouldReopen();},true);document.addEventListener('click',(e)=>{if(e.target.closest(CLOSE_SEL))markUserClosed();},true);function blurFocusHard(){const closeEl=document.querySelector(CLOSE_SEL);const openEl=document.querySelector(OPEN_SEL);if(closeEl&&typeof closeEl.blur==='function')closeEl.blur();if(openEl&&typeof openEl.blur==='function')openEl.blur();if(document.activeElement&&typeof document.activeElement.blur==='function'){document.activeElement.blur();}
let sink=document.getElementById('ws-oc-focus-sink');if(!sink){sink=document.createElement('span');sink.id='ws-oc-focus-sink';sink.tabIndex=-1;sink.style.cssText='position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;';document.body.appendChild(sink);}
sink.focus({preventScroll:true});}
window.addEventListener('load',()=>{if(!shouldReopen())return;const opener=document.querySelector(OPEN_SEL);if(!opener)return;let tries=0;const maxTries=10;const tryOpen=()=>{tries++;opener.click();const expanded=opener.getAttribute('aria-expanded');if(expanded==='true'){ssDel(KEY_REOPEN);document.documentElement.classList.add('ws-oc-reopening');[0,60,140,260].forEach((ms)=>setTimeout(blurFocusHard,ms));setTimeout(()=>{document.documentElement.classList.remove('ws-oc-reopening');},350);return;}
if(tries<maxTries)setTimeout(tryOpen,120);};setTimeout(tryOpen,120);});})();</script>
				
			

better-search-results

				
					add_filter('query_vars', function($vars) {
    $vars[] = 'e_search_props';
    return $vars;
});

add_action('template_redirect', function() {
    if (isset($_GET['e_search_props']) && isset($_GET['s'])) {
        wp_redirect( remove_query_arg('e_search_props'), 301 );
        exit;
    }
});
				
			

quick-access

				
					/**
 * Quick Links (Dashboard Only) — Hardened (no critical errors)
 */
if ( ! defined('ABSPATH') ) exit;

class WSQA_Dashboard_Only_V6 {
	const META_CATALOG  = 'wsqa_catalog_v6';   // array: id => item
	const META_SELECTED = 'wsqa_selected_v6';  // ordered array of ids
	const PAGE_SLUG     = 'wsqa-v6';
	const AJAX_ACTION   = 'wsqa_scan_v6';
	const NONCE_ACTION  = 'wsqa_v6_nonce';

	public static function init() {
		add_action('admin_menu', [__CLASS__, 'add_settings_page']);
		add_action('wp_dashboard_setup', [__CLASS__, 'add_dashboard_widget']);

		add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_assets']);
		add_action('admin_head-index.php', [__CLASS__, 'dashboard_css']);

		add_action('admin_init', [__CLASS__, 'handle_save']);
		add_action('wp_ajax_' . self::AJAX_ACTION, [__CLASS__, 'ajax_scan_save']);
	}

	public static function add_settings_page() {
		add_options_page(
			'Quick Access',
			'Quick Access',
			'read',
			self::PAGE_SLUG,
			[__CLASS__, 'render_settings_page']
		);
	}

	public static function add_dashboard_widget() {
		wp_add_dashboard_widget(
			'wsqa_widget_v6',
			'Quick Access',
			[__CLASS__, 'render_dashboard_widget']
		);
	}

	public static function dashboard_css() {
		?>
		<style>.wsqa6-wrap{margin:-12px;padding:12px;background:#fafafa;}.wsqa6-group{margin:0 0 15px;}.wsqa6-title{font-size:12px;font-weight:700;color:#1e1e1e;margin:0 0 2px 0;text-transform:uppercase;letter-spacing:.05em;}.wsqa6-links{list-style:none;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:8px;}.wsqa6-links a{display:inline-flex;align-items:center;padding:5px 15px;border:1px solid #D0D0CE;border-radius:25px;background:#fff;text-decoration:none;color:#1d2327;font-size:12px;transition:all .2s ease-in-out;}.wsqa6-links a:hover{background:#f6f7f7;border-color:#a7aaad;color:#2271b1;}.wsqa6-label{font-weight:500;}.wsqa6-pill{display:none;}.wsqa6-edit{margin:15px 0 0;font-size:12px;border-top:1px solid #e5e5e5;padding-top:10px;}</style>
		<?php
	}

	public static function render_dashboard_widget() {
		$catalog  = self::get_catalog();   // hardened
		$selected = self::get_selected();  // hardened

		$items = [];
		foreach ($selected as $id) {
			if (!is_string($id) || $id === '') continue;
			if (!isset($catalog[$id]) || !is_array($catalog[$id])) continue;

			$it = self::sanitize_item($catalog[$id]);
			if (!$it) continue;

			if (!empty($it['cap']) && !current_user_can($it['cap'])) continue;
			$items[] = $it;
		}

		if (empty($items)) {
			echo '<p style="margin:0;">No quick links yet.</p>';
			echo '<p style="margin:8px 0 0;"><a href="'.esc_url(admin_url('options-general.php?page='.self::PAGE_SLUG)).'">Scan and choose quick links</a></p>';
			return;
		}

		$grouped = [];
		foreach ($items as $it) {
			$p = !empty($it['parent']) ? $it['parent'] : 'Other';
			if (!isset($grouped[$p])) $grouped[$p] = [];
			$grouped[$p][] = $it;
		}

		echo '<div class="wsqa6-wrap">';
		foreach ($grouped as $parent => $links) {
			echo '<div class="wsqa6-group">';
			echo '<div class="wsqa6-title">'.esc_html($parent).'</div>';
			echo '<ul class="wsqa6-links">';
			foreach ($links as $l) {
				if (!is_array($l)) continue;
				$url = self::normalize_admin_url(isset($l['url']) ? $l['url'] : '');
				$label = isset($l['label']) ? $l['label'] : '';
				if ($url === '' || $label === '') continue;

				echo '<li><a href="'.esc_url($url).'">';
				echo '<span class="wsqa6-label">'.esc_html($label).'</span>';
				echo '</a></li>';
			}
			echo '</ul></div>';
		}
		echo '<p class="wsqa6-edit"><a href="'.esc_url(admin_url('options-general.php?page='.self::PAGE_SLUG)).'">Edit quick links</a></p>';
		echo '</div>';
	}

	public static function enqueue_assets($hook) {
		if ($hook !== 'settings_page_' . self::PAGE_SLUG) return;

		wp_enqueue_script('jquery-ui-sortable');
		$nonce = wp_create_nonce(self::NONCE_ACTION);
		$ajax  = admin_url('admin-ajax.php');

		$js = "
jQuery(function($){
  function syncOrder(){
    var order = [];
    $('#wsqa6-selected li').each(function(){
      var id = $(this).attr('data-id');
      if (id) order.push(id);
    });
    $('#wsqa6_order').val(order.join(','));
  }

  $('#wsqa6-selected').sortable({ handle: '.wsqa6-handle', update: syncOrder });

  function escapeHtml(s){
    s = String(s || '');
    return s.replace(/[&<>\"']/g, function(m){
      return ({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#039;'}[m]);
    });
  }

  $(document).on('click', '.wsqa6-remove', function(){
    var li = $(this).closest('li');
    var id = li.attr('data-id');
    li.remove();
    $('#wsqa6-catalog input[type=checkbox][value=\"'+id+'\"]').prop('checked', false);
    syncOrder();
  });

  $(document).on('change', '#wsqa6-catalog input[type=checkbox]', function(){
    var cb = $(this);
    var id = cb.val();
    var parent = cb.attr('data-parent') || 'Other';
    var label = cb.attr('data-label') || '';
    if (cb.is(':checked')) {
      if ($('#wsqa6-selected li[data-id=\"'+id+'\"]').length) { syncOrder(); return; }
      $('#wsqa6-selected').append(
        '<li class=\"wsqa6-sel\" data-id=\"'+id+'\">'
        + '<span class=\"wsqa6-handle\" aria-hidden=\"true\">☰</span>'
        + '<span class=\"wsqa6-sel-text\"><strong>'+escapeHtml(parent)+'</strong> — '+escapeHtml(label)+'</span>'
        + '<button type=\"button\" class=\"wsqa6-remove\" aria-label=\"Remove\">✕</button>'
        + '</li>'
      );
    } else {
      $('#wsqa6-selected li[data-id=\"'+id+'\"]').remove();
    }
    syncOrder();
  });

  function hashId(s){
    s = String(s || '').toLowerCase();
    var h = 0, i, chr;
    for (i = 0; i < s.length; i++) { chr = s.charCodeAt(i); h = ((h << 5) - h) + chr; h |= 0; }
    if (h < 0) h = h * -1;
    return 'wsqa6_' + h;
  }

  function cleanText(t){
    return String(t || '').replace(/\\s+/g, ' ').replace(/^\\s+|\\s+$/g,'');
  }

  function addItem(items, parent, label, url, source){
    if (!label || !url) return;
    var id = hashId(parent + '|' + label + '|' + url);
    items.push({ id: id, parent: parent, label: label, url: url, source: source || '' });
  }

  function scrapeAdminMenu(){
    var items = [];
    var menu = document.getElementById('adminmenu');
    if (!menu) return items;
    var lis = menu.children;
    for (var i=0; i<lis.length; i++){
      var li = lis[i];
      if (!li || !li.querySelector) continue;
      var topA = li.querySelector(':scope > a') || li.querySelector('a');
      var parent = cleanText(topA ? topA.textContent : '') || 'Other';
      var subs = li.querySelectorAll('ul.wp-submenu a');
      for (var j=0; j<subs.length; j++){
        var a = subs[j];
        var label = cleanText(a.textContent);
        var url = a.getAttribute('href');
        if (!url || url === '#' || url.indexOf('javascript:') === 0) continue;
        addItem(items, parent, label, url, 'Admin Menu');
      }
    }
    return items;
  }

  function walkObject(obj, out, depth){
    if (!obj || typeof obj !== 'object') return;
    if (depth > 8) return;
    if (typeof obj.title === 'string' && typeof obj.url === 'string') {
      var label = cleanText(obj.title);
      var url = obj.url;
      if (label && url) addItem(out, 'Elementor', label, url, 'Elementor');
    }
    for (var k in obj){
      if (!Object.prototype.hasOwnProperty.call(obj, k)) continue;
      var v = obj[k];
      if (v && typeof v === 'object') walkObject(v, out, depth + 1);
    }
  }

  function scrapeElementorGlobals(){
    var out = [];
    var candidates = [ window.elementorCommonConfig, window.elementorAppProConfig, window.elementor ];
    for (var i=0; i<candidates.length; i++){
      try { walkObject(candidates[i], out, 0); } catch(e){}
    }
    return out;
  }

  function uniqById(arr){
    var seen = {};
    var out = [];
    for (var i=0; i<arr.length; i++){
      var it = arr[i];
      if (!it || !it.id) continue;
      if (seen[it.id]) continue;
      seen[it.id] = true;
      out.push(it);
    }
    return out;
  }

  $('#wsqa6-scan').on('click', function(e){
    e.preventDefault();
    var btn = $(this);
    btn.prop('disabled', true).text('Scanning…');
    try {
      var items = [];
      items = items.concat(scrapeAdminMenu());
      items = items.concat(scrapeElementorGlobals());
      items = uniqById(items);
      $.post('{$ajax}', {
        action: '".self::AJAX_ACTION."',
        _ajax_nonce: '{$nonce}',
        items_json: JSON.stringify(items)
      }).done(function(resp){
        if (resp && resp.success) {
          window.location.reload();
        } else {
          alert('Scan failed.');
        }
      }).fail(function(){
        alert('Scan failed.');
      }).always(function(){
        btn.prop('disabled', false).text('Scan Now');
      });
    } catch(err) {
      btn.prop('disabled', false).text('Scan Now');
    }
  });

  syncOrder();
});
";
		wp_add_inline_script('jquery-ui-sortable', $js);

		$css = "
.wsqa6-grid{ display:grid; grid-template-columns: 1fr 1fr; gap:16px; max-width:1200px; }
@media (max-width: 960px){ .wsqa6-grid{ grid-template-columns:1fr; } }
.wsqa6-panel{ background:#fff; border:1px solid #ccd0d4; border-radius:14px; padding:14px; }
#wsqa6-selected{ list-style:none; margin:0; padding:0; }
#wsqa6-selected li{
  display:flex; align-items:center; gap:10px;
  padding:10px 12px; margin:8px 0;
  border:1px solid #dcdcde; border-radius:12px; background:#fff;
}
.wsqa6-handle{ cursor:grab; user-select:none; font-size:16px; color:#50575e; }
.wsqa6-sel-text{ flex:1; font-weight:600; }
.wsqa6-remove{
  border:1px solid #d0d7de; background:#fff; border-radius:10px;
  width:32px; height:32px; cursor:pointer; font-weight:800; color:#b32d2e;
}
.wsqa6-remove:hover{ background:#f6f7f7; }
.wsqa6-details{ border:1px solid #e5e7eb; border-radius:12px; padding:10px; margin:10px 0; }
.wsqa6-details summary{ cursor:pointer; font-weight:700; }
.wsqa6-item{ display:block; padding:10px; border:1px solid #e5e7eb; border-radius:12px; margin:8px 0; }
";
		wp_add_inline_style('common', $css);
	}

	public static function render_settings_page() {
		if (!current_user_can('read')) return;

		$catalog  = self::get_catalog();   // hardened
		$selected = self::get_selected();  // hardened

		$clean = [];
		foreach ($selected as $id) {
			if (is_string($id) && $id !== '' && isset($catalog[$id]) && is_array($catalog[$id])) {
				$clean[] = $id;
			}
		}
		$selected = $clean;
		?>
		<div class="wrap">
			<h1>Quick Access (Dashboard Only)</h1>
			<form method="post">
				<?php wp_nonce_field(self::NONCE_ACTION, '_wsqa6_nonce'); ?>
				<input type="hidden" id="wsqa6_order" name="wsqa6_order" value="" />
				<div class="wsqa6-grid">
					<div class="wsqa6-panel">
						<h2 style="margin-top:0;">Selected</h2>
						<ul id="wsqa6-selected">
							<?php if (!$selected): ?>
								<li style="opacity:.75;">Nothing selected yet.</li>
							<?php else: ?>
								<?php foreach ($selected as $id): ?>
									<?php
									$it = isset($catalog[$id]) && is_array($catalog[$id]) ? self::sanitize_item($catalog[$id]) : null;
									if (!$it) continue;
									?>
									<li class="wsqa6-sel" data-id="<?php echo esc_attr($id); ?>">
										<span class="wsqa6-handle">☰</span>
										<span class="wsqa6-sel-text"><strong><?php echo esc_html($it['parent']); ?></strong> — <?php echo esc_html($it['label']); ?></span>
										<button type="button" class="wsqa6-remove">✕</button>
									</li>
								<?php endforeach; ?>
							<?php endif; ?>
						</ul>
						<p><button type="submit" class="button button-primary" name="wsqa6_save" value="1">Save</button></p>
					</div>

					<div class="wsqa6-panel">
						<div style="display:flex; align-items:center; justify-content:space-between;">
							<h2>Available links</h2>
							<button class="button button-secondary" id="wsqa6-scan" type="button">Scan Now</button>
						</div>
						<div id="wsqa6-catalog">
							<?php if (!empty($catalog)): ?>
								<?php
								$groups = [];
								foreach ($catalog as $id => $raw) {
									if (!is_array($raw)) continue;
									$it = self::sanitize_item($raw);
									if (!$it) continue;

									$p = !empty($it['parent']) ? $it['parent'] : 'Other';
									if (!isset($groups[$p])) $groups[$p] = [];
									$groups[$p][$id] = $it;
								}
								ksort($groups);

								foreach ($groups as $parent => $items) :
								?>
								<details class="wsqa6-details">
									<summary><?php echo esc_html($parent); ?></summary>
									<div style="margin-top:10px;">
										<?php foreach ($items as $id => $it): ?>
											<label class="wsqa6-item">
												<input
													type="checkbox"
													name="wsqa6_pick[]"
													value="<?php echo esc_attr($id); ?>"
													<?php checked(in_array($id, $selected, true)); ?>
													data-parent="<?php echo esc_attr($it['parent']); ?>"
													data-label="<?php echo esc_attr($it['label']); ?>"
												/>
												<strong><?php echo esc_html($it['label']); ?></strong>
											</label>
										<?php endforeach; ?>
									</div>
								</details>
								<?php endforeach; ?>
							<?php endif; ?>
						</div>
					</div>

				</div>
			</form>
		</div>
		<?php
	}

	public static function handle_save() {
		if (!isset($_POST['wsqa6_save'])) return;

		check_admin_referer(self::NONCE_ACTION, '_wsqa6_nonce');

		$catalog = self::get_catalog(); // hardened
		$picked  = isset($_POST['wsqa6_pick']) ? (array) $_POST['wsqa6_pick'] : [];
		$picked  = array_values(array_filter(array_map('sanitize_text_field', $picked)));

		$order_raw = isset($_POST['wsqa6_order']) ? sanitize_text_field($_POST['wsqa6_order']) : '';
		$order = array_values(array_filter(explode(',', $order_raw)));

		$final = [];
		foreach ($order as $id) {
			if (in_array($id, $picked, true) && isset($catalog[$id]) && is_array($catalog[$id])) $final[] = $id;
		}
		foreach ($picked as $id) {
			if (!in_array($id, $final, true) && isset($catalog[$id]) && is_array($catalog[$id])) $final[] = $id;
		}

		update_user_meta(get_current_user_id(), self::META_SELECTED, $final);
		wp_safe_redirect(add_query_arg(['page'=>self::PAGE_SLUG,'updated'=>'1'], admin_url('options-general.php')));
		exit;
	}

	/**
	 * Build a robust catalog from WordPress registered admin menu arrays ($menu / $submenu).
	 */
	private static function build_wp_admin_menu_items() {
		if ( ! is_admin() ) return [];

		global $menu, $submenu;
		$out = [];

		if ( ! is_array( $menu ) ) return $out;

		foreach ( $menu as $m ) {
			if ( ! is_array( $m ) || empty( $m[2] ) ) continue;

			$parent_slug = (string) $m[2];
			$parent_cap  = isset( $m[1] ) ? (string) $m[1] : 'read';

			$parent_label = isset( $m[0] ) ? wp_strip_all_tags( (string) $m[0] ) : '';
			$parent_label = trim( preg_replace( '/\s+/', ' ', $parent_label ) );

			if ( in_array($parent_slug, ['separator1','separator2','separator-last'], true) ) continue;
			if ( $parent_label === '' ) continue;
			if ( ! current_user_can( $parent_cap ) ) continue;

			if ( isset( $submenu[ $parent_slug ] ) && is_array( $submenu[ $parent_slug ] ) ) {
				foreach ( $submenu[ $parent_slug ] as $sm ) {
					if ( ! is_array( $sm ) || empty( $sm[2] ) ) continue;

					$label = isset( $sm[0] ) ? wp_strip_all_tags( (string) $sm[0] ) : '';
					$label = trim( preg_replace( '/\s+/', ' ', $label ) );
					if ( $label === '' ) continue;

					$cap = isset( $sm[1] ) ? (string) $sm[1] : $parent_cap;
					if ( ! current_user_can( $cap ) ) continue;

					$url = self::normalize_admin_url( (string) $sm[2] );
					if ( ! $url ) continue;

					$out[] = self::make_item( $parent_label, $label, $url, 'Admin Menu', $cap );
				}
			}
		}

		$out = array_merge( $out, self::build_extra_admin_links() );
		return $out;
	}

	/**
	 * Extra links for plugin UIs that don't register in WP's left admin menu ($submenu).
	 */
	private static function build_extra_admin_links() {
		$out = [];

		// Elementor "Custom Code" uses CPT elementor_snippet.
		if ( post_type_exists( 'elementor_snippet' ) ) {
			$pto = get_post_type_object( 'elementor_snippet' );
			$cap = ( $pto && ! empty( $pto->cap->edit_posts ) ) ? $pto->cap->edit_posts : 'edit_posts';

			if ( current_user_can( $cap ) ) {
				$out[] = self::make_item(
					'Elementor',
					'Custom Code',
					self::normalize_admin_url( 'edit.php?post_type=elementor_snippet' ),
					'Elementor',
					$cap
				);
			}
		}

		// Elementor Templates CPT.
		if ( post_type_exists( 'elementor_library' ) ) {
			$pto = get_post_type_object( 'elementor_library' );
			$cap = ( $pto && ! empty( $pto->cap->edit_posts ) ) ? $pto->cap->edit_posts : 'edit_posts';
			if ( current_user_can( $cap ) ) {
				$out[] = self::make_item(
					'Elementor',
					'Templates',
					self::normalize_admin_url( 'edit.php?post_type=elementor_library' ),
					'Elementor',
					$cap
				);
			}
		}

		return $out;
	}

	/**
	 * Normalize an admin URL/slug to an absolute URL.
	 */
	private static function normalize_admin_url( $url ) {
		$url = trim( (string) $url );
		if ( $url === '' ) return '';
		if ( $url === '#' ) return '';
		if ( stripos( $url, 'javascript:' ) === 0 ) return '';
		if ( preg_match( '#^https?://#i', $url ) ) return $url;
		return admin_url( ltrim( $url, '/' ) );
	}

	private static function make_item( $parent, $label, $url, $source, $cap = 'read' ) {
		$parent = sanitize_text_field( (string) $parent );
		$label  = sanitize_text_field( (string) $label );
		$url    = esc_url_raw( (string) $url );
		$source = sanitize_text_field( (string) $source );
		$cap    = sanitize_text_field( (string) $cap );

		$id = substr( md5( $source . '|' . $url . '|' . $label ), 0, 12 );

		return [
			'id'     => $id,
			'parent' => $parent ?: 'Other',
			'label'  => $label ?: $url,
			'url'    => $url,
			'source' => $source,
			'cap'    => $cap ?: 'read',
		];
	}

	/**
	 * Merge posted items (from JS scanners) with server-side WP menu items, then save.
	 */
	private static function build_merged_catalog_from_request( $items ) {
		$catalog = [];

		foreach ( self::build_wp_admin_menu_items() as $it ) {
			if ( empty( $it['id'] ) ) continue;
			$catalog[ $it['id'] ] = $it;
		}

		if ( is_array( $items ) ) {
			foreach ( $items as $it ) {
				if ( ! is_array( $it ) ) continue;

				$parent = isset( $it['parent'] ) ? sanitize_text_field( (string) $it['parent'] ) : 'Other';
				$label  = isset( $it['label'] ) ? sanitize_text_field( (string) $it['label'] ) : '';
				$url    = isset( $it['url'] ) ? self::normalize_admin_url( (string) $it['url'] ) : '';
				$source = isset( $it['source'] ) ? sanitize_text_field( (string) $it['source'] ) : 'Scan';
				$cap    = isset( $it['cap'] ) ? sanitize_text_field( (string) $it['cap'] ) : 'read';

				if ( $label === '' || $url === '' ) continue;

				$id = substr( md5( $source . '|' . $url . '|' . $label ), 0, 12 );

				if ( ! isset( $catalog[ $id ] ) ) {
					$catalog[ $id ] = [
						'id'     => $id,
						'parent' => $parent ?: 'Other',
						'label'  => $label,
						'url'    => esc_url_raw( $url ),
						'source' => $source,
						'cap'    => $cap ?: 'read',
					];
				}
			}
		}

		return $catalog;
	}

	public static function ajax_scan_save() {
		check_ajax_referer(self::NONCE_ACTION);

		$items = [];
		if ( isset($_POST['items_json']) ) {
			$decoded = json_decode(wp_unslash($_POST['items_json']), true);
			if ( is_array($decoded) ) {
				$items = $decoded;
			}
		}

		$catalog = self::build_merged_catalog_from_request( $items );

		// Force-add extra links every time
		foreach ( self::build_extra_admin_links() as $it ) {
			if ( is_array($it) && !empty($it['id']) ) {
				$catalog[ $it['id'] ] = $it;
			}
		}

		// Final sanitize before saving (prevents corrupt meta from ever being stored)
		$catalog = self::sanitize_catalog($catalog);

		update_user_meta(get_current_user_id(), self::META_CATALOG, $catalog);
		wp_send_json_success();
	}

	/* =========================
	   HARDENING (prevents fatals)
	========================= */

	private static function sanitize_item($it) {
		if (!is_array($it)) return null;

		$id     = isset($it['id']) ? sanitize_text_field((string)$it['id']) : '';
		$parent = isset($it['parent']) ? sanitize_text_field((string)$it['parent']) : 'Other';
		$label  = isset($it['label']) ? sanitize_text_field((string)$it['label']) : '';
		$url    = isset($it['url']) ? (string)$it['url'] : '';
		$source = isset($it['source']) ? sanitize_text_field((string)$it['source']) : '';
		$cap    = isset($it['cap']) ? sanitize_text_field((string)$it['cap']) : 'read';

		$url = self::normalize_admin_url($url);

		if ($id === '' || $label === '' || $url === '') return null;

		return [
			'id'     => $id,
			'parent' => $parent !== '' ? $parent : 'Other',
			'label'  => $label,
			'url'    => $url,
			'source' => $source,
			'cap'    => $cap !== '' ? $cap : 'read',
		];
	}

	private static function sanitize_catalog($raw) {
		// Handle JSON-string meta from older versions
		if (is_string($raw)) {
			$maybe = json_decode($raw, true);
			if (is_array($maybe)) $raw = $maybe;
		}
		if (!is_array($raw)) return [];

		$clean = [];
		foreach ($raw as $key => $it) {
			if (!is_array($it)) continue;
			$san = self::sanitize_item($it);
			if (!$san) continue;
			$clean[$san['id']] = $san;
		}
		return $clean;
	}

	private static function get_catalog() {
		$raw = get_user_meta(get_current_user_id(), self::META_CATALOG, true);
		return self::sanitize_catalog($raw);
	}

	private static function get_selected() {
		$raw = get_user_meta(get_current_user_id(), self::META_SELECTED, true);

		if (is_string($raw)) {
			$maybe = json_decode($raw, true);
			if (is_array($maybe)) $raw = $maybe;
		}
		if (!is_array($raw)) return [];

		$out = [];
		foreach ($raw as $v) {
			$v = sanitize_text_field((string)$v);
			if ($v !== '') $out[] = $v;
		}
		return $out;
	}
}

WSQA_Dashboard_Only_V6::init();
				
			

extract-urls

				
					/**
 * Admin Tools -> Export URLs (CSV) for all public post types.
 */
add_action('admin_menu', function () {
  add_management_page(
    'Export URLs',
    'Export URLs',
    'manage_options',
    'export-all-urls',
    'ws_export_all_urls_page'
  );
});

function ws_export_all_urls_page() {
  if (!current_user_can('manage_options')) return;

  $download_url = wp_nonce_url(
    admin_url('tools.php?page=export-all-urls&ws_export_urls=1'),
    'ws_export_urls'
  );

  echo '<div class="wrap">';
  echo '<h1>Export URLs</h1>';
  echo '<p>Download a CSV containing URLs for all <strong>public post types</strong> (posts, pages, products, and custom post types).</p>';
  echo '<p><a class="button button-primary" href="' . esc_url($download_url) . '">Download CSV</a></p>';
  echo '</div>';
}

add_action('admin_init', function () {
  if (empty($_GET['ws_export_urls'])) return;
  if (!current_user_can('manage_options')) return;
  check_admin_referer('ws_export_urls');

  // Get all public post types (includes custom post types like products, FAQs, etc.)
  $post_types = get_post_types(['public' => true], 'names');

  // Query all published posts across all those types
  $q = new WP_Query([
    'post_type'      => array_values($post_types),
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'fields'         => 'ids',
    'no_found_rows'  => true,
  ]);

  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=all-urls-' . date('Y-m-d') . '.csv');

  $out = fopen('php://output', 'w');
  fputcsv($out, ['ID', 'post_type', 'post_title', 'status', 'date', 'url']);

  foreach ($q->posts as $post_id) {
    fputcsv($out, [
      $post_id,
      get_post_type($post_id),
      html_entity_decode(get_the_title($post_id), ENT_QUOTES, 'UTF-8'),
      get_post_status($post_id),
      get_post_time('Y-m-d H:i:s', true, $post_id),
      get_permalink($post_id),
    ]);
  }

  fclose($out);
  exit;
});

				
			

disable-right-click

				
					-- Add to Custom Code 
-- Set to body-end

<script type="text/phast">document.addEventListener('contextmenu', event => event.preventDefault());</script>
				
			

The Settings Pack - Code Snippets

Last Updated Wednesday 17th July 2024

Code Snippets Bundle

The Bundle contains 22 Snippets that improve Performance of your website, and add Admin Controls. You can import them all in one go rather than copying and pasting individually.

You will need the Free Code Snippets Plugin.

Before adding New Snippets

  1. Always take a Backup
  2. Preferably Export a Full Backup
  3. Test on a Staging Site.
 

Click to download the Bundle OR Scroll down to see each individual snippet and add individually.

1) Unzip the File.

2) Go to WordPress Dashboard > Snippets > Import

3) The snippets will be added in ‘Deactivated’ form so you can manually activate them depending on your choice.

Go to Upload Files, and choose the unzipped file: elementor.code-snippets.json

Click the ‘Upload files and import’

If you are adding the Bundle again after it’s been updated with new snippets, then select the 3rd option to not import any duplicate snippets.

Then go to All Snippets and decide on which Snippets to Activate.

Activate and check one at a time.

				
					add_action( 'init', 'add_categories_to_pages' );
 /*
  * Add CATEGORIES to pages
  */
function add_categories_to_pages() {
  
  register_taxonomy_for_object_type( 'category', 'page' );
  
}
				
			
				
					// Add the Contrast Checker Menu
add_action('admin_menu', 'contrast_checker_menu');
add_action('admin_init', 'contrast_checker_settings');

function contrast_checker_menu() {
    add_options_page('Contrast Checker', 'Contrast Checker', 'manage_options', 'contrast-checker', 'contrast_checker_page');
}

function contrast_checker_settings() {
    add_settings_section('contrast_checker_section', 'Contrast Checker Settings', null, 'contrast-checker');

    add_settings_field('background_color', 'Background Color', 'background_color_callback', 'contrast-checker', 'contrast_checker_section');
    add_settings_field('text_color', 'Foreground Color', 'foreground_color_callback', 'contrast-checker', 'contrast_checker_section');

    register_setting('contrast_checker_group', 'background_color');
    register_setting('contrast_checker_group', 'text_color');
}

function background_color_callback() {
    $background_color = get_option('background_color', '#FFFFFF');
    echo '<div style="display: flex; align-items: center;"><input type="text" id="background_color" name="background_color" value="' . esc_attr($background_color) . '" class="my-color-field" style="font-size: 15px !important;" />';
    echo '<span id="background_color_hex" style="margin-left: 10px; font-size: 15px;">' . esc_attr($background_color) . '</span></div>';
}

function foreground_color_callback() {
    $foreground_color = get_option('text_color', '#000000');
    echo '<div style="display: flex; align-items: center;"><input type="text" id="text_color" name="text_color" value="' . esc_attr($foreground_color) . '" class="my-color-field" style="font-size: 15px !important;" />';
    echo '<span id="text_color_hex" style="margin-left: 10px; font-size: 15px;">' . esc_attr($foreground_color) . '</span></div>';
}

function contrast_checker_page() {
    ?>
    <div class="wrap" style="font-size: 15px; line-height: 1.2em; background-color: #ffffff; padding: 20px; border-radius: 5px;">
        <h1 style="font-size: 20px; line-height: 1.2em;">Contrast Checker</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields('contrast_checker_group');
            do_settings_sections('contrast-checker');
            submit_button('Save Colors', 'primary', 'submit', true, array('style' => 'background-color: #000; font-size: 16px; font-weight: 600;'));
            ?>
        </form>
        <div id="contrast-result" style="margin-top: 20px;"></div>
        <div style="margin-top: 20px; font-size: 15px; line-height: 1.2em;">
            <h2 style="font-size: 15px; line-height: 1.2em;">What is AA?</h2>
            <p style="font-size: 15px; line-height: 1.2em;">AA compliance refers to the Web Content Accessibility Guidelines (WCAG) 2.1, which require a contrast ratio of at least 4.5:1 for normal text (minimum 16px) and 3:1 for large text (minimum 24px or 19px bold). This ensures that content is readable and accessible for individuals with moderate visual impairments.</p>
            <h2 style="font-size: 15px; line-height: 1.2em;">What is AAA?</h2>
            <p style="font-size: 15px; line-height: 1.2em;">AAA compliance is the highest level of conformance in WCAG 2.1. It requires a contrast ratio of at least 7:1 for normal text (minimum 16px) and 4.5:1 for large text (minimum 24px or 19px bold). Achieving AAA compliance ensures that content is accessible to the widest range of users, including those with significant visual impairments.</p>
        </div>
    </div>
    <style>.my-color-field{font-size:15px !important;}.contrast-pass-yes{color:#007E33;font-weight:600;}.contrast-pass-no{color:#E60000;font-weight:600;}</style>
    <?php
}

// Enqueue the color picker script and add inline script
add_action('admin_enqueue_scripts', 'contrast_checker_enqueue_scripts');
function contrast_checker_enqueue_scripts($hook_suffix) {
    if ($hook_suffix != 'settings_page_contrast-checker') {
        return;
    }
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
    wp_add_inline_script('wp-color-picker', '
        jQuery(document).ready(function($) {
            function updateContrast() {
                var bgColor = $("#background_color").val();
                var txtColor = $("#text_color").val();

                $.ajax({
                    url: ajaxurl,
                    type: "POST",
                    data: {
                        action: "check_contrast",
                        bg_color: bgColor,
                        txt_color: txtColor
                    },
                    success: function(response) {
                        if (response.success) {
                            $("#contrast-result").html(response.data);
                        }
                    }
                });
            }

            $(".my-color-field").wpColorPicker({
                defaultColor: {
                    background_color: "#FFFFFF",
                    text_color: "#000000"
                },
                change: function(event, ui) {
                    var color = ui.color.toString();
                    if (event.target.id === "background_color") {
                        $("#background_color_hex").text(color);
                    } else if (event.target.id === "text_color") {
                        $("#text_color_hex").text(color);
                    }
                    updateContrast();
                }
            });

            // Initial contrast check
            updateContrast();
        });
    ');
}

// AJAX handler for checking contrast
add_action('wp_ajax_check_contrast', 'ajax_check_contrast');
function ajax_check_contrast() {
    $bg_color = sanitize_hex_color($_POST['bg_color']);
    $txt_color = sanitize_hex_color($_POST['txt_color']);
    $result = check_contrast($bg_color, $txt_color);
    wp_send_json_success($result);
}

function check_contrast($bg_hex, $txt_hex) {
    $bg_rgb = hex_to_rgb($bg_hex);
    $txt_rgb = hex_to_rgb($txt_hex);

    $bg_luminance = luminance($bg_rgb);
    $txt_luminance = luminance($txt_rgb);

    $contrast_ratio = contrast_ratio($bg_luminance, $txt_luminance);
    $aa_pass = ($contrast_ratio >= 4.5) ? '<span class="contrast-pass-yes">Yes</span>' : '<span class="contrast-pass-no">No</span>';
    $aaa_pass = ($contrast_ratio >= 7) ? '<span class="contrast-pass-yes">Yes</span>' : '<span class="contrast-pass-no">No</span>';

    $suggested_aa = adjust_foreground_color($bg_rgb, $txt_rgb, 4.5);
    $suggested_aaa = adjust_foreground_color($bg_rgb, $txt_rgb, 7);

    return '
        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
            <div style="background-color: ' . esc_attr($bg_hex) . '; width: 20px; height: 20px; border: 1px solid #000;"></div>
            <div style="background-color: ' . esc_attr($txt_hex) . '; width: 20px; height: 20px; border: 1px solid #000;"></div>
        </div>
        <div style="font-size: 15px; line-height: 1.2em;">
            <div style="margin-bottom: 5px;"><strong>Contrast Ratio:</strong> ' . round($contrast_ratio, 2) . '</div>
            <div style="margin-bottom: 5px;"><strong>AA Compliant:</strong> ' . $aa_pass . '</div>
            <div style="margin-bottom: 5px;"><strong>AAA Compliant:</strong> ' . $aaa_pass . '</div>
        </div>
        <div style="margin-top: 20px; font-size: 15px; line-height: 1.2em;">
            <div style="margin-bottom: 20px;">
                <strong>Suggested Foreground Color for AA:</strong>
                <span style="background-color: ' . $suggested_aa . '; width: 20px; height: 20px; display: inline-block; border: 1px solid #000;"></span> ' . $suggested_aa . '
            </div>
            <div>
                <strong>Suggested Foreground Color for AAA:</strong>
                <span style="background-color: ' . $suggested_aaa . '; width: 20px; height: 20px; display: inline-block; border: 1px solid #000;"></span> ' . $suggested_aaa . '
            </div>
        </div>';
}

function hex_to_rgb($hex) {
    $hex = ltrim($hex, '#');
    $r = hexdec(substr($hex, 0, 2)) / 255;
    $g = hexdec(substr($hex, 2, 2)) / 255;
    $b = hexdec(substr($hex, 4, 2)) / 255;
    return array($r, $g, $b);
}

function rgb_to_hex($rgb) {
    return sprintf("#%02x%02x%02x", round($rgb[0] * 255), round($rgb[1] * 255), round($rgb[2] * 255));
}

function luminance($rgb) {
    list($r, $g, $b) = $rgb;
    $r = ($r <= 0.03928) ? $r / 12.92 : pow(($r + 0.055) / 1.055, 2.4);
    $g = ($g <= 0.03928) ? $g / 12.92 : pow(($g + 0.055) / 1.055, 2.4);
    $b = ($b <= 0.03928) ? $b / 12.92 : pow(($b + 0.055) / 1.055, 2.4);
    return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
}

function contrast_ratio($l1, $l2) {
    $lighter = max($l1, $l2);
    $darker = min($l1, $l2);
    return ($lighter + 0.05) / ($darker + 0.05);
}

function adjust_foreground_color($bg_rgb, $txt_rgb, $target_ratio) {
    $bg_luminance = luminance($bg_rgb);
    $step = 0.02; // Adjust step value for precision and performance

    // Incrementally adjust the RGB values to find a compliant color
    for ($i = 0; $i <= 1; $i += $step) {
        $test_rgb = adjust_rgb_lightness($txt_rgb, $i);
        $test_luminance = luminance($test_rgb);
        if (contrast_ratio($test_luminance, $bg_luminance) >= $target_ratio) {
            return rgb_to_hex($test_rgb);
        }

        $test_rgb = adjust_rgb_lightness($txt_rgb, -$i);
        $test_luminance = luminance($test_rgb);
        if (contrast_ratio($test_luminance, $bg_luminance) >= $target_ratio) {
            return rgb_to_hex($test_rgb);
        }
    }

    return "#000000"; // fallback to black if no suitable color found
}

function adjust_rgb_lightness($rgb, $adjustment) {
    return array(
        min(1, max(0, $rgb[0] + $adjustment)),
        min(1, max(0, $rgb[1] + $adjustment)),
        min(1, max(0, $rgb[2] + $adjustment))
    );
}

				
			
				
					// Disable user registration
add_filter('pre_option_users_can_register', '__return_zero');

				
			
				
					/**
 * Duplicate WordPress Posts, Pages, and Custom Post Types as Drafts
 *
 * This code snippet enables the duplication of WordPress posts, pages, and all registered custom post types (CPTs).
 * It adds a 'Duplicate' link to the row actions for each item in the admin dashboard. When clicked, this link
 * triggers the duplication of the selected item, creating a new draft with the same content, custom fields,
 * and taxonomies.
 *
 * Functions:
 * 1. `duplicate_post_as_draft`: Handles the duplication process. It copies the post data, including title,
 *    content, excerpt, and custom fields, and creates a new post with a 'draft' status. It also maintains
 *    the taxonomy terms (like categories and tags) from the original post.
 * 2. `duplicate_post_link`: Adds the 'Duplicate' action link to the WordPress admin interface for each post,
 *    page, and custom post type. This link uses WordPress's built-in nonce functionality for security.
 * 3. `apply_duplicate_post_link_to_cpts`: Dynamically applies the duplicate post link function to all public
 *    post types, ensuring the 'Duplicate' link appears for any custom post types registered on the site.
 *
 * Author: Mark Harris
 * URI: https://www.christchurchwebsolutions.co.uk
 */

function duplicate_post_as_draft() {
    global $wpdb;

    // Verify the nonce for security
    $nonce_action = 'duplicate_post_as_draft';
    $nonce_name = 'duplicate_nonce';
    if (!isset($_GET[$nonce_name]) || !wp_verify_nonce($_GET[$nonce_name], $nonce_action)) {
        wp_die(esc_html__('Security check failed.', 'wpturbo'));
    }

    // Check if the 'post' parameter is set in either GET or POST request
    $post_id = filter_input(INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT) ?: filter_input(INPUT_POST, 'post', FILTER_SANITIZE_NUMBER_INT);

    if (!$post_id) {
        wp_die(esc_html__('No post to duplicate has been supplied!', 'wpturbo'));
    }

    // Check if the post exists
    $post = get_post($post_id);
    if (!$post) {
        wp_die(esc_html(sprintf(__('Post creation failed, could not find original post: %s', 'wpturbo'), $post_id)));
    }

    $current_user = wp_get_current_user();
    $new_post_author = $current_user->ID;

    $args = [
        "comment_status" => $post->comment_status,
        "ping_status" => $post->ping_status,
        "post_author" => $new_post_author,
        "post_content" => $post->post_content,
        "post_excerpt" => $post->post_excerpt,
        "post_name" => $post->post_name,
        "post_parent" => $post->post_parent,
        "post_password" => $post->post_password,
        "post_status" => "draft",
        "post_title" => $post->post_title . " (Copy)",
        "post_type" => $post->post_type,
        "to_ping" => $post->to_ping,
        "menu_order" => $post->menu_order
    ];

    $new_post_id = wp_insert_post($args);

    $taxonomies = get_object_taxonomies($post->post_type);
    foreach ($taxonomies as $taxonomy) {
        $post_terms = wp_get_object_terms($post_id, $taxonomy, ["fields" => "slugs"]);
        wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);
    }

    $post_meta_infos = $wpdb->get_results(
        $wpdb->prepare("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id = %d", $post_id)
    );
    if (count($post_meta_infos) != 0) {
        foreach ($post_meta_infos as $meta_info) {
            $meta_key = $meta_info->meta_key;
            $meta_value = sanitize_meta($meta_info->meta_key, $meta_info->meta_value, "post");
            $wpdb->insert($wpdb->postmeta, [
                "post_id" => $new_post_id,
                "meta_key" => $meta_key,
                "meta_value" => $meta_value
            ]);
        }
    }

    // Redirect to the post list screen and show a success message
    $redirect_url = admin_url("edit.php?post_type=" . $post->post_type);
    wp_redirect(add_query_arg("message", "101", $redirect_url));
    exit();
}

add_action("admin_action_duplicate_post_as_draft", "duplicate_post_as_draft");

function duplicate_post_link($actions, $post) {
    if (current_user_can('edit_posts')) {
        $actions['duplicate'] = '<a href="' . 
            wp_nonce_url(
                admin_url("admin.php?action=duplicate_post_as_draft&post=" . $post->ID), 
                'duplicate_post_as_draft', 
                'duplicate_nonce'
            ) . 
            '" title="' . esc_attr__('Duplicate this item', 'wpturbo') . 
            '" rel="permalink">' . esc_html__('Duplicate', 'wpturbo') . '</a>';
    }
    return $actions;
}

add_filter("post_row_actions", "duplicate_post_link", 10, 2);
add_filter("page_row_actions", "duplicate_post_link", 10, 2);

function apply_duplicate_post_link_to_cpts() {
    $post_types = get_post_types(["public" => true], "names");
    foreach ($post_types as $post_type) {
        add_filter("{$post_type}_row_actions", "duplicate_post_link", 10, 2);
    }
}

add_action("admin_init", "apply_duplicate_post_link_to_cpts");

function show_duplicate_admin_notice() {
    if (isset($_GET['message']) && $_GET['message'] === '101') {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html('Post duplicated successfully.') . '</p></div>';
    }
}

add_action('admin_notices', 'show_duplicate_admin_notice');
				
			
				
					// Function to add the calculator to the admin menu
function ft_calculator_admin_menu()
{
    add_menu_page(
        "Fluid Typography Calculator", // Page title
        "Clamp Calculator", // Menu title
        "manage_options", // Capability
        "fluid-typography-calculator", // Menu slug
        "ft_calculator_page" // Function that displays the page content
    );
}

add_action("admin_menu", "ft_calculator_admin_menu");

// Function that generates the calculator page
function ft_calculator_page() {
    // Initialize the $useRem variable at the start of the function
    $useRem = false;

    echo '<div class="wrap"><h1>Fluid Typography Calculator</h1>';

    // Basic styles for the form and output
    echo '<style>.ft-form input[type="number"]{width:100px;padding:8px;margin:4px 0;box-sizing:border-box;border:1px solid #ccc;border-radius:4px;}.ft-form label{font-weight:bold;}.ft-form div{margin-bottom:10px;}.ft-form textarea{width:100%;// Adjust this to your preference height:150px;// Or any height that suits your layout padding:8px;border:1px solid #ccc;border-radius:4px;margin-top:10px;}#cssOutput,#cssVariablesOutput{width:50%;// Makes the textarea take up the full width of its container max-width:50%;// You can adjust this as needed min-width:300px;// Ensures a minimum width padding:8px;border:1px solid #ccc;border-radius:4px;margin-top:10px;}.ft-form button{background-color:#4CAF50;color:white;padding:10px 15px;border:none;border-radius:4px;cursor:pointer;}.ft-form button:hover{background-color:#45a049;}.grid-container{display:grid;grid-template-columns:repeat(5,1fr);gap:10px;}</style>';

// Initialize variables
    $rootFontSize = isset($_POST["rootFontSize"]) ? $_POST["rootFontSize"] : 16;
    $defaultValues = [
        "h1" => [
            "MinWidth" => 380,
            "MinFontSize" => 29,
            "MaxWidth" => 1600,
            "MaxFontSize" => 68,
        ],
        "h2" => [
            "MinWidth" => 380,
            "MinFontSize" => 24,
            "MaxWidth" => 1600,
            "MaxFontSize" => 51,
        ],
        "h3" => [
            "MinWidth" => 380,
            "MinFontSize" => 20,
            "MaxWidth" => 1600,
            "MaxFontSize" => 38,
        ],
        "h4" => [
            "MinWidth" => 380,
            "MinFontSize" => 17,
            "MaxWidth" => 1600,
            "MaxFontSize" => 29,
        ],
        "h5" => [
            "MinWidth" => 380,
            "MinFontSize" => 14,
            "MaxWidth" => 1600,
            "MaxFontSize" => 22,
        ],
        "h6" => [
            "MinWidth" => 380,
            "MinFontSize" => 12,
            "MaxWidth" => 1600,
            "MaxFontSize" => 16,
        ],
        "body" => [
            "MinWidth" => 380,
            "MinFontSize" => 16,
            "MaxWidth" => 1600,
            "MaxFontSize" => 24,
        ],
        "p" => [
            "MinWidth" => 380,
            "MinFontSize" => 16,
            "MaxWidth" => 1600,
            "MaxFontSize" => 24,
        ],
    ];

    $cssOutput = ""; // Initialize traditional CSS output string
    $cssVariablesOutput = ""; // Initialize CSS variables output string

    // Check if form is submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $useRem = isset($_POST["unitToggle"]) && $_POST["unitToggle"] === 'on';
        // Security check using nonce
        if (!isset($_POST["ft_calculator_nonce_field"]) || !wp_verify_nonce($_POST["ft_calculator_nonce_field"], "ft_calculator_action")) {
            echo "<p>Security check failed. Please try again.</p>";
            return;
        }

foreach (["h1", "h2", "h3", "h4", "h5", "h6", "body", "p"] as $tag) {
            $minWidth = $_POST[$tag . "MinWidth"]; // In pixels
            $minFontSizePx = $_POST[$tag . "MinFontSize"]; // In pixels or REM based on $useRem
            $maxWidth = $_POST[$tag . "MaxWidth"]; // In pixels
            $maxFontSizePx = $_POST[$tag . "MaxFontSize"]; // In pixels or REM based on $useRem

            // Handle unit conversion
            if ($useRem) {
                // Convert REM to Pixels for internal calculation
                $minFontSizePx *= $rootFontSize;
                $maxFontSizePx *= $rootFontSize;
            }

            // Convert pixel values to REM for CSS generation
            $minFontSize = $minFontSizePx / $rootFontSize; // In rem
            $maxFontSize = $maxFontSizePx / $rootFontSize; // In rem

            // Convert widths from px to vw (assuming 1rem = rootFontSize px)
            $minWidthVW = $minWidth / $rootFontSize; // In vw
            $maxWidthVW = $maxWidth / $rootFontSize; // In vw

            // Calculate the CSS
            $vwUnit =
                (($maxFontSize - $minFontSize) / ($maxWidthVW - $minWidthVW)) *
                100;
            $constant = $minFontSize - ($vwUnit * $minWidthVW) / 100;

            // Format to a maximum of 5 decimal places
            $vwUnitFormatted = number_format($vwUnit, 5, ".", "");
            $constantFormatted = number_format($constant, 5, ".", "");

            // Add to traditional CSS output
            $cssOutput .=
                "{$tag} {font-size: clamp(" .
                $minFontSize .
                "rem, " .
                $constantFormatted .
                "rem + " .
                $vwUnitFormatted .
                "vw, " .
                $maxFontSize .
                "rem);}\n";

            // Add to CSS variables output
            $cssVariablesOutput .=
                "  --{$tag}-font-size: clamp(" .
                $minFontSize .
                "rem, " .
                $constantFormatted .
                "rem + " .
                $vwUnitFormatted .
                "vw, " .
                $maxFontSize .
                "rem);\n";
        }

        // Wrap CSS variables in a :root selector
        $cssVariablesOutput = ":root {\n" . $cssVariablesOutput . "}\n";
    }

// Display the form
echo '<form class="ft-form" method="post">';
wp_nonce_field("ft_calculator_action", "ft_calculator_nonce_field");

echo '<div>
        <label for="rootFontSize">Root HTML Font Size (px):</label>
        <input type="number" id="rootFontSize" name="rootFontSize" required value="' . htmlspecialchars($rootFontSize) . '">
      </div>
      <div>
        <label for="unitToggle">Use REM Units for Font Size:</label>
        <input type="checkbox" id="unitToggle" name="unitToggle" ' . ($useRem ? 'checked' : '') . ' onchange="toggleUnits()">
      </div>';

echo '<div class="grid-container">
        <div><strong>Tag</strong></div>
        <div><strong>Min Width (px)</strong></div>
        <div><strong>Min Font Size (' . ($useRem ? 'rem' : 'px') . ')</strong></div>
        <div><strong>Max Width (px)</strong></div>
        <div><strong>Max Font Size (' . ($useRem ? 'rem' : 'px') . ')</strong></div>';

// Display input fields for each tag
foreach (["h1", "h2", "h3", "h4", "h5", "h6", "body", "p"] as $tag) {
    $minWidthValue = isset($_POST[$tag . "MinWidth"]) ? $_POST[$tag . "MinWidth"] : $defaultValues[$tag]["MinWidth"];
    $minFontSizeValue = isset($_POST[$tag . "MinFontSize"]) ? $_POST[$tag . "MinFontSize"] : $defaultValues[$tag]["MinFontSize"];
    $maxWidthValue = isset($_POST[$tag . "MaxWidth"]) ? $_POST[$tag . "MaxWidth"] : $defaultValues[$tag]["MaxWidth"];
    $maxFontSizeValue = isset($_POST[$tag . "MaxFontSize"]) ? $_POST[$tag . "MaxFontSize"] : $defaultValues[$tag]["MaxFontSize"];

echo "<div><strong>{$tag}</strong></div>
          <div><input type='number' id='{$tag}MinWidth' name='{$tag}MinWidth' class='unit-input' required value='{$minWidthValue}'></div>
          <div><input type='number' id='{$tag}MinFontSize' name='{$tag}MinFontSize' class='unit-input' step='0.01' required value='{$minFontSizeValue}'></div>
          <div><input type='number' id='{$tag}MaxWidth' name='{$tag}MaxWidth' class='unit-input' required value='{$maxWidthValue}'></div>
          <div><input type='number' id='{$tag}MaxFontSize' name='{$tag}MaxFontSize' class='unit-input' step='0.01' required value='{$maxFontSizeValue}'></div>";
}


echo '</div><input type="submit" value="Generate CSS"></form>';


    // Display the traditional CSS output
    if (!empty($cssOutput)) {
        echo "<h2>Generated CSS:</h2>";
        echo '<textarea id="cssOutput" rows="10">' . htmlspecialchars($cssOutput) . "</textarea><br>";
        echo '<button onclick="copyToClipboard(\'cssOutput\')">Copy CSS</button>';
    }

    // Display the CSS variables output
    if (!empty($cssVariablesOutput)) {
        echo "<h2>Generated CSS Variables:</h2>";
        echo '<textarea id="cssVariablesOutput" rows="10">' . htmlspecialchars($cssVariablesOutput) . "</textarea><br>";
        echo '<button onclick="copyToClipboard(\'cssVariablesOutput\')">Copy CSS Variables</button>';
    }

    // JavaScript for copy to clipboard functionality and unit conversion
    echo '<script type="text/phast">function copyToClipboard(elementId){var copyText=document.getElementById(elementId);copyText.select();document.execCommand("copy");}
function toggleUnits(){var useRem=document.getElementById("unitToggle").checked;var rootFontSize=parseFloat(document.getElementById("rootFontSize").value);var fontSizeElements=document.querySelectorAll(".unit-input");fontSizeElements.forEach(function(element){if(element.id.endsWith("MinFontSize")||element.id.endsWith("MaxFontSize")){var value=parseFloat(element.value);if(!isNaN(value)){if(useRem){element.value=(value/rootFontSize).toFixed(2);}else{element.value=(value*rootFontSize).toFixed(0);}}}});}</script>';

    echo "</div>";
}


// Define the function for the fluid typography calculator
function fluid_typography_calculator() {
    // Call the existing function to display the fluid typography calculator
    ft_calculator_page();
}

// Add the shortcode
add_shortcode('Fluid_calc', 'fluid_typography_calculator');

				
			
				
					add_filter( 'media_library_infinite_scrolling', '__return_true' );
				
			
				
					function custom_mime_types($mimes) {
    $mimes['woff'] = 'font/woff';
    $mimes['woff2'] = 'font/woff2';
    return $mimes;
}
add_filter('upload_mimes', 'custom_mime_types');

				
			
				
					function limit_image_sizes($sizes) {
    // Keep only the thumbnail size
    return array(
        'thumbnail' => $sizes['thumbnail']
    );
}
add_filter('intermediate_image_sizes_advanced', 'limit_image_sizes');

function set_thumbnail_size() {
    // Set the thumbnail size to 150x150
    update_option('thumbnail_size_w', 150);
    update_option('thumbnail_size_h', 150);
    update_option('thumbnail_crop', 1); // 1 for hard crop, 0 for soft crop
}
add_action('admin_init', 'set_thumbnail_size');

// Remove the unnecessary regenerate_thumbnails function as the thumbnail is already handled

				
			
				
					function restrict_plugins_page() {
    // Check if the current user is trying to access the Plugins page
    global $pagenow;
    if ($pagenow === 'plugins.php' || strpos($_SERVER['REQUEST_URI'], 'plugin-install.php') !== false || strpos($_SERVER['REQUEST_URI'], 'plugin-editor.php') !== false) {
        
        // Start a session if not already started
        if (!session_id()) {
            session_start();
        }
        
        // SET THE PASSWORD HERE !!
        $required_password = '123'; // Change this to your desired password
        
        // Check if the password has been submitted and is correct
        if (isset($_POST['plugins_password']) && $_POST['plugins_password'] === $required_password) {
            $_SESSION['plugins_access_granted'] = true;
        }
        
        // Check if the session variable is not set, meaning access is not granted
        if (empty($_SESSION['plugins_access_granted'])) {
            // Display the password form
            echo '<form method="post" action="">
                <p>Enter the password to access the Plugins page:</p>
                <input type="password" name="plugins_password" />
                <input type="submit" value="Submit" />
            </form>';
            
            // Prevent the rest of the Plugins page from loading
            exit;
        }
    }
}
add_action('admin_init', 'restrict_plugins_page');

				
			
				
					function restrict_settings_page() {
    // Check if the current user is trying to access the Settings page
    global $pagenow;
    $settings_pages = array(
        'options-general.php',
        'options-writing.php',
        'options-reading.php',
        'options-discussion.php',
        'options-media.php',
        'options-permalink.php',
        // Add more settings pages if you have plugins that add their own settings
    );

    if (in_array($pagenow, $settings_pages)) {
        
        // Start a session if not already started
        if (!session_id()) {
            session_start();
        }
        
        // Set the password
        $required_password = '123'; // Change this to your desired password
        
        // Check if the password has been submitted and is correct
        if (isset($_POST['settings_password']) && $_POST['settings_password'] === $required_password) {
            $_SESSION['settings_access_granted'] = true;
        }
        
        // Check if the session variable is not set, meaning access is not granted
        if (empty($_SESSION['settings_access_granted'])) {
            // Display the password form
            echo '<form method="post" action="">
                <p>Enter the password to access the Settings page:</p>
                <input type="password" name="settings_password" />
                <input type="submit" value="Submit" />
            </form>';
            
            // Prevent the rest of the Settings page from loading
            exit;
        }
    }
}
add_action('admin_init', 'restrict_settings_page');

				
			
				
					if (!function_exists('restrict_snippets_pages')) {
    function restrict_snippets_pages() {
        // Check if the current user is trying to access the Snippets pages
        global $pagenow;
        $restricted_pages = array(
            'admin.php?page=snippets',
            'admin.php?page=snippet-manager',
            'admin.php?page=snippet-import',
            'admin.php?page=add-snippet',
            'admin.php?page=import-code-snippets'
        );

        // Check if the current request URI contains any of the restricted pages
        $is_restricted_page = false;
        foreach ($restricted_pages as $restricted_page) {
            if (strpos($_SERVER['REQUEST_URI'], $restricted_page) !== false) {
                $is_restricted_page = true;
                break;
            }
        }

        if ($is_restricted_page) {
            // Start a session if not already started
            if (!session_id()) {
                session_start();
            }
            
            // SET THE PASSWORD HERE !!
            $required_password = '123'; // Change this to your desired password
            
            // Check if the password has been submitted and is correct
            if (isset($_POST['snippets_password']) && $_POST['snippets_password'] === $required_password) {
                $_SESSION['snippets_access_granted'] = true;
            }
            
            // Check if the session variable is not set, meaning access is not granted
            if (empty($_SESSION['snippets_access_granted'])) {
                // Display the password form
                echo '<form method="post" action="">
                    <p>Enter the password to access the Snippets pages:</p>
                    <input type="password" name="snippets_password" />
                    <input type="submit" value="Submit" />
                </form>';
                
                // Prevent the rest of the Snippets page from loading
                exit;
            }
        }
    }
    add_action('admin_init', 'restrict_snippets_pages');
}

				
			
				
					function restrict_users_page() {
    // Check if the current user is trying to access the Users page
    global $pagenow;
    if ($pagenow === 'users.php' || $pagenow === 'user-new.php' || $pagenow === 'profile.php') {
        
        // Start a session if not already started
        if (!session_id()) {
            session_start();
        }
        
        // Set the password
        $required_password = '123'; // Change this to your desired password
        
        // Check if the password has been submitted and is correct
        if (isset($_POST['users_password']) && $_POST['users_password'] === $required_password) {
            $_SESSION['users_access_granted'] = true;
        }
        
        // Check if the session variable is not set, meaning access is not granted
        if (empty($_SESSION['users_access_granted'])) {
            // Display the password form
            echo '<form method="post" action="">
                <p>Enter the password to access the Users page:</p>
                <input type="password" name="users_password" />
                <input type="submit" value="Submit" />
            </form>';
            
            // Prevent the rest of the Users page from loading
            exit;
        }
    }
}
add_action('admin_init', 'restrict_users_page');

				
			
				
					if ( ! function_exists( 'custom_set_permalink_structure_to_post_name' ) ) {
    /**
     * Sets the default permalink structure to 'Post Name' if it is not already set.
     *
     * To change the default permalink structure, update the `$desired_permalink_structure`
     * variable with one of the following values:
     *
     * - Plain: ''
     * - Day and Name: '/%year%/%monthnum%/%day%/%postname%/'
     * - Month and Name: '/%year%/%monthnum%/%postname%/'
     * - Numeric: '/%post_id%/'
     * - Post Name: '/%postname%/'
     * - Custom Structure: '/your/custom/structure/'
     */
    function custom_set_permalink_structure_to_post_name() {
        // Get the current permalink structure
        $current_permalink_structure = get_option('permalink_structure');

        // Set the desired permalink structure here
        // Default is 'Post Name'
        $desired_permalink_structure = '/%postname%/';

        // Uncomment one of the following lines to set a different permalink structure
        // Plain: 
        // $desired_permalink_structure = '';
        
        // Day and Name: 
        // $desired_permalink_structure = '/%year%/%monthnum%/%day%/%postname%/';
        
        // Month and Name: 
        // $desired_permalink_structure = '/%year%/%monthnum%/%postname%/';
        
        // Numeric: 
        // $desired_permalink_structure = '/%post_id%/';
        
        // Custom Structure: 
        // $desired_permalink_structure = '/your/custom/structure/';

        // Check if the current structure is not already set to the desired structure
        if ($current_permalink_structure != $desired_permalink_structure) {
            // Update the permalink structure
            update_option('permalink_structure', $desired_permalink_structure);
            // Flush rewrite rules to apply the new permalink structure
            flush_rewrite_rules();
        }
    }
    add_action('admin_init', 'custom_set_permalink_structure_to_post_name');
}

				
			
				
					/*
Plugin Name: Purge Cache
Description: Adds a button to the WordPress dashboard to clear the object cache
*/

add_action( 'admin_bar_menu', 'add_purge_cache_button', 999 );

function add_purge_cache_button( $wp_admin_bar ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $args = array(
        'id'    => 'purge-cache',
        'title' => 'Purge Cache',
        'href'  => '#',
        'meta'  => array( 'class' => 'purge-cache' )
    );
    $wp_admin_bar->add_node( $args );
}

add_action( 'admin_footer', 'add_purge_cache_script' );

function add_purge_cache_script() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }
    ?>
    <script type="text/phast">jQuery(document).ready(function($){$('#wp-admin-bar-purge-cache').click(function(){if(confirm('Are you sure you want to purge the cache?')){$.ajax({url:'<?php echo admin_url( 'admin-ajax.php' ); ?>',data:{action:'purge_cache',},success:function(){alert('Cache purged successfully!');},error:function(){alert('An error occurred while purging the cache.');}});}});});</script>
    <?php
}

add_action( 'wp_ajax_purge_cache', 'purge_cache_callback' );

function purge_cache_callback() {
    global $wp_object_cache;
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die();
    }

    wp_cache_flush();

    wp_die();
}
				
			
				
					/*
Comments in WordPress are like an open mic.
Sometimes you want to turn the mic off.
Silencing the comment section might just be your ticket to serenity.*/

function codesnippets_disable_comments() {
    // Remove comment support for posts
    remove_post_type_support( 'post', 'comments' );

    // Remove comment support for pages
    remove_post_type_support( 'page', 'comments' );

    // Remove comments from the admin menu
    remove_menu_page( 'edit-comments.php' );

    // Redirect comment-related URLs to the homepage
    add_action( 'template_redirect', 'codesnippets_disable_comments_redirect' );
}

function codesnippets_disable_comments_redirect() {
    global $wp_query;
    if ( is_single() || is_page() || is_attachment() ) {
        if ( have_comments() || comments_open() ) {
            wp_redirect( home_url(), 301 );
            exit;
        }
    }
}

add_action( 'admin_init', 'codesnippets_disable_comments' );
				
			
				
					function remove_dashboard_widgets() {
    remove_action( 'welcome_panel', 'wp_welcome_panel' );
    remove_meta_box( 'dashboard_right_now', 'dashboard', 'normal' );
    remove_meta_box( 'dashboard_activity', 'dashboard', 'normal' );
    remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' );
    remove_meta_box( 'dashboard_primary', 'dashboard', 'side' );
    remove_meta_box( 'dashboard_site_health', 'dashboard', 'normal' );
	 remove_meta_box( 'e-dashboard-overview', 'dashboard', 'normal' );
}
add_action( 'wp_dashboard_setup', 'remove_dashboard_widgets' );
				
			
				
					add_action('save_post', function ($post_id, $post, $update) {
    // Check if the post is an instance of Elementor's Kit
    if ('elementor_library' === get_post_type($post_id) && 'kit' === get_post_meta($post_id, '_elementor_template_type', true)) {
        $meta = get_post_meta($post_id, '_elementor_page_settings', true);

        // Handle custom colors
        if (!empty($meta['custom_colors'])) {
            foreach ($meta['custom_colors'] as &$custom_color) {
                // Replace the hyphens inside of titles with underscores to ensure consistency
                $custom_color['_id'] = str_replace('-', '_', sanitize_title($custom_color['title']));
            }
        }

        // Update post meta
        update_post_meta($post_id, '_elementor_page_settings', $meta);
    }
}, 10, 3);

				
			
				
					define('WP_POST_REVISIONS', 3);
				
			

This comes in 3 parts.

  1. HTML Widget for the Toggle, adjust the CSS for styling. Place in your Header Template or anywhere else on your site.
  2. Add the Code Snippet to Code Snippets.
  3. Use the CSS as an example of how to style for the Light and Dark Mode. Note that using the Custom Global Colours CSS will help with using Custom Colours. The CSS should be added to Site Settings or any Customised CSS area.

Part 1: The HTML

				
					<div class="mode-toggle">
  <input type="checkbox" id="mode-switch" aria-label="Toggle dark mode" role="switch" aria-checked="false" />
  <label for="mode-switch" class="toggle-label">
    <span class="light-mode">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="12" cy="12" r="5"></circle>
        <line x1="12" y1="1" x2="12" y2="3"></line>
        <line x1="12" y1="21" x2="12" y2="23"></line>
        <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
        <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
        <line x1="1" y1="12" x2="3" y2="12"></line>
        <line x1="21" y1="12" x2="23" y2="12"></line>
        <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
        <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
      </svg>
    </span>
    <span class="dark-mode">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
      </svg>
    </span>
  </label>
</div>


<style>.mode-toggle{position:relative;display:inline-block;width:55px;height:28px;}.mode-toggle input{opacity:0;width:0;height:0;}.toggle-label{position:absolute;top:0;left:0;right:0;bottom:0;background-color:#000;border-radius:28px;cursor:pointer;transition:background-color 0.2s;}.toggle-label::before{position:absolute;content:"";height:20px;width:20px;left:4px;bottom:4px;background-color:#fff;border-radius:50%;transition:transform 0.3s,background-color 0.3s;z-index:999;}.light-mode,.dark-mode{position:absolute;width:50%;height:100%;text-align:center;line-height:28px;font-size:12px;font-weight:bold;color:#fff;display:flex;justify-content:center;align-items:center;transition:color 0.3s;}.light-mode{left:0;}.dark-mode{right:0;}input:checked + .toggle-label{background-color:#fff;}input:checked + .toggle-label::before{transform:translateX(26px);background-color:#000;}input:checked + .toggle-label .light-mode,input:checked + .toggle-label .dark-mode{color:#000;}body{transition:background-color 0.3s ease-in-out,color 0.3s ease-in-out;}body h1,body h2,body h3,body h4,body h5,body h6{transition:color 0.2s ease-in-out;}</style>
				
			

Part 2: The Snippet

				
					add_action('wp_head', 'dark_mode_toggle_script');

function dark_mode_toggle_script() {
  ?>
  <script type="text/phast">document.addEventListener('DOMContentLoaded',(event)=>{const modeSwitch=document.querySelector('#mode-switch');const isDarkMode=localStorage.getItem('darkMode')==='true';const setMode=(dark)=>{document.body.classList.toggle('darkMode',dark);modeSwitch.setAttribute('aria-checked',dark);localStorage.setItem('darkMode',dark);};setMode(isDarkMode);modeSwitch.addEventListener('change',()=>{const darkModeEnabled=modeSwitch.checked;setMode(darkModeEnabled);});modeSwitch.addEventListener('keypress',(event)=>{if(event.key==='Enter'||event.key===' '){modeSwitch.checked=!modeSwitch.checked;modeSwitch.dispatchEvent(new Event('change'));event.preventDefault();}});});</script>
  <?php
}

				
			

Part 3: Example CSS

				
					html { font-size: 100%; } /* Default is always 16px */

/* Text */
h1 {
  font-size: clamp(2.5rem, 1.75rem + 3vw, 4rem);
  font-weight: 900;
  color: var(--e-global-color-primary);
}

.darkMode h1 {
  color: #FFF;
}

h2 {
  font-size: 2rem;
  font-weight: 600;
  color: var(--e-global-color-secondary);
}

.darkMode h2 {
  color: #D0D0CE;
}

.purple h2 {
  font-size: 1.5rem;
  font-weight: 900;
  color: var(--e-global-color-purple_shade);
}

.darkMode .purple h2 {
  color: var(--e-global-color-dark_mode_yellow);
}

p {
  font-size: clamp(1rem, 0.875rem + 0.5vw, 1.25rem);
  font-weight: normal;
  color: var(--e-global-color-text);
}

.darkMode p {
  color: var(--e-global-color-white);
}

/* Backgrounds */
body {
  background-color: #FFF; /* Light background */
}

.darkMode {
  background-color: #000; /* Dark background */
}

.hero_banner {
  background-color: #EFEFEF;
}

.darkMode .hero_banner {
  background-color: #222222;
}

/* Buttons */
.elementor-button {
  background-color: var(--e-global-color-primary);
  color: #FFF;
}

.elementor-button:hover {
  background-color: #000;
}

.darkMode .elementor-button {
  background-color: #F3F3F3;
  color: #000;
}

.darkMode .purple_shade .elementor-button {
  background-color: var(--e-global-color-dark_mode_yellow);
  color: #000;
}

/* Applied to Menu */
.elementor-nav-menu a {
  color: #000;
}

.darkMode .elementor-nav-menu a {
  color: var(--e-global-color-dark_mode_yellow);
}

/* Images */
.darkMode img {
  filter: brightness(0.7) contrast(1.1);
}

.darkMode .grayscale img {
  filter: grayscale(1); /* Between 0 and 1 */
}

.darkMode .saturate img {
  filter: saturate(1.5); /* 1+ increase, <1 decrease */
}

.darkMode .sepia img {
  filter: sepia(1); /* Between 0 and 1 */
}

/* SVG Icons */
.elementor-icon svg {
  fill: #000;
}

.darkMode .elementor-icon svg {
  fill: var(--e-global-color-dark_mode_yellow);
}
				
			
				
					add_filter( 'elementor_pro/custom_fonts/font_display', function( $current_value, $font_family, $data ) {
	return 'swap';
}, 10, 3 );
				
			
				
					add_filter( 'elementor/frontend/print_google_fonts', '__return_false' );
				
			
				
					/**
 * We will Dequeue the jQuery UI script as example.
 *
 * Hooked to the wp_print_scripts action, with a late priority (99),
 * so that it is after the script was enqueued.
 */
function wp_remove_scripts() {
// check if user is admin
 if (current_user_can( 'update_core' )) {
            return;
        }
 else {
    // Check for the page you want to target
    if ( is_page( 'homepage' ) ) {
        // Remove Scripts
  wp_dequeue_style( 'jquery-ui-core' );
     }
 }
}
add_action( 'wp_enqueue_scripts', 'wp_remove_scripts', 99 );
				
			
				
					add_filter( 'wp_lazy_loading_enabled', '__return_false' );
				
			

The Settings Pack - WordPress

Last Updated Saturday 29 June 2024

WordPress General Settings

1) Set the Site Title (or go to WordPress Dashboard > Appearance > Customize).

2) Set the Site Icon (or go to WordPress Dashboard > Appearance > Customize).

3) Ensure the Address/Site URL both begin with https:// (If you don’t have a valid SSL Certificate, then check with your host).

4) Ensure the Admin Email Address is correct.

WordPress Reading Settings

This step can be left until a Homepage or a Landing Page has been created.

Return here to set the first page to be loaded when a user enters your parent domain.

WordPress Discussion Settings

The items here are subjective to if;

1) You permit comments to be added, and

2) You will moderate activity and remove spam.

Within the ‘Course’, we will advise on disabling Comments for particular Posts and Pages.

Inside of the ‘Settings Pack’, you will find the Snippets Bundle with a Code Snippet to fully disable comments on all Posts and Pages.

WordPress Media Settings

When images are added to the Media Library, multiple versions may be created in your wp-uploads folder.

1) Images should be uploaded as a webp format. We show how to convert PNG/JPEG within the ‘Course’.

2) Images should be reasonably sized to the maximum size required on the site. Do not upload an image that is 1920x 1080 if it will only be 300px wide on a site.

I leave the Thumbnail Size as 150×150, and set the others to be 0. 

Inside of the ‘Settings Pack’, you will find the Snippets Bundle with a Code Snippet to ‘future-proof’ prevent duplicate images being created in your database.

WordPress Permalink Settings

Set the format of the links that will appear for Posts, Pages and Products.

I recommend ‘Post Name’ especially if you care about SEO and Keyword Marketing.

Inside of the ‘Settings Pack’, you will find the Snippets Bundle with a Code Snippet to set the Permalink to always stay set to prevent someone modifying it.

Excellent

Click Download for your file