WP sitemap xml (part 1) – draft

   

Per generare sitemap.xml in automatico ma senza plug-in come riferimento utilizzo documentazione sitemaps.org e tengo come linea guida per generare sitemap senza plug-in.

Sempre interessante e da tener presente doumentazione ufficiale wordpress.

Idea di base:

aggiungere un’azione al theme che stiamo utilizzando che aggiorni sitemap tutte le volte che salviamo post o pagina

situazione di partenza con una semplice sitemap e robots.txt per wordpress

sitemap.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
  <loc>https://www.drservice.it/index.php</loc>
        <lastmod>2021-04-29</lastmod>
        <changefreq>monthly</changefreq>
        <priority>1.0</priority>
    </url>
</urlset>
robots.txt
User-Agent: *
Allow: /wp-content/uploads/
Disallow: /wp-content/plugins/
Disallow: /wp-admin/
Disallow: /readme.html
Disallow: /refer/
 
Sitemap: https://drservice.it/sitemap.xml
Modifica file function.php

Apro il file wp-content/themes/your theme folder/functions.php e inserisco dove opportuno il codice, in questo caso dopo ultimo add_action

/**
 * generatore di site map ogni volta che salvo post e pagine
 */
add_action("publish_post", "local_sitemap_generator");
add_action("publish_page", "local_sitemap_generator");


function local_sitemap_generator() {
    // genero array pagine e post
    $postAndPagesSitemap = get_posts(array(
    'numberposts' => -1,
    'orderby' => 'modified',
    'post_type' => array('post','page'),
    'order' => 'DESC'
    ));
    // intestazione xml costante
    $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
    // adesso non inserisco foglio stile -- !! inserito space tra ? e >
    // $sitemap .= '< ?xml-stylesheet type="text/xsl" href="sitemap-style.xsl" ? >';
    // giusto ma genera errore 'strict-origin-when-cross-origin'
    // $sitemap .= '<?xml-stylesheet type="text/xsl" href="https://drservice.it/sitemap-generic.xsl" ? >';
// schema 
    $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    // peer ogni riga array inserisco <url>
    foreach($postAndPagesSitemap as $post) {
        // genero global $post data -- !! Note that this variable must have this name!
        // https://developer.wordpress.org/reference/functions/setup_postdata/
        setup_postdata($post);
        $postdate = explode(" ", $post->post_modified);
        $sitemap .= '<url>'.
        '<loc>'. get_permalink($post->ID) .'</loc>'.
        '<priority>1</priority>'.
        '<lastmod>'. $postdate[0] .'</lastmod>'.
        '<changefreq>daily</changefreq>'.
        '</url>';
// adattare changefreq alle esigenze
    }
    $sitemap .= '</urlset>';
    // salvo file nella root principale
    $fp = fopen(ABSPATH . "sitemap.xml", 'w');
    fwrite($fp, $sitemap);
    fclose($fp);
}

Con il primo salvataggio, anche di questa pagina, posso verificare se viene rigenerata sitemap.xml e se tutto ok ottengo, su una riga, un risultato simile a:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://drservice.it/blog/wp-sitemap-xml/</loc>
        <priority>1</priority>
        <lastmod>2021-05-08</lastmod>
        <changefreq>daily</changefreq>
    </url>
    ...

    ...
    <url>
        <loc>https://drservice.it/</loc>
        <priority>1</priority>
        <lastmod>2021-04-28</lastmod>
        <changefreq>daily</changefreq>
    </url>
</urlset>

Da Google Search Console provo a caricare nuova sitemap e posso subito vedere eventuali errori da

https://drservice.it/sitemap.xml

wordpress default sitemap

ma anche wordpress, dalla v 5.5, genera in automatico la propria sitemap che posso vedere se aggiungo wp-sitemap.xml subito dopo il dominio es: https://drservice.it/wp-sitemap.xml in seguito vedremo come disattivare questa modifica a function.php e utilizzare wordpress core.

Genero stylesheet xsl generico sitemap-generic.xsl, che salvo nella root prendendo come esempio quelle riportato su wplift, si possono anche trovare molti esempi online e migliorata per la versione definitiva.

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="2.0" xmlns:html="http://www.w3.org/TR/REC-html40" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="html" encoding="utf-8" indent="yes"/> 
    <xsl:template match="/">
        <xsl:variable name="fileType"> 
            <xsl:choose> 
                <xsl:when test="//sitemap:url">Sitemap</xsl:when> 
                <xsl:otherwise>SitemapIndex</xsl:otherwise> 
            </xsl:choose> 
        </xsl:variable>
        <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
                <title>
                    <xsl:choose>
                        <xsl:when test="$fileType='Sitemap'">Sitemap</xsl:when>
                        <xsl:otherwise>Sitemap Index</xsl:otherwise>
                    </xsl:choose>
                </title>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <style type="text/css">body {font-family:Helvetica,Arial,sans-serif;font-size:68.5%;}table {border:none;border-collapse:collapse;}table {font-size:1em;width:100%;}th {text-align:left;padding:5px;}tr.stripe {background-color:#f7f7f7;}</style>
            </head> 
            <body> 
                <div id="content"> 
                    <h1>XML Generic Sitemap</h1> 
                    <div> 
                        <p>
                            <xsl:choose>
                                <xsl:when test="$fileType='Sitemap'"> This sitemap contains <xsl:value-of select="count(sitemap:urlset/sitemap:url)">
                                    </xsl:value-of> URLs</xsl:when> 
                                <xsl:otherwise>This sitemap index contains <xsl:value-of select="count(sitemap:sitemapindex/sitemap:sitemap)">
                                    </xsl:value-of> sitemaps</xsl:otherwise>
                            </xsl:choose>
                        </p> 
                    </div>
                    <xsl:choose>
                        <xsl:when test="$fileType='Sitemap'">
                            <xsl:call-template name="sitemapTable"/>
                        </xsl:when> 
                        <xsl:otherwise>
                            <xsl:call-template name="siteindexTable"/>
                        </xsl:otherwise>
                    </xsl:choose> 
                </div> 
            </body> 
        </html> 
    </xsl:template> 
    <xsl:template name="siteindexTable"> 
        <table cellpadding="3">
            <thead>
                <tr>
                    <th width="50%">URL</th>
                    <th>LastChange</th>
                </tr>
            </thead>
            <tbody>
                <xsl:variable name="lower" select="'abcdefghijklmnopqrstuvwxyz'"/>
                <xsl:variable name="upper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
                <xsl:for-each select="sitemap:sitemapindex/sitemap:sitemap">
                    <tr>
                        <xsl:if test="position() mod 2 != 1">
                            <xsl:attribute name="class">stripe</xsl:attribute>
                        </xsl:if>
                        <td>
                            <xsl:variable name="itemURL">
                                <xsl:value-of select="sitemap:loc"/>
                            </xsl:variable>
                            <a href="{$itemURL}">
                                <xsl:value-of select="sitemap:loc"/>
                            </a>
                        </td>
                        <td>
                            <xsl:value-of select="concat(substring(sitemap:lastmod,0,11),concat(' ', substring(sitemap:lastmod,12,5)))"/>
                        </td>
                    </tr>
                </xsl:for-each>
            </tbody>
        </table> 
    </xsl:template> 
    <xsl:template name="sitemapTable">
        <table cellpadding="3">
            <thead>
                <tr>
                    <th width="50%">URL</th>
                    <th>Priority</th>
                    <th>Change Frequency</th>
                    <th>LastChange</th>
                </tr>
            </thead>
            <tbody>
                <xsl:variable name="lower" select="'abcdefghijklmnopqrstuvwxyz'"/>
                <xsl:variable name="upper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
                <xsl:for-each select="sitemap:urlset/sitemap:url">
                    <tr>
                        <xsl:if test="position() mod 2 != 1">
                            <xsl:attribute name="class">stripe</xsl:attribute>
                        </xsl:if>
                        <td>
                            <xsl:variable name="itemURL">
                                <xsl:value-of select="sitemap:loc"/>
                            </xsl:variable>
                            <a href="{$itemURL}">
                                <xsl:value-of select="sitemap:loc"/>
                            </a>
                        </td>
                        <td>
                            <xsl:if test="string(number(sitemap:priority))!='NaN'">
                                <xsl:value-of select="concat(sitemap:priority*100,'%')"/>
                            </xsl:if>
                        </td>
                        <td>
                            <xsl:value-of select="concat(translate(substring(sitemap:changefreq, 1, 1),concat($lower, $upper),concat($upper, $lower)),substring(sitemap:changefreq, 2))"/>
                        </td>
                        <td>
                            <xsl:value-of select="concat(substring(sitemap:lastmod,0,11),concat(' ', substring(sitemap:lastmod,12,5)))"/>
                        </td>
                    </tr>
                </xsl:for-each>
            </tbody>
        </table> 
    </xsl:template>
</xsl:stylesheet>

WP abilitare upload svg


Come impostazione default WordPress non permette upload file f.to svg.

Primo metodo

Apro file con Illustrator e risalvo come svg, spesso funziona.

Secondo metodo

Posso attivare supporto svg e quasi alla fine di function.php, nel mio thema aggiungo il filtro

// Allow SVG
    add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {

        global $wp_version;
        if ( $wp_version !== '5.7' ) {
        return $data;
        }
    
        $filetype = wp_check_filetype( $filename, $mimes );
    
        return [
            'ext'             => $filetype['ext'],
            'type'            => $filetype['type'],
            'proper_filename' => $data['proper_filename']
        ];
    
    }, 10, 4 );
    
    function cc_mime_types( $mimes ){
        $mimes['svg']  = 'image/svg+xml';
        $mimes['svgz'] = 'image/svg+xml';
        return $mimes;
    }
    add_filter( 'upload_mimes', 'cc_mime_types' );
    
    function fix_svg() {
        echo '<style type="text/css">
            .attachment-266x266, .thumbnail img {
                width: 100% !important;
                height: auto !important;
            }
            </style>';
    }
    add_action( 'admin_head', 'fix_svg' );