I have create custom type post (FAQ) function and display function vh_display_post_faqs( $post_id = 0 ) and its working correctly. I have also added schema markup inside while statement. But I am getting this error that there is Duplicate field “FAQPage” when I test via https://search.google.com/test/rich-results. Am I looping wrongly?
Error of Duplicate field “FAQPage” Image
function vh_display_post_faqs( $post_id = 0 ) {
// Return if post id is empty.
if ( empty( $post_id ) ) {
return;
}
// Get the categories' ids using the passed post id.
$categories_ids = wp_get_post_terms( $post_id, 'category', array( 'fields' => 'ids' ) );
// Validate for empty ids or wp errors.
if ( empty( $categories_ids ) || is_wp_error( $categories_ids ) ) {
return;
}
// Prepare query args, using tax query.
$query_args = array(
'post_type' => 'faq',
'posts_per_page' => 2,
'tax_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $categories_ids,
),
);
// Run query and fetch faq posts.
$faqs = new WP_Query( $query_args );
// Check if we have posts from the query.
if ( $faqs->have_posts() ) :
// Loop through the query posts.
while ( $faqs->have_posts() ) :
$faqs->the_post();
$striped = the_content();
$strip = str_replace(['"',"'"], "", $striped);
// Print the content.
?>
<div class="faq-post">
<h2 class="faq-title"><?php the_title(); ?></h2>
<div class="faq-content"><?php the_content(); ?>
</div>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [{
"@type": "Question",
"name": "<?php the_title(); ?>",
"acceptedAnswer": {
"@type": "Answer",
"text": "<?php str_replace("n","",the_content()); ?>"
}
}]
}
</script>
<?php
endwhile;
// Reset the post data.
wp_reset_postdata();
endif;
}