has_seo_conflict() || apply_filters( 'advanced_seo_force_output', false ) ) {
remove_action( 'wp_head', 'rel_canonical' ); // we output our own
add_filter( 'pre_get_document_title', [ $this, 'custom_title' ], 10 );
add_filter( 'wp_robots', [ $this, 'filter_robots' ] );
add_action( 'wp_head', [ $this, 'output_meta_tags' ], 1 );
add_action( 'wp_head', [ $this, 'output_canonical' ], 1 );
add_action( 'wp_head', [ $this, 'output_og_tags' ], 2 );
}
}
public function on_init() {
load_plugin_textdomain( 'advanced-seo-meta', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
add_image_size( self::OG_IMAGE_SIZE, 1200, 630, true );
// Expose meta to the REST API / block editor.
$text = [
self::META_TITLE => 'sanitize_text_field',
self::META_DESC => 'sanitize_textarea_field',
self::META_NOINDEX => 'sanitize_text_field',
];
$auth = function ( $allowed, $meta_key, $post_id ) {
return current_user_can( 'edit_post', $post_id );
};
foreach ( $this->post_types() as $pt ) {
foreach ( $text as $key => $cb ) {
register_post_meta( $pt, $key, [
'type' => 'string',
'single' => true,
'show_in_rest' => true,
'sanitize_callback' => $cb,
'auth_callback' => $auth,
] );
}
register_post_meta( $pt, self::META_OG_IMAGE, [
'type' => 'integer',
'single' => true,
'show_in_rest' => true,
'sanitize_callback' => 'absint',
'auth_callback' => $auth,
] );
register_post_meta( $pt, self::META_FAQ, [
'type' => 'array',
'single' => true,
'show_in_rest' => [
'schema' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'question' => [ 'type' => 'string' ],
'answer' => [ 'type' => 'string' ],
],
],
],
],
'sanitize_callback' => [ $this, 'sanitize_faq_array' ],
'auth_callback' => $auth,
] );
}
}
/* ============================================================
* HELPERS — GENERAL
* ============================================================ */
private function post_types() {
$types = get_post_types( [ 'public' => true ] );
unset( $types['attachment'] );
return array_values( (array) apply_filters( 'advanced_seo_post_types', array_values( $types ) ) );
}
private function has_seo_conflict() {
return defined( 'WPSEO_VERSION' ) // Yoast
|| defined( 'RANK_MATH_VERSION' ) // Rank Math
|| class_exists( 'RankMath' )
|| defined( 'AIOSEO_VERSION' ) // All in One SEO
|| defined( 'SEOPRESS_VERSION' ) // SEOPress
|| defined( 'THE_SEO_FRAMEWORK_VERSION' );
}
public function conflict_notice() {
if ( ! $this->has_seo_conflict() || ! current_user_can( 'manage_options' ) ) return;
$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
if ( ! $screen || ! in_array( $screen->id, [ 'plugins', 'settings_page_advanced-seo-settings' ], true ) ) return;
echo '
Advanced SEO Meta: '
. esc_html__( 'Another SEO plugin was detected. To avoid duplicate tags, this plugin has disabled its title, description, Open Graph, canonical and robots output. FAQ and business schema are still output. Use the "advanced_seo_force_output" filter to override.', 'advanced-seo-meta' )
. '
';
}
private function faq_allowed_html() {
return [
'p' => [], 'br' => [], 'ul' => [], 'ol' => [], 'li' => [],
'strong' => [], 'b' => [], 'em' => [], 'i' => [],
'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [],
'a' => [ 'href' => true ],
];
}
public function sanitize_faq_array( $value ) {
if ( ! is_array( $value ) ) return [];
$out = [];
foreach ( $value as $row ) {
$q = isset( $row['question'] ) ? sanitize_text_field( $row['question'] ) : '';
$a = isset( $row['answer'] ) ? wp_kses( (string) $row['answer'], $this->faq_allowed_html() ) : '';
if ( '' !== $q && '' !== trim( $a ) ) {
$out[] = [ 'question' => $q, 'answer' => $a ];
}
}
return $out;
}
private function clean_text( $text ) {
$text = wp_strip_all_tags( (string) $text );
$text = preg_replace( '/\s+/u', ' ', $text );
return trim( $text );
}
/** Truncate at a word boundary. */
private function truncate( $text, $limit = 160 ) {
$text = $this->clean_text( $text );
if ( mb_strlen( $text ) <= $limit ) return $text;
$cut = mb_substr( $text, 0, $limit );
$trimmed = preg_replace( '/\s+\S*$/u', '', $cut );
if ( '' !== $trimmed && null !== $trimmed ) $cut = $trimmed;
return rtrim( $cut, " ,.;:-–—" ) . '…';
}
private function print_jsonld( array $schema ) {
echo '' . "\n";
}
private function paged() {
return max( 1, (int) get_query_var( 'paged' ) );
}
/* ============================================================
* CONTEXT
* ============================================================ */
private function get_context() {
if ( null !== $this->ctx ) return $this->ctx;
$kind = 'other';
$id = 0;
if ( is_front_page() ) {
$kind = 'front';
$id = (int) get_option( 'page_on_front' );
} elseif ( is_home() ) {
$kind = 'posts_page';
$id = (int) get_option( 'page_for_posts' );
} elseif ( is_singular() ) {
$kind = 'singular';
$id = (int) get_queried_object_id();
} elseif ( is_category() || is_tag() || is_tax() ) {
$kind = 'term';
$id = (int) get_queried_object_id();
} elseif ( is_author() ) {
$kind = 'author';
$id = (int) get_queried_object_id();
} elseif ( is_post_type_archive() ) {
$kind = 'pt_archive';
} elseif ( is_search() ) {
$kind = 'search';
} elseif ( is_404() ) {
$kind = '404';
}
$this->ctx = [ 'kind' => $kind, 'id' => $id ];
return $this->ctx;
}
/* ============================================================
* ADMIN — ASSETS
* ============================================================ */
public function enqueue_admin_assets( $hook ) {
$is_post_edit = in_array( $hook, [ 'post.php', 'post-new.php' ], true );
$is_settings = ( 'settings_page_advanced-seo-settings' === $hook );
if ( ! $is_post_edit && ! $is_settings ) return;
wp_enqueue_media();
wp_register_script( 'advanced-seo-admin', false, [ 'jquery', 'jquery-ui-sortable' ], self::VERSION, true );
wp_enqueue_script( 'advanced-seo-admin' );
wp_add_inline_script(
'advanced-seo-admin',
'window.advancedSeoL10n=' . wp_json_encode( [
'selectImage' => __( 'Select Image', 'advanced-seo-meta' ),
'useImage' => __( 'Use this image', 'advanced-seo-meta' ),
] ) . ';',
'before'
);
wp_add_inline_script( 'advanced-seo-admin', $this->admin_js() );
}
private function admin_js() {
return <<<'JS'
jQuery(function($){
var L = window.advancedSeoL10n || {};
// ---- Character counters ----
function counter($el){
var min = parseInt($el.data('min'),10) || 0,
max = parseInt($el.data('max'),10) || 0,
len = $el.val().length,
$c = $el.next('.seo-counter');
if (!$c.length) return;
var color = (len === 0) ? '#757575' : ((len < min || len > max) ? '#b26200' : '#007017');
$c.text(len + ' / ' + max).css('color', color);
}
$('.seo-count').each(function(){ counter($(this)); });
$(document).on('input', '.seo-count', function(){ counter($(this)); });
// ---- FAQ rows ----
function checkDupes(){
var seen = {}, dupe = false;
$('input[name="faq_question[]"]').each(function(){
var v = $.trim($(this).val()).toLowerCase();
if (!v) return;
if (seen[v]) dupe = true;
seen[v] = 1;
});
$('#faq-dupe-warning').toggle(dupe);
}
$(document).on('input', 'input[name="faq_question[]"]', checkDupes);
$(document).on('click', '.add-faq-row', function(e){
e.preventDefault();
$('#faq-container').append($('#faq-row-template').html());
});
$(document).on('click', '.remove-faq-row', function(e){
e.preventDefault();
$(this).closest('.faq-row').remove();
checkDupes();
});
if ($.fn.sortable && $('#faq-container').length) {
$('#faq-container').sortable({ items: '.faq-row', handle: '.faq-handle', axis: 'y' });
}
checkDupes();
// ---- Media picker (post + settings) ----
$(document).on('click', '.seo-image-upload', function(e){
e.preventDefault();
var $wrap = $(this).closest('.seo-image-field');
var frame = wp.media({
title: L.selectImage || 'Select Image',
button: { text: L.useImage || 'Use this image' },
multiple: false,
library: { type: 'image' }
});
frame.on('select', function(){
var att = frame.state().get('selection').first().toJSON();
$wrap.find('input[type=hidden]').val(att.id);
var url = (att.sizes && att.sizes.medium) ? att.sizes.medium.url : att.url;
$wrap.find('.seo-image-preview').empty().append(
$(' ').attr('src', url).css({ maxWidth: '300px', height: 'auto', border: '1px solid #ddd' })
);
$wrap.find('.seo-image-remove').show();
});
frame.open();
});
$(document).on('click', '.seo-image-remove', function(e){
e.preventDefault();
var $wrap = $(this).closest('.seo-image-field');
$wrap.find('input[type=hidden]').val('');
$wrap.find('.seo-image-preview').empty();
$(this).hide();
});
});
JS;
}
/* ============================================================
* ADMIN — META BOX (per post/page/CPT)
* ============================================================ */
public function add_meta_box() {
add_meta_box(
'advanced_seo_meta_box',
__( 'Advanced SEO & FAQ Schema', 'advanced-seo-meta' ),
[ $this, 'render_meta_box' ],
$this->post_types(),
'normal',
'default'
);
}
private function render_faq_row( $question = '', $answer = '', $with_placeholders = false ) {
$ph_q = $with_placeholders ? __( 'e.g., What is Comprehensive Genomic Profiling?', 'advanced-seo-meta' ) : '';
$ph_a = $with_placeholders ? __( 'Write a clear, direct answer…', 'advanced-seo-meta' ) : '';
ob_start();
?>
ID, self::META_TITLE, true );
$seo_description = get_post_meta( $post->ID, self::META_DESC, true );
$og_image_id = (int) get_post_meta( $post->ID, self::META_OG_IMAGE, true );
$noindex = '1' === get_post_meta( $post->ID, self::META_NOINDEX, true );
$faq_data = get_post_meta( $post->ID, self::META_FAQ, true );
if ( ! is_array( $faq_data ) ) $faq_data = [];
?>
/>
'max-width:300px;height:auto;border:1px solid #ddd;' ] ); ?>
render_faq_row( $faq['question'] ?? '', $faq['answer'] ?? '' ); // phpcs:ignore WordPress.Security.EscapeOutput -- escaped in render_faq_row().
}
} else {
echo $this->render_faq_row( '', '', true ); // phpcs:ignore WordPress.Security.EscapeOutput
}
?>
post_types(), true ) ) return;
if ( ! current_user_can( 'edit_post', $post_id ) ) return;
if ( isset( $_POST['seo_title'] ) ) {
$this->save_or_delete_meta( $post_id, self::META_TITLE, sanitize_text_field( wp_unslash( $_POST['seo_title'] ) ) );
}
if ( isset( $_POST['seo_description'] ) ) {
$this->save_or_delete_meta( $post_id, self::META_DESC, sanitize_textarea_field( wp_unslash( $_POST['seo_description'] ) ) );
}
if ( isset( $_POST['seo_og_image_id'] ) ) {
$this->save_or_delete_meta( $post_id, self::META_OG_IMAGE, absint( $_POST['seo_og_image_id'] ) );
}
// Checkbox: the nonce proves the box was rendered, so absence = unchecked.
$this->save_or_delete_meta( $post_id, self::META_NOINDEX, ! empty( $_POST['seo_noindex'] ) ? '1' : '' );
// FAQ pairs
$questions = ( isset( $_POST['faq_question'] ) && is_array( $_POST['faq_question'] ) ) ? wp_unslash( $_POST['faq_question'] ) : [];
$answers = ( isset( $_POST['faq_answer'] ) && is_array( $_POST['faq_answer'] ) ) ? wp_unslash( $_POST['faq_answer'] ) : [];
$pairs = [];
foreach ( $questions as $i => $q ) {
$pairs[] = [
'question' => $q,
'answer' => $answers[ $i ] ?? '',
];
}
$this->save_or_delete_meta( $post_id, self::META_FAQ, $this->sanitize_faq_array( $pairs ) );
}
/* ============================================================
* ADMIN — SETTINGS PAGE
* ============================================================ */
public function register_settings_page() {
add_options_page(
__( 'Advanced SEO Settings', 'advanced-seo-meta' ),
__( 'Advanced SEO', 'advanced-seo-meta' ),
'manage_options',
'advanced-seo-settings',
[ $this, 'render_settings_page' ]
);
}
private function business_types() {
return [
'MedicalBusiness' => 'MedicalBusiness',
'MedicalClinic' => 'MedicalClinic',
'DiagnosticLab' => 'DiagnosticLab',
'LocalBusiness' => 'LocalBusiness',
'Organization' => 'Organization',
];
}
public function register_settings() {
$g = 'advanced_seo_settings';
$text_fields = [
self::OPT_HOME_TITLE, self::OPT_BIZ_NAME, self::OPT_BIZ_PHONE, self::OPT_BIZ_STREET,
self::OPT_BIZ_CITY, self::OPT_BIZ_COUNTRY, self::OPT_BIZ_AREAS, self::OPT_BIZ_PRICE,
];
foreach ( $text_fields as $f ) {
register_setting( $g, $f, [ 'sanitize_callback' => 'sanitize_text_field' ] );
}
register_setting( $g, self::OPT_HOME_DESC, [ 'sanitize_callback' => 'sanitize_textarea_field' ] );
register_setting( $g, self::OPT_BIZ_HOURS, [ 'sanitize_callback' => 'sanitize_textarea_field' ] );
register_setting( $g, self::OPT_BIZ_EMAIL, [ 'sanitize_callback' => 'sanitize_email' ] );
register_setting( $g, self::OPT_DEFAULT_OG, [ 'sanitize_callback' => 'absint' ] );
register_setting( $g, self::OPT_BIZ_LOGO, [ 'sanitize_callback' => 'absint' ] );
register_setting( $g, self::OPT_BIZ_TYPE, [ 'sanitize_callback' => [ $this, 'sanitize_biz_type' ] ] );
register_setting( $g, self::OPT_BIZ_SAMEAS, [ 'sanitize_callback' => [ $this, 'sanitize_urls_lines' ] ] );
register_setting( $g, self::OPT_BIZ_LAT, [ 'sanitize_callback' => [ $this, 'sanitize_coord' ] ] );
register_setting( $g, self::OPT_BIZ_LNG, [ 'sanitize_callback' => [ $this, 'sanitize_coord' ] ] );
}
public function sanitize_biz_type( $v ) {
$v = sanitize_text_field( (string) $v );
return isset( $this->business_types()[ $v ] ) ? $v : 'MedicalBusiness';
}
public function sanitize_urls_lines( $v ) {
$lines = preg_split( '/\r\n|\r|\n/', (string) $v );
$out = [];
foreach ( $lines as $line ) {
$url = esc_url_raw( trim( $line ) );
if ( $url ) $out[] = $url;
}
return implode( "\n", $out );
}
public function sanitize_coord( $v ) {
$v = trim( (string) $v );
return is_numeric( $v ) ? (string) (float) $v : '';
}
private function render_image_field( $option, $id, $button_label ) {
?>
'max-width:300px;height:auto;border:1px solid #ddd;' ] ); ?>
get_seo_title( $this->get_context() );
return '' !== $custom ? $custom : $title;
}
private function post_description( $id ) {
if ( ! $id ) return '';
$desc = get_post_meta( $id, self::META_DESC, true );
if ( $desc ) return $desc;
$post = get_post( $id );
if ( ! $post || post_password_required( $post ) ) return '';
if ( '' !== trim( $post->post_excerpt ) ) return $post->post_excerpt;
$content = excerpt_remove_blocks( strip_shortcodes( $post->post_content ) );
return wp_trim_words( wp_strip_all_tags( $content ), 40, '' );
}
/** Single source of truth for meta description AND og:description. */
private function get_description( $ctx ) {
$id = $ctx['id'];
$desc = '';
switch ( $ctx['kind'] ) {
case 'front':
$desc = get_option( self::OPT_HOME_DESC );
if ( ! $desc && $id ) $desc = $this->post_description( $id );
if ( ! $desc ) $desc = get_bloginfo( 'description' );
break;
case 'posts_page':
case 'singular':
$desc = $this->post_description( $id );
break;
case 'term':
$obj = get_queried_object();
$desc = ( $obj && isset( $obj->description ) ) ? $obj->description : '';
break;
case 'author':
$desc = $id ? get_the_author_meta( 'description', $id ) : '';
break;
}
return $this->truncate( $desc, 160 );
}
private function fallback_title( $ctx ) {
$id = $ctx['id'];
switch ( $ctx['kind'] ) {
case 'front':
$title = get_bloginfo( 'name' );
$tagline = get_bloginfo( 'description' );
return $tagline ? $title . ' | ' . $tagline : $title;
case 'posts_page':
case 'singular':
return $id ? wp_strip_all_tags( get_the_title( $id ) ) : get_bloginfo( 'name' );
case 'term':
return single_term_title( '', false );
case 'author':
return (string) get_the_author_meta( 'display_name', $id );
}
return get_bloginfo( 'name' );
}
/* ============================================================
* FRONTEND — META DESCRIPTION
* ============================================================ */
public function output_meta_tags() {
$desc = $this->get_description( $this->get_context() );
if ( '' !== $desc ) {
echo ' ' . "\n";
}
}
/* ============================================================
* FRONTEND — CANONICAL + ROBOTS
* ============================================================ */
private function get_canonical_url() {
$ctx = $this->get_context();
$paged = $this->paged();
$url = '';
switch ( $ctx['kind'] ) {
case 'singular':
$url = wp_get_canonical_url( $ctx['id'] );
break;
case 'front':
$url = ( $paged > 1 ) ? get_pagenum_link( $paged ) : home_url( '/' );
break;
case 'posts_page':
$url = $ctx['id'] ? get_permalink( $ctx['id'] ) : home_url( '/' );
if ( $paged > 1 ) $url = get_pagenum_link( $paged );
break;
case 'term':
$obj = get_queried_object();
$url = $obj ? get_term_link( $obj ) : '';
if ( is_wp_error( $url ) ) $url = '';
if ( $url && $paged > 1 ) $url = get_pagenum_link( $paged );
break;
case 'author':
$url = get_author_posts_url( $ctx['id'] );
if ( $paged > 1 ) $url = get_pagenum_link( $paged );
break;
case 'pt_archive':
$url = get_post_type_archive_link( get_query_var( 'post_type' ) );
if ( $url && $paged > 1 ) $url = get_pagenum_link( $paged );
break;
}
return (string) apply_filters( 'advanced_seo_canonical', $url ?: '', $ctx );
}
public function output_canonical() {
$url = $this->get_canonical_url();
if ( $url ) {
echo ' ' . "\n";
}
}
public function filter_robots( $robots ) {
$ctx = $this->get_context();
if ( in_array( $ctx['kind'], [ 'search', '404' ], true ) ) {
$robots['noindex'] = true;
$robots['follow'] = true;
}
// Off by default (Google no longer recommends noindex on pagination).
if ( apply_filters( 'advanced_seo_noindex_paginated', false ) && $this->paged() > 1 && 'singular' !== $ctx['kind'] ) {
$robots['noindex'] = true;
$robots['follow'] = true;
}
if ( 'singular' === $ctx['kind'] && $ctx['id'] && '1' === get_post_meta( $ctx['id'], self::META_NOINDEX, true ) ) {
$robots['noindex'] = true;
$robots['follow'] = true;
}
return $robots;
}
public function sitemap_exclude_noindex( $args, $post_type ) {
$clause = [
'relation' => 'OR',
[ 'key' => self::META_NOINDEX, 'compare' => 'NOT EXISTS' ],
[ 'key' => self::META_NOINDEX, 'value' => '1', 'compare' => '!=' ],
];
if ( empty( $args['meta_query'] ) ) {
$args['meta_query'] = [ $clause ];
} else {
$args['meta_query'][] = $clause;
}
return $args;
}
/* ============================================================
* FRONTEND — OPEN GRAPH + TWITTER CARD
* ============================================================ */
public function output_og_tags() {
if ( is_feed() || is_404() ) return;
$data = $this->get_og_data();
if ( empty( $data ) || empty( $data['title'] ) ) return;
$data = apply_filters( 'advanced_seo_og_data', $data );
$data = wp_parse_args( (array) $data, [
'title' => '', 'description' => '', 'url' => '', 'type' => 'website',
'image' => '', 'image_width' => 0, 'image_height' => 0, 'image_alt' => '',
'published_time' => '', 'modified_time' => '', 'section' => '',
] );
if ( '' === $data['title'] ) return;
echo "\n\n";
$tags = [
'og:type' => $data['type'],
'og:site_name' => get_bloginfo( 'name' ),
'og:title' => $data['title'],
'og:description' => $data['description'],
'og:url' => $data['url'],
'og:locale' => get_locale(),
];
if ( ! empty( $data['image'] ) ) {
$tags['og:image'] = $data['image'];
$tags['og:image:alt'] = $data['image_alt'];
if ( ! empty( $data['image_width'] ) ) $tags['og:image:width'] = $data['image_width'];
if ( ! empty( $data['image_height'] ) ) $tags['og:image:height'] = $data['image_height'];
}
foreach ( $tags as $prop => $content ) {
if ( '' === $content || null === $content ) continue;
printf( ' ' . "\n", esc_attr( $prop ), esc_attr( $content ) );
}
if ( 'article' === $data['type'] ) {
foreach ( [
'article:published_time' => $data['published_time'],
'article:modified_time' => $data['modified_time'],
'article:section' => $data['section'],
] as $prop => $content ) {
if ( $content ) printf( ' ' . "\n", esc_attr( $prop ), esc_attr( $content ) );
}
}
// Twitter Card
$card = ! empty( $data['image'] ) ? 'summary_large_image' : 'summary';
printf( ' ' . "\n", esc_attr( $card ) );
printf( ' ' . "\n", esc_attr( $data['title'] ) );
if ( $data['description'] ) {
printf( ' ' . "\n", esc_attr( $data['description'] ) );
}
if ( ! empty( $data['image'] ) ) {
printf( ' ' . "\n", esc_url( $data['image'] ) );
}
}
private function get_og_data() {
$ctx = $this->get_context();
$kind = $ctx['kind'];
$id = $ctx['id'];
if ( ! in_array( $kind, [ 'front', 'posts_page', 'singular', 'term', 'author' ], true ) ) return [];
$title = $this->get_seo_title( $ctx );
if ( '' === $title ) $title = $this->fallback_title( $ctx );
$url = $this->get_canonical_url();
if ( ! $url ) $url = home_url( '/' );
$type = 'website';
$post = null;
if ( 'singular' === $kind ) {
$post = get_post( $id );
if ( ! $post ) return [];
if ( 'post' === $post->post_type ) $type = 'article';
}
$post_id = in_array( $kind, [ 'front', 'posts_page', 'singular' ], true ) ? $id : 0;
$data = $this->build_og_data( $title, $this->get_description( $ctx ), $url, $type, $post_id );
if ( 'article' === $type && $post ) {
$data['published_time'] = get_the_date( 'c', $post );
$data['modified_time'] = get_the_modified_date( 'c', $post );
$cats = get_the_category( $post->ID );
if ( ! empty( $cats ) ) $data['section'] = $cats[0]->name;
}
return $data;
}
private function build_og_data( $title, $desc, $url, $type, $post_id = 0 ) {
// Image chain: per-post override → featured → default option → site icon
$image_id = 0;
if ( $post_id ) {
$image_id = (int) get_post_meta( $post_id, self::META_OG_IMAGE, true );
if ( ! $image_id && has_post_thumbnail( $post_id ) ) {
$image_id = (int) get_post_thumbnail_id( $post_id );
}
}
if ( ! $image_id ) {
$image_id = (int) get_option( self::OPT_DEFAULT_OG );
}
$image = '';
$w = 0;
$h = 0;
$alt = $title;
if ( $image_id ) {
// Prefers the 1200×630 crop; falls back to full if not generated yet.
$src = wp_get_attachment_image_src( $image_id, self::OG_IMAGE_SIZE );
if ( $src ) {
$image = $src[0];
$w = (int) $src[1];
$h = (int) $src[2];
$alt_meta = get_post_meta( $image_id, '_wp_attachment_image_alt', true );
if ( $alt_meta ) $alt = $alt_meta;
}
}
if ( ! $image ) {
$image = get_site_icon_url( 512 );
}
return [
'title' => $title,
'description' => $desc,
'url' => $url,
'type' => $type,
'image' => $image,
'image_width' => $w,
'image_height' => $h,
'image_alt' => $alt,
];
}
/* ============================================================
* FRONTEND — FAQ SCHEMA (JSON-LD) + VISIBLE SHORTCODE
* ============================================================ */
private function get_faq( $post_id ) {
$faq = get_post_meta( $post_id, self::META_FAQ, true );
return ( is_array( $faq ) && ! empty( $faq ) ) ? $faq : [];
}
public function output_faq_schema() {
if ( ! is_singular() ) return;
$faq_data = $this->get_faq( get_queried_object_id() );
if ( empty( $faq_data ) ) return;
$main_entity = [];
foreach ( $faq_data as $faq ) {
$q = isset( $faq['question'] ) ? wp_strip_all_tags( $faq['question'] ) : '';
$a = isset( $faq['answer'] ) ? trim( wp_kses( $faq['answer'], $this->faq_allowed_html() ) ) : '';
if ( '' === $q || '' === $a ) continue;
$main_entity[] = [
'@type' => 'Question',
'name' => $q,
'acceptedAnswer' => [
'@type' => 'Answer',
'text' => $a,
],
];
}
if ( empty( $main_entity ) ) return;
$this->print_jsonld( [
'@context' => 'https://schema.org',
'@type' => 'FAQPage',
'mainEntity' => $main_entity,
] );
}
/** [seo_faq] — renders the visible FAQ that the JSON-LD describes. */
public function shortcode_faq( $atts ) {
$atts = shortcode_atts( [ 'id' => 0 ], $atts, 'seo_faq' );
$post_id = (int) $atts['id'] ?: (int) get_the_ID();
if ( ! $post_id ) return '';
$faq = $this->get_faq( $post_id );
if ( empty( $faq ) ) return '';
$html = '';
foreach ( $faq as $item ) {
if ( empty( $item['question'] ) || empty( $item['answer'] ) ) continue;
$html .= '
'
. '
' . esc_html( $item['question'] ) . ' '
. '
' . wpautop( wp_kses( $item['answer'], $this->faq_allowed_html() ) ) . '
'
. '
';
}
$html .= '
';
return $html;
}
/* ============================================================
* FRONTEND — BUSINESS SCHEMA
* ============================================================ */
public function output_business_schema() {
if ( ! is_front_page() || is_paged() ) return;
$name = get_option( self::OPT_BIZ_NAME );
if ( empty( $name ) ) return;
$type = $this->sanitize_biz_type( get_option( self::OPT_BIZ_TYPE ) );
$schema = [
'@context' => 'https://schema.org',
'@type' => $type,
'@id' => home_url( '/#organization' ),
'name' => $name,
'url' => home_url( '/' ),
];
if ( $phone = get_option( self::OPT_BIZ_PHONE ) ) $schema['telephone'] = $phone;
if ( $email = get_option( self::OPT_BIZ_EMAIL ) ) $schema['email'] = $email;
if ( $price = get_option( self::OPT_BIZ_PRICE ) ) $schema['priceRange'] = $price;
$logo_id = (int) get_option( self::OPT_BIZ_LOGO );
if ( $logo_id ) {
$logo_url = wp_get_attachment_image_url( $logo_id, 'full' );
if ( $logo_url ) {
$schema['image'] = $logo_url;
$schema['logo'] = [ '@type' => 'ImageObject', 'url' => $logo_url ];
}
}
$street = get_option( self::OPT_BIZ_STREET );
$city = get_option( self::OPT_BIZ_CITY );
$country = get_option( self::OPT_BIZ_COUNTRY );
if ( $street || $city || $country ) {
$schema['address'] = array_filter( [
'@type' => 'PostalAddress',
'streetAddress' => $street,
'addressLocality' => $city,
'addressCountry' => $country,
] );
}
$lat = get_option( self::OPT_BIZ_LAT );
$lng = get_option( self::OPT_BIZ_LNG );
if ( '' !== (string) $lat && '' !== (string) $lng ) {
$schema['geo'] = [
'@type' => 'GeoCoordinates',
'latitude' => (float) $lat,
'longitude' => (float) $lng,
];
}
$hours = get_option( self::OPT_BIZ_HOURS );
if ( $hours ) {
$lines = array_values( array_filter( array_map( 'trim', preg_split( '/\r\n|\r|\n/', $hours ) ) ) );
if ( $lines ) $schema['openingHours'] = $lines;
}
$areas = get_option( self::OPT_BIZ_AREAS );
if ( $areas ) {
$codes = array_values( array_filter( array_map( 'trim', explode( ',', $areas ) ) ) );
if ( $codes ) {
$schema['areaServed'] = array_map( function ( $c ) {
return [ '@type' => 'Country', 'name' => strtoupper( $c ) ];
}, $codes );
}
}
$same_as = get_option( self::OPT_BIZ_SAMEAS );
if ( $same_as ) {
$urls = array_values( array_filter( array_map( 'trim', preg_split( '/\r\n|\r|\n/', $same_as ) ) ) );
if ( $urls ) $schema['sameAs'] = $urls;
}
$schema = apply_filters( 'advanced_seo_business_schema', $schema );
if ( ! empty( $schema ) && is_array( $schema ) ) {
$this->print_jsonld( $schema );
}
}
/* ============================================================
* UNINSTALL
* ============================================================ */
public static function uninstall() {
$options = [
self::OPT_HOME_TITLE, self::OPT_HOME_DESC, self::OPT_DEFAULT_OG, self::OPT_BIZ_TYPE,
self::OPT_BIZ_NAME, self::OPT_BIZ_PHONE, self::OPT_BIZ_EMAIL, self::OPT_BIZ_STREET,
self::OPT_BIZ_CITY, self::OPT_BIZ_COUNTRY, self::OPT_BIZ_AREAS, self::OPT_BIZ_LOGO,
self::OPT_BIZ_SAMEAS, self::OPT_BIZ_LAT, self::OPT_BIZ_LNG, self::OPT_BIZ_HOURS,
self::OPT_BIZ_PRICE,
];
foreach ( $options as $opt ) {
delete_option( $opt );
}
foreach ( [ self::META_TITLE, self::META_DESC, self::META_OG_IMAGE, self::META_FAQ, self::META_NOINDEX ] as $key ) {
delete_post_meta_by_key( $key );
}
}
}
new Advanced_SEO_Meta();
register_uninstall_hook( __FILE__, [ 'Advanced_SEO_Meta', 'uninstall' ] );