Skip to content

Instantly share code, notes, and snippets.

@Jehu
Created December 13, 2022 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jehu/9b78c2127c22a8efaf4cbd76e808015c to your computer and use it in GitHub Desktop.
Save Jehu/9b78c2127c22a8efaf4cbd76e808015c to your computer and use it in GitHub Desktop.
SEOPress manual FAQ Schema + Metabox.io – Use related custom FAQ post type
/**
* FAQ Schema.org for MetaBox Relationship if manual FAQ Schema is active
*
* @See https://www.seopress.org/support/hooks/filter-manual-faq-schema/
*/
add_filter('seopress_pro_get_json_data_faq','sp_pro_schema_faq_json', 10, 2);
function sp_pro_schema_faq_json($json, $context)
{
$relationship_id = 'faq-page'; // Replace with your Relationship ID
$question_id = FALSE; // Replace with your Answer Field ID or FALSE if post title should be used
$answer_id = 'faq_answer'; // Replace with your Answer Field ID
$show_all_if_nonrelated = FALSE; // Show all FAQ if there is no FAQ related to this post
$faqs = new WP_Query( [
'relationship' => [
'id' => $relationship_id,
'from' => get_the_ID(),
],
'nopaging' => true,
'order' => 'ASC',
'orderby' => 'menu_order',
] );
unset($json['mainEntity']);
$json['mainEntity'] = [];
if(!$faqs->have_posts()) {
if(!$show_all_if_nonrelated) {
// If we don't have FAQ related to this post, do not return FAQ schema
return $json;
} else {
// If we don't have FAQ related to this post, get all FAQ
$faqs = new WP_Query( [
'post_type' => 'faq',
'nopaging' => true,
'order' => 'ASC',
'orderby' => 'menu_order',
] );
}
}
while ( $faqs->have_posts() ) {
$faqs->the_post();
$question = ($question_id) ? rwmb_meta($answer_id) : get_the_title(); // Replace with your FAQ "Question" field value
$answer = rwmb_meta($answer_id); // Replace with your FAQ "Answer" field value
$faq_question = esc_attr(stripslashes_deep(wp_filter_nohtml_kses(wp_strip_all_tags(strip_shortcodes( $question )))));
$faq_answer = esc_attr(stripslashes_deep(wp_filter_nohtml_kses(wp_strip_all_tags(strip_shortcodes( $answer )))));
// Needed if FAQ answer is a wysiwyg editor
$faq_answer = str_replace("\n", '<br />', normalize_whitespace($faq_answer));
$faq[] = [
'@type' => 'Question',
'name' => $faq_question,
'answerCount' => 1,
'acceptedAnswer' =>
[
'@type' => 'Answer',
'text' => $faq_answer,
],
];
}
wp_reset_postdata();
$json['mainEntity'] = $faq;
return $json;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment