如何在 SiteNavigationElement 架构中添加分类法名称及其 URL?

How Can I add Taxonomy Name and It's URL in SiteNavigationElement Schema?

我是 Whosebug 的新手,也是 wordpress 编码方面的新手。我在学习。我有一个分类法,我想添加所有分类法,它是 SiteNavigationElement 架构中的 URL。谁能帮我提供解决方案。

下面是我的代码


<script type="application/ld+json">
    
    {
            <?php
$custom_terms = get_the_terms('dealstore' );
$term_link = get_term_link( $custom_terms );
foreach($custom_terms as $custom_term) {
    wp_reset_query();
$args = array(
'post_type' => 'post',
         );

$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while( $query->have_posts() ) :
$query->the_post(); ?>
<?php if ($query->current_post +1 == $query->post_count) : ?>
   {
            "@type": "SiteNavigationElement",
            "@id": "#navigation",
            "name": "<?php echo $query->name; ?>",
            "url": "<?php echo esc_url( $term_link );?>"
        }
<?php else : ?>
    {
            "@type": "SiteNavigationElement",
            "@id": "#navigation",
            "name": "<?php echo $query->name; ?>",
            "url": "<?php echo esc_url( $term_link );?>"
        },
<?php endif;  ?>


      
<?php endwhile;

endif;
wp_reset_postdata(); } ?>
            
        }
</script>

IF条件可以吗? 例如 - 如果第一个分类名称比 它显示如下,带有“,”(逗号)


{
            "@type": "SiteNavigationElement",
            "@id": "#navigation",
            "name": "<?php echo $query->name; ?>",
            "url": "<?php echo esc_url( $term_link );?>"
        },

如果最后的分类名称比下面显示的没有“,”(逗号))


{
            "@type": "SiteNavigationElement",
            "@id": "#navigation",
            "name": "<?php echo $query->name; ?>",
            "url": "<?php echo esc_url( $term_link );?>"
        }

您可以通过使用get_queried_object 将其放在您的分类页面上来获取当前页面上的当前分类。

$terms = get_terms( array(
    'taxonomy' => 'species',
    'hide_empty' => false,
) );

if( !empty( $terms ) ){

    ?>

    <script type="application/ld+json">
    {   
        <?php 
            $total = count($terms);
            $i = 0;
            foreach ( $terms as $term ) { $term_link = get_term_link( $term );
                $i++;
            ?>
            {
                "@type": "SiteNavigationElement",
                "@id": "#navigation",
                "name": "<?php echo $term->name; ?>",
                "url": "<?php echo esc_url( $term_link );?>"
            }                   
        <?php if ($i != $total) echo', '; } ?>
    }
    </script>
    <?php 
}

已测试并有效。