Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrancoStino/840ba799e0e0ea81a08777c1e87accd3 to your computer and use it in GitHub Desktop.
Save FrancoStino/840ba799e0e0ea81a08777c1e87accd3 to your computer and use it in GitHub Desktop.
Filtro JSON-LD di Rank Math per Categorie di Prodotto WooCommerce

Filtro JSON-LD di Rank Math per Categorie di Prodotto WooCommerce

Questo filtro personalizzato aggiunge dati strutturati JSON-LD alle pagine delle categorie di prodotto in WooCommerce, migliorando la visibilità SEO e la ricchezza dei risultati nei motori di ricerca. Il filtro genera dati strutturati per i prodotti pubblicati e disponibili nella categoria corrente.

Funzionalità

  • Verifica che la pagina corrente sia una categoria di prodotto valida.
  • Recupera prodotti pubblicati e in stock, ordinati alfabeticamente.
  • Genera dati JSON-LD secondo lo standard Schema.org, includendo dettagli come nome, URL, descrizione, immagine e prezzi.
  • Supporta prodotti semplici e variabili, gestendo prezzi multipli per variazioni.

Requisiti

  • WordPress con WooCommerce attivo.
  • Plugin Rank Math SEO installato e configurato.

Istruzioni di Utilizzo

  1. Copia il codice seguente nel file functions.php del tema attivo di WordPress:

    /**
    * Filters the Rank Math JSON-LD data to include structured data for WooCommerce product categories.
    *
    * @param array $data The existing JSON-LD data.
    * @return array The modified JSON-LD data.
    */
    add_filter( 'rank_math/json_ld', function ($data)
    {
        // Check if the current page is a product category page and if the category object is valid
        if ( empty( $data ) || !is_product_category() || !( $category = get_queried_object() ) || !isset( $category->term_id ) )
    {
        return $data;
    }
    
    // Get the current page number and the number of products per page
    $paged    = max( 1, get_query_var( 'paged' ) );
    $per_page = isset( $_GET[ 'per_page' ] )
        ? intval( $_GET[ 'per_page' ] )
        : ( get_option( 'woocommerce_catalog_columns' ) * get_option( 'woocommerce_catalog_rows', 4 ) );
    
    // Get the products in the current category
    $products = wc_get_products( [ 
        'category'     => [ $category->slug ],
        'status'       => 'publish',
        'limit'        => $per_page,
        'page'         => $paged,
        'paginate'     => true,
        'stock_status' => 'instock',
        'orderby'      => 'name',
        'order'        => 'ASC',
    ] );
    
    // If there are no products, return the original data
    if ( empty( $products->products ) )
    {
        return $data;
    }
    
    // Initialize the structured data array
    $structured_data = [ 
        '@type'           => 'ItemList',
        'numberOfItems'   => 0,
        'itemListElement' => [],
    ];
    
    // Calculate the base position for the products
    $base_position = ( $paged - 1 ) * $per_page;
    
    // Loop through the products and add them to the structured data array
    foreach ( $products->products as $index => $product )
    {
        $product_data = [ 
            '@type'    => 'ListItem',
            'position' => $base_position + $index + 1,
            'item'     => [ 
                '@type'       => 'Product',
                'name'        => $product->get_name(),
                'url'         => get_permalink( $product->get_id() ),
                'description' => wp_strip_all_tags( $product->get_short_description() ),
                'image'       => wp_get_attachment_url( $product->get_image_id() ),
            ],
        ];
    
        // Handle variable products by adding an AggregateOffer
        if ( $product->is_type( 'variable' ) )
        {
            $variations = $product->get_available_variations();
            $prices     = array_filter( array_column( $variations, 'display_price' ) );
    
            if ( !empty( $prices ) )
            {
                $product_data[ 'item' ][ 'offers' ] = [ 
                    '@type'         => 'AggregateOffer',
                    'lowPrice'      => min( $prices ),
                    'highPrice'     => max( $prices ),
                    'priceCurrency' => get_woocommerce_currency(),
                    'availability'  => 'https://schema.org/InStock',
                    'offerCount'    => count( $prices ),
                ];
            }
        }
        // Handle simple products by adding an Offer
        else
        {
            $price = $product->get_price();
            if ( $price )
            {
                $product_data[ 'item' ][ 'offers' ] = [ 
                    '@type'         => 'Offer',
                    'price'         => $price,
                    'priceCurrency' => get_woocommerce_currency(),
                    'availability'  => 'https://schema.org/InStock',
                    'url'           => get_permalink( $product->get_id() ),
                ];
            }
        }
    
        // Add the product data to the itemListElement array
        $structured_data[ 'itemListElement' ][] = $product_data;
    }
    
    // Set the number of items in the structured data
    $structured_data[ 'numberOfItems' ] = count( $structured_data[ 'itemListElement' ] );
    
    // Add the structured data to the JSON-LD graph
    if ( isset( $data[ '@graph' ] ) )
    {
        $data[ '@graph' ][] = $structured_data;
    }
    else
    {
        $data[ '@graph' ] = [ $structured_data ];
    }
    
    return $data;
    
    }, 20, 2 );
  2. Salva il file e verifica che non ci siano errori sul tuo sito WordPress.

Dettagli Tecnici

  • I prodotti sono ordinati alfabeticamente (orderby impostato su name).
  • I prezzi per i prodotti variabili sono calcolati come intervallo (minimo e massimo).
  • Supporta paginazione e controllo personalizzato del numero di prodotti per pagina tramite il parametro per_page.

Contribuisci

Per segnalare bug o suggerire miglioramenti, crea un problema su GitHub.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment