1173 lines
52 KiB
PHP
1173 lines
52 KiB
PHP
<?php
|
||
/**
|
||
* Plugin Name: Advanced SEO Meta + AI FAQ Schema
|
||
* Plugin URI: https://my-dev.pro/advanced-seo-meta
|
||
* Description: SEO meta box (Title, Description, OG Image, Noindex) + FAQ JSON-LD & shortcode + Homepage SEO + canonical/robots + LocalBusiness-family schema.
|
||
* Version: 4.1.0
|
||
* Requires at least: 5.7
|
||
* Requires PHP: 7.4
|
||
* Author: MYDev
|
||
* Author URI: https://my-dev.pro
|
||
* License: GPL-2.0+
|
||
* Text Domain: advanced-seo-meta
|
||
* Domain Path: /languages
|
||
*/
|
||
|
||
if ( ! defined( 'ABSPATH' ) ) exit;
|
||
|
||
class Advanced_SEO_Meta {
|
||
|
||
const VERSION = '4.1.0';
|
||
const NONCE = 'advanced_seo_nonce';
|
||
|
||
// Post meta keys
|
||
const META_TITLE = '_seo_title';
|
||
const META_DESC = '_seo_description';
|
||
const META_OG_IMAGE = '_seo_og_image_id';
|
||
const META_FAQ = '_seo_faq';
|
||
const META_NOINDEX = '_seo_noindex';
|
||
|
||
// Option keys
|
||
const OPT_HOME_TITLE = '_seo_home_title';
|
||
const OPT_HOME_DESC = '_seo_home_description';
|
||
const OPT_DEFAULT_OG = '_seo_default_og_image';
|
||
const OPT_BIZ_TYPE = '_seo_biz_type';
|
||
const OPT_BIZ_NAME = '_seo_biz_name';
|
||
const OPT_BIZ_PHONE = '_seo_biz_phone';
|
||
const OPT_BIZ_EMAIL = '_seo_biz_email';
|
||
const OPT_BIZ_STREET = '_seo_biz_street';
|
||
const OPT_BIZ_CITY = '_seo_biz_city';
|
||
const OPT_BIZ_COUNTRY = '_seo_biz_country';
|
||
const OPT_BIZ_AREAS = '_seo_biz_areas';
|
||
const OPT_BIZ_LOGO = '_seo_biz_logo';
|
||
const OPT_BIZ_SAMEAS = '_seo_biz_sameas';
|
||
const OPT_BIZ_LAT = '_seo_biz_lat';
|
||
const OPT_BIZ_LNG = '_seo_biz_lng';
|
||
const OPT_BIZ_HOURS = '_seo_biz_hours';
|
||
const OPT_BIZ_PRICE = '_seo_biz_price';
|
||
|
||
const OG_IMAGE_SIZE = 'advanced_seo_og';
|
||
|
||
/** @var array|null Cached request context. */
|
||
private $ctx = null;
|
||
|
||
public function __construct() {
|
||
add_action( 'plugins_loaded', [ $this, 'init' ], 20 );
|
||
}
|
||
|
||
public function init() {
|
||
// Shared
|
||
add_action( 'init', [ $this, 'on_init' ] );
|
||
|
||
// Admin
|
||
add_action( 'add_meta_boxes', [ $this, 'add_meta_box' ] );
|
||
add_action( 'save_post', [ $this, 'save_meta_data' ] );
|
||
add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
|
||
add_action( 'admin_menu', [ $this, 'register_settings_page' ] );
|
||
add_action( 'admin_init', [ $this, 'register_settings' ] );
|
||
add_action( 'admin_notices', [ $this, 'conflict_notice' ] );
|
||
|
||
// Frontend: always-safe output (schema + shortcode)
|
||
add_action( 'wp_head', [ $this, 'output_faq_schema' ], 5 );
|
||
add_action( 'wp_head', [ $this, 'output_business_schema' ], 6 );
|
||
add_shortcode( 'seo_faq', [ $this, 'shortcode_faq' ] );
|
||
|
||
// Sitemaps: exclude noindex posts
|
||
add_filter( 'wp_sitemaps_posts_query_args', [ $this, 'sitemap_exclude_noindex' ], 10, 2 );
|
||
|
||
// Frontend: title / description / OG / canonical / robots.
|
||
// Skipped when another SEO plugin is active (unless forced via filter).
|
||
if ( ! $this->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 '<div class="notice notice-warning"><p><strong>Advanced SEO Meta:</strong> '
|
||
. 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' )
|
||
. '</p></div>';
|
||
}
|
||
|
||
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 '<script type="application/ld+json">'
|
||
. wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP )
|
||
. '</script>' . "\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(
|
||
$('<img>').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();
|
||
?>
|
||
<div class="faq-row">
|
||
<p><span class="dashicons dashicons-menu faq-handle" style="cursor:move;" title="<?php esc_attr_e( 'Drag to reorder', 'advanced-seo-meta' ); ?>"></span>
|
||
<label><?php esc_html_e( 'Question:', 'advanced-seo-meta' ); ?></label>
|
||
<input type="text" name="faq_question[]" value="<?php echo esc_attr( $question ); ?>" placeholder="<?php echo esc_attr( $ph_q ); ?>" style="width:100%;" /></p>
|
||
<p><label><?php esc_html_e( 'Answer (basic HTML allowed: p, br, ul, ol, li, a, strong, em, headings):', 'advanced-seo-meta' ); ?></label>
|
||
<textarea name="faq_answer[]" rows="3" placeholder="<?php echo esc_attr( $ph_a ); ?>" style="width:100%;"><?php echo esc_textarea( $answer ); ?></textarea></p>
|
||
<button type="button" class="remove-faq-row button button-small"><?php esc_html_e( 'Remove Question', 'advanced-seo-meta' ); ?></button>
|
||
</div>
|
||
<?php
|
||
return ob_get_clean();
|
||
}
|
||
|
||
public function render_meta_box( $post ) {
|
||
wp_nonce_field( self::NONCE, self::NONCE );
|
||
|
||
$seo_title = get_post_meta( $post->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 = [];
|
||
?>
|
||
<style>
|
||
.seo-field { margin-bottom: 20px; }
|
||
.seo-field > label { font-weight: 600; display: block; margin-bottom: 5px; }
|
||
.seo-field input[type="text"], .seo-field textarea { width: 100%; max-width: 700px; }
|
||
.seo-counter { display: block; font-size: 12px; margin-top: 3px; }
|
||
.faq-row { background: #f5f5f5; padding: 15px; margin-bottom: 15px; border: 1px solid #ddd; border-radius: 4px; }
|
||
.seo-image-preview img { display: block; }
|
||
#faq-dupe-warning { display: none; }
|
||
</style>
|
||
|
||
<div class="seo-field">
|
||
<label for="seo_title"><?php esc_html_e( 'SEO Title (search results — aim for ~60 characters)', 'advanced-seo-meta' ); ?></label>
|
||
<input type="text" id="seo_title" name="seo_title" class="seo-count" data-min="30" data-max="60"
|
||
value="<?php echo esc_attr( $seo_title ); ?>"
|
||
placeholder="<?php esc_attr_e( 'e.g., Comprehensive Genomic Profiling & WES for Precision Oncology', 'advanced-seo-meta' ); ?>" />
|
||
<span class="seo-counter"></span>
|
||
</div>
|
||
|
||
<div class="seo-field">
|
||
<label for="seo_description"><?php esc_html_e( 'Meta Description (150–160 characters)', 'advanced-seo-meta' ); ?></label>
|
||
<textarea id="seo_description" name="seo_description" class="seo-count" data-min="120" data-max="160" rows="3"><?php echo esc_textarea( $seo_description ); ?></textarea>
|
||
<span class="seo-counter"></span>
|
||
</div>
|
||
|
||
<div class="seo-field">
|
||
<label>
|
||
<input type="checkbox" name="seo_noindex" value="1" <?php checked( $noindex ); ?> />
|
||
<?php esc_html_e( 'Hide this page from search engines (noindex) and exclude it from the XML sitemap', 'advanced-seo-meta' ); ?>
|
||
</label>
|
||
</div>
|
||
|
||
<div class="seo-field seo-image-field">
|
||
<label><?php esc_html_e( 'Social Share Image (og:image)', 'advanced-seo-meta' ); ?></label>
|
||
<p class="description"><?php esc_html_e( 'Recommended size: 1200×630px. If left empty, falls back to the Featured Image, then the Default OG Image in Settings.', 'advanced-seo-meta' ); ?></p>
|
||
<input type="hidden" name="seo_og_image_id" value="<?php echo esc_attr( $og_image_id ); ?>" />
|
||
<div class="seo-image-preview" style="margin:10px 0;">
|
||
<?php if ( $og_image_id ) echo wp_get_attachment_image( $og_image_id, 'medium', false, [ 'style' => 'max-width:300px;height:auto;border:1px solid #ddd;' ] ); ?>
|
||
</div>
|
||
<button type="button" class="button seo-image-upload"><?php esc_html_e( 'Choose / Upload Image', 'advanced-seo-meta' ); ?></button>
|
||
<button type="button" class="button seo-image-remove" style="<?php echo $og_image_id ? '' : 'display:none;'; ?>"><?php esc_html_e( 'Remove', 'advanced-seo-meta' ); ?></button>
|
||
</div>
|
||
|
||
<hr style="margin: 30px 0;" />
|
||
|
||
<h3 style="margin-top:0;"><?php esc_html_e( 'FAQ Schema (FAQPage JSON-LD)', 'advanced-seo-meta' ); ?></h3>
|
||
<p class="description">
|
||
<?php esc_html_e( 'Google requires FAQ markup to match content that is visible on the page. Place the shortcode [seo_faq] in your content (or call it from your template) to display these Q&As. Note: Google currently shows FAQ rich results only for well-known government and health authority sites; the markup remains valid structured data.', 'advanced-seo-meta' ); ?>
|
||
</p>
|
||
<div class="notice notice-warning inline" id="faq-dupe-warning"><p><?php esc_html_e( 'Duplicate questions detected — each question should be unique.', 'advanced-seo-meta' ); ?></p></div>
|
||
|
||
<div id="faq-container">
|
||
<?php
|
||
if ( ! empty( $faq_data ) ) {
|
||
foreach ( $faq_data as $faq ) {
|
||
echo $this->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
|
||
}
|
||
?>
|
||
</div>
|
||
|
||
<script type="text/template" id="faq-row-template"><?php echo $this->render_faq_row( '', '', true ); // phpcs:ignore WordPress.Security.EscapeOutput ?></script>
|
||
|
||
<button type="button" class="add-faq-row button button-primary"><?php esc_html_e( '+ Add New FAQ', 'advanced-seo-meta' ); ?></button>
|
||
<?php
|
||
}
|
||
|
||
private function save_or_delete_meta( $post_id, $key, $value ) {
|
||
if ( '' === $value || 0 === $value || null === $value || ( is_array( $value ) && empty( $value ) ) ) {
|
||
delete_post_meta( $post_id, $key );
|
||
} else {
|
||
update_post_meta( $post_id, $key, $value );
|
||
}
|
||
}
|
||
|
||
public function save_meta_data( $post_id ) {
|
||
if ( ! isset( $_POST[ self::NONCE ] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[ self::NONCE ] ) ), self::NONCE ) ) return;
|
||
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
|
||
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) return;
|
||
if ( ! in_array( get_post_type( $post_id ), $this->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 ) {
|
||
?>
|
||
<div class="seo-image-field">
|
||
<input type="hidden" name="<?php echo esc_attr( $option ); ?>" value="<?php echo esc_attr( $id ); ?>" />
|
||
<div class="seo-image-preview" style="margin:10px 0;">
|
||
<?php if ( $id ) echo wp_get_attachment_image( $id, 'medium', false, [ 'style' => 'max-width:300px;height:auto;border:1px solid #ddd;' ] ); ?>
|
||
</div>
|
||
<button type="button" class="button seo-image-upload"><?php echo esc_html( $button_label ); ?></button>
|
||
<button type="button" class="button seo-image-remove" style="<?php echo $id ? '' : 'display:none;'; ?>"><?php esc_html_e( 'Remove', 'advanced-seo-meta' ); ?></button>
|
||
</div>
|
||
<?php
|
||
}
|
||
|
||
public function render_settings_page() {
|
||
if ( ! current_user_can( 'manage_options' ) ) return;
|
||
|
||
$default_og = (int) get_option( self::OPT_DEFAULT_OG );
|
||
$logo_id = (int) get_option( self::OPT_BIZ_LOGO );
|
||
?>
|
||
<style>.seo-counter{display:block;font-size:12px;margin-top:3px;}</style>
|
||
<div class="wrap">
|
||
<h1><?php esc_html_e( 'Advanced SEO Settings', 'advanced-seo-meta' ); ?></h1>
|
||
|
||
<form method="post" action="options.php">
|
||
<?php settings_fields( 'advanced_seo_settings' ); ?>
|
||
|
||
<h2><?php esc_html_e( 'Homepage SEO', 'advanced-seo-meta' ); ?></h2>
|
||
<table class="form-table" role="presentation">
|
||
<tr>
|
||
<th scope="row"><label for="<?php echo esc_attr( self::OPT_HOME_TITLE ); ?>"><?php esc_html_e( 'Homepage Title (~60 chars)', 'advanced-seo-meta' ); ?></label></th>
|
||
<td>
|
||
<input type="text" class="regular-text seo-count" data-min="30" data-max="60"
|
||
id="<?php echo esc_attr( self::OPT_HOME_TITLE ); ?>"
|
||
name="<?php echo esc_attr( self::OPT_HOME_TITLE ); ?>"
|
||
value="<?php echo esc_attr( get_option( self::OPT_HOME_TITLE ) ); ?>"
|
||
placeholder="Codex Genetics Center | Trusted Genetics Test Lab in Cairo" />
|
||
<span class="seo-counter"></span>
|
||
</td>
|
||
</tr>
|
||
<tr>
|
||
<th scope="row"><label for="<?php echo esc_attr( self::OPT_HOME_DESC ); ?>"><?php esc_html_e( 'Homepage Meta Description (150–160 chars)', 'advanced-seo-meta' ); ?></label></th>
|
||
<td>
|
||
<textarea class="large-text seo-count" data-min="120" data-max="160" rows="3"
|
||
id="<?php echo esc_attr( self::OPT_HOME_DESC ); ?>"
|
||
name="<?php echo esc_attr( self::OPT_HOME_DESC ); ?>"><?php echo esc_textarea( get_option( self::OPT_HOME_DESC ) ); ?></textarea>
|
||
<span class="seo-counter"></span>
|
||
</td>
|
||
</tr>
|
||
<tr>
|
||
<th scope="row"><?php esc_html_e( 'Default OG Image (1200×630)', 'advanced-seo-meta' ); ?></th>
|
||
<td><?php $this->render_image_field( self::OPT_DEFAULT_OG, $default_og, __( 'Choose / Upload Image', 'advanced-seo-meta' ) ); ?></td>
|
||
</tr>
|
||
</table>
|
||
|
||
<h2><?php esc_html_e( 'Business Schema', 'advanced-seo-meta' ); ?></h2>
|
||
<p class="description"><?php esc_html_e( 'Output on the homepage as JSON-LD. Leave Business Name blank to disable.', 'advanced-seo-meta' ); ?></p>
|
||
<table class="form-table" role="presentation">
|
||
<?php
|
||
$fields = [
|
||
self::OPT_BIZ_TYPE => [ __( 'Schema Type', 'advanced-seo-meta' ), '', 'select' ],
|
||
self::OPT_BIZ_NAME => [ __( 'Business Name', 'advanced-seo-meta' ), 'Codex Genetics Center', 'text' ],
|
||
self::OPT_BIZ_PHONE => [ __( 'Phone', 'advanced-seo-meta' ), '+20 155 800 2030', 'text' ],
|
||
self::OPT_BIZ_EMAIL => [ __( 'Email', 'advanced-seo-meta' ), 'info@example.com', 'email' ],
|
||
self::OPT_BIZ_STREET => [ __( 'Street Address', 'advanced-seo-meta' ), '32 Mesadaq St., Dokki', 'text' ],
|
||
self::OPT_BIZ_CITY => [ __( 'City', 'advanced-seo-meta' ), 'Giza', 'text' ],
|
||
self::OPT_BIZ_COUNTRY => [ __( 'Country Code (2-letter)', 'advanced-seo-meta' ), 'EG', 'text' ],
|
||
self::OPT_BIZ_LAT => [ __( 'Latitude', 'advanced-seo-meta' ), '30.0382', 'text' ],
|
||
self::OPT_BIZ_LNG => [ __( 'Longitude', 'advanced-seo-meta' ), '31.2118', 'text' ],
|
||
self::OPT_BIZ_HOURS => [ __( 'Opening Hours (one per line, e.g. Mo-Fr 09:00-17:00)', 'advanced-seo-meta' ), "Mo-Th 09:00-17:00\nSa 10:00-14:00", 'textarea' ],
|
||
self::OPT_BIZ_PRICE => [ __( 'Price Range', 'advanced-seo-meta' ), '$$', 'text' ],
|
||
self::OPT_BIZ_AREAS => [ __( 'Areas Served (comma-separated ISO codes)', 'advanced-seo-meta' ), 'EG, SA, LY, AE', 'text' ],
|
||
self::OPT_BIZ_SAMEAS => [ __( 'Social / Profile URLs (one per line)', 'advanced-seo-meta' ), "https://www.facebook.com/yourpage\nhttps://www.linkedin.com/company/yourco", 'textarea' ],
|
||
];
|
||
foreach ( $fields as $key => $cfg ) :
|
||
[ $label, $placeholder, $type ] = $cfg;
|
||
$value = get_option( $key );
|
||
?>
|
||
<tr>
|
||
<th scope="row"><label for="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $label ); ?></label></th>
|
||
<td>
|
||
<?php if ( 'select' === $type ) : ?>
|
||
<select id="<?php echo esc_attr( $key ); ?>" name="<?php echo esc_attr( $key ); ?>">
|
||
<?php foreach ( $this->business_types() as $val => $lab ) : ?>
|
||
<option value="<?php echo esc_attr( $val ); ?>" <?php selected( $value ?: 'MedicalBusiness', $val ); ?>><?php echo esc_html( $lab ); ?></option>
|
||
<?php endforeach; ?>
|
||
</select>
|
||
<?php elseif ( 'textarea' === $type ) : ?>
|
||
<textarea class="large-text" rows="3" id="<?php echo esc_attr( $key ); ?>"
|
||
name="<?php echo esc_attr( $key ); ?>"
|
||
placeholder="<?php echo esc_attr( $placeholder ); ?>"><?php echo esc_textarea( $value ); ?></textarea>
|
||
<?php else : ?>
|
||
<input type="<?php echo 'email' === $type ? 'email' : 'text'; ?>" class="regular-text"
|
||
id="<?php echo esc_attr( $key ); ?>" name="<?php echo esc_attr( $key ); ?>"
|
||
value="<?php echo esc_attr( $value ); ?>"
|
||
placeholder="<?php echo esc_attr( $placeholder ); ?>" />
|
||
<?php endif; ?>
|
||
</td>
|
||
</tr>
|
||
<?php endforeach; ?>
|
||
<tr>
|
||
<th scope="row"><?php esc_html_e( 'Logo', 'advanced-seo-meta' ); ?></th>
|
||
<td><?php $this->render_image_field( self::OPT_BIZ_LOGO, $logo_id, __( 'Choose / Upload Logo', 'advanced-seo-meta' ) ); ?></td>
|
||
</tr>
|
||
</table>
|
||
|
||
<?php submit_button(); ?>
|
||
</form>
|
||
</div>
|
||
<?php
|
||
}
|
||
|
||
/* ============================================================
|
||
* FRONTEND — TITLE / DESCRIPTION RESOLUTION
|
||
* ============================================================ */
|
||
|
||
/** Custom SEO title for the current context, or '' if none. */
|
||
private function get_seo_title( $ctx ) {
|
||
$id = $ctx['id'];
|
||
switch ( $ctx['kind'] ) {
|
||
case 'front':
|
||
$t = get_option( self::OPT_HOME_TITLE );
|
||
if ( ! $t && $id ) $t = get_post_meta( $id, self::META_TITLE, true );
|
||
return (string) $t;
|
||
case 'posts_page':
|
||
case 'singular':
|
||
return $id ? (string) get_post_meta( $id, self::META_TITLE, true ) : '';
|
||
}
|
||
return '';
|
||
}
|
||
|
||
public function custom_title( $title ) {
|
||
$custom = $this->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 '<meta name="description" content="' . esc_attr( $desc ) . '" />' . "\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 '<link rel="canonical" href="' . esc_url( $url ) . '" />' . "\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<!-- Advanced SEO Meta: Open Graph -->\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( '<meta property="%s" content="%s" />' . "\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( '<meta property="%s" content="%s" />' . "\n", esc_attr( $prop ), esc_attr( $content ) );
|
||
}
|
||
}
|
||
|
||
// Twitter Card
|
||
$card = ! empty( $data['image'] ) ? 'summary_large_image' : 'summary';
|
||
printf( '<meta name="twitter:card" content="%s" />' . "\n", esc_attr( $card ) );
|
||
printf( '<meta name="twitter:title" content="%s" />' . "\n", esc_attr( $data['title'] ) );
|
||
if ( $data['description'] ) {
|
||
printf( '<meta name="twitter:description" content="%s" />' . "\n", esc_attr( $data['description'] ) );
|
||
}
|
||
if ( ! empty( $data['image'] ) ) {
|
||
printf( '<meta name="twitter:image" content="%s" />' . "\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 = '<div class="advanced-seo-faq">';
|
||
foreach ( $faq as $item ) {
|
||
if ( empty( $item['question'] ) || empty( $item['answer'] ) ) continue;
|
||
$html .= '<div class="advanced-seo-faq__item">'
|
||
. '<h3 class="advanced-seo-faq__question">' . esc_html( $item['question'] ) . '</h3>'
|
||
. '<div class="advanced-seo-faq__answer">' . wpautop( wp_kses( $item['answer'], $this->faq_allowed_html() ) ) . '</div>'
|
||
. '</div>';
|
||
}
|
||
$html .= '</div>';
|
||
|
||
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' ] );
|