*/ private $entities = array(); /** * Whether output has already been printed. * * @var bool */ private $printed = false; /** * Register hooks. * * @return void */ public function register() { add_action( 'wp_footer', array( $this, 'print_schema' ), 20 ); } /** * Add rendered items to the schema collection. * * @param array $items Item data from the renderer. * @return void */ public function add_items( array $items ) { foreach ( $items as $item ) { if ( empty( $item['id'] ) ) { continue; } $question = isset( $item['question'] ) ? wp_strip_all_tags( (string) $item['question'] ) : ''; $answer = isset( $item['answer_text'] ) ? trim( (string) $item['answer_text'] ) : ''; if ( '' === $question || '' === $answer ) { continue; } // Deduplicate by post ID. $this->entities[ (int) $item['id'] ] = array( '@type' => 'Question', 'name' => $question, 'acceptedAnswer' => array( '@type' => 'Answer', 'text' => $answer, ), ); } } /** * Print the FAQPage JSON-LD once, in the footer. * * @return void */ public function print_schema() { if ( $this->printed || empty( $this->entities ) ) { return; } $this->printed = true; $entities = array_values( $this->entities ); /** * Filter the FAQPage schema entities before output. * * @param array $entities Question entities. */ $entities = apply_filters( 'accordion_faq_schema_entities', $entities ); if ( empty( $entities ) ) { return; } $schema = array( '@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => $entities, ); echo "\n\n"; } }