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

问题描述

我是 stackoverflow 和 wordpress 编码的新手。我在学习。我有一个分类法,我想在 SiteNavigationElement Schema 中添加所有分类法和它的 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","url": "<?PHP echo esc_url( $term_link );?>"
        },<?PHP endif;  ?>


      
<?PHP endwhile;

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

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


{
            "@type": "SiteNavigationElement",

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


{
            "@type": "SiteNavigationElement","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 
}

经过测试并有效。

enter image description here