diff --git a/README.md b/README.md index 47b3cb2..650a8ab 100644 --- a/README.md +++ b/README.md @@ -1,103 +1,317 @@ - # Advanced SEO Meta + AI FAQ Schema -Advanced SEO Meta + AI FAQ Schema is a lightweight WordPress plugin that adds fine-grained control over page titles, meta descriptions, Open Graph tags, and automatic JSON-LD FAQ output to improve visibility in classic search and AI-powered search experiences. +A lightweight WordPress plugin for precise control over page titles, meta descriptions, Open Graph / Twitter cards, canonical and robots tags, FAQ structured data, and business (local) schema. -![Version](https://img.shields.io/badge/version-3.0.0-blue.svg) ![WordPress](https://img.shields.io/badge/wordpress-5.8%2B-brightgreen.svg) ![PHP](https://img.shields.io/badge/php-7.4%2B-8892BF.svg) +[![Version](https://img.shields.io/badge/version-4.1.0-blue.svg)](#changelog) +[![WordPress](https://img.shields.io/badge/wordpress-5.7%2B-brightgreen.svg)](#requirements) +[![PHP](https://img.shields.io/badge/php-7.4%2B-8892BF.svg)](#requirements) +[![License](https://img.shields.io/badge/license-GPL--2.0%2B-lightgrey.svg)](#license) -## Summary +## Table of contents -- One-line: Add custom SEO title, meta description, Open Graph and FAQ JSON-LD for posts and pages. - -## Requirements - -- WordPress 5.8 or later -- PHP 7.4 or later +- [Features](#features) +- [Requirements](#requirements) +- [Installation](#installation) +- [Upgrading from 3.x](#upgrading-from-3x) +- [Usage](#usage) +- [Settings](#settings) +- [FAQ schema and the `[seo_faq]` shortcode](#faq-schema-and-the-seo_faq-shortcode) +- [What gets output on the front end](#what-gets-output-on-the-front-end) +- [Compatibility with other SEO plugins](#compatibility-with-other-seo-plugins) +- [Developer reference](#developer-reference) +- [Troubleshooting](#troubleshooting) +- [Uninstalling](#uninstalling) +- [Changelog](#changelog) +- [License](#license) ## Features -- Custom SEO title field for posts and pages -- Custom meta description field for improved search snippets -- FAQ builder to add multiple questions and answers per post/page -- Automatic JSON-LD `FAQPage` schema output for AI search engines (Google SGE, Bing Chat, etc.) -- Open Graph meta tags for Facebook, LinkedIn, and other social previews -- Clean meta box in the WordPress editor for quick optimization +**Per-post / per-page (meta box)** -## What the plugin adds +- Custom SEO title and meta description, with live character counters (title ~60, description 150–160) +- Social share image (`og:image`) override, with fallback to Featured Image, then the site default +- "Hide from search engines" (noindex) checkbox, which also removes the item from the core XML sitemap +- FAQ builder: drag-to-reorder rows, duplicate-question warning, basic HTML allowed in answers +- Works on every public post type (filterable) -When editing a post or page you can enter: +**Site-wide (Settings → Advanced SEO)** -- SEO Title -- Meta Description -- FAQ questions and answers +- Homepage title and description +- Default Open Graph image (1200×630 recommended) +- Business schema: `MedicalBusiness`, `MedicalClinic`, `DiagnosticLab`, `LocalBusiness` or `Organization`, with address, phone, email, geo, opening hours, price range, areas served and `sameAs` profiles -On the front end the plugin outputs: +**Front-end output** -- A page title override when provided -- A meta description tag -- Open Graph meta tags -- Structured FAQ schema in JSON-LD format +- `` override +- Meta description (one shared source for both `description` and `og:description`, trimmed at a word boundary to 160 characters) +- Canonical URL (replaces the core one, pagination-aware) +- Robots: `noindex` for search, 404 and flagged posts (via the core `wp_robots` filter) +- Open Graph and Twitter Card tags, including `article:*` tags for posts +- FAQPage JSON-LD and a visible `[seo_faq]` shortcode +- Business JSON-LD on the homepage +- Handles static front pages and separate posts pages correctly, plus category, tag, taxonomy and author archives + +## Requirements + +- WordPress 5.7 or later (uses the `wp_robots` filter) +- PHP 7.4 or later ## Installation -1. Upload the plugin folder to your WordPress installation's `wp-content/plugins/` directory and activate it under `Plugins` → `Installed Plugins`. -2. Or install from ZIP: `Plugins` → `Add New` → `Upload Plugin` → choose the ZIP and click `Install Now`. -3. After activation, edit any post or page and look for the "Advanced SEO & AI FAQ Schema" meta box in the editor. +**From a ZIP** + +1. Download the latest ZIP from [Releases](https://git.my-dev.pro/mydev/advanced-seo-keywords/releases). +2. In WordPress go to **Plugins → Add New → Upload Plugin**, choose the ZIP and click **Install Now**. +3. Click **Activate**. + +**Manually** + +1. Copy the plugin folder to `wp-content/plugins/advanced-seo-keywords/` (the main file is `advanced-seo-keywords.php`). +2. Activate it under **Plugins → Installed Plugins**, or run `wp plugin activate advanced-seo-keywords`. + +After activation: + +- Go to **Settings → Advanced SEO** and fill in the homepage and business details. +- Edit any post or page to see the **Advanced SEO & FAQ Schema** meta box. + +## Upgrading from 3.x + +Version 3.x and 4.x define the same PHP class (`Advanced_SEO_Meta`), so they cannot be active at the same time. + +1. Replace the plugin files in the **same folder** (`advanced-seo-keywords`), or deactivate and delete the old 3.x plugin first and then install 4.x. +2. Activate the plugin and confirm that **Settings → Advanced SEO** now exists. +3. Clear your caches (object cache, page cache and CDN). + +Your existing data is preserved. Version 4.x reads the same post meta keys (`_seo_title`, `_seo_description`, `_seo_faq`) as 3.x. + +> **Note:** the 3.x README listed `aseo_*` filters. Those were never implemented in the 3.x code. Use the `advanced_seo_*` filters documented [below](#developer-reference). ## Usage -1. Open a post or page in the editor. -2. Fill in the custom SEO Title and Meta Description as needed. -3. Use the FAQ builder to add one or more question/answer pairs. -4. Publish or update the post — the JSON-LD will be added to the page head automatically. +### Per post or page -### Example JSON-LD output +1. Open the editor and find the **Advanced SEO & FAQ Schema** box. +2. Fill in: + - **SEO Title** (counter turns green between 30 and 60 characters) + - **Meta Description** (green between 120 and 160 characters) + - **Noindex** if the page should stay out of search results and the sitemap + - **Social Share Image** (1200×630 recommended) + - **FAQ** question and answer pairs +3. Update the post. -```json -{ - "@context": "https://schema.org", - "@type": "FAQPage", - "mainEntity": [ - { - "@type": "Question", - "name": "What does this plugin do?", - "acceptedAnswer": { - "@type": "Answer", - "text": "It adds custom SEO title, meta description, Open Graph tags and FAQ JSON-LD to posts and pages." - } - } - ] -} +If a field is empty, the plugin falls back sensibly: + +| Value | Fallback chain | +|---|---| +| Title | Custom title → WordPress default title | +| Description | Custom description → manual excerpt → trimmed content (shortcodes and blocks stripped) | +| `og:image` | Per-post image → Featured Image → Default OG Image → Site Icon | + +### Homepage + +Set the homepage title, description and default OG image under **Settings → Advanced SEO**. If those are blank, the static front page's own SEO fields are used, then the site title and tagline. + +## Settings + +**Settings → Advanced SEO** + +| Section | Field | Notes | +|---|---|---| +| Homepage SEO | Title | ~60 characters | +| | Meta Description | 150–160 characters | +| | Default OG Image | Used when a page has no image of its own | +| Business Schema | Schema Type | `MedicalBusiness`, `MedicalClinic`, `DiagnosticLab`, `LocalBusiness`, `Organization` | +| | Business Name | Leave blank to disable the schema entirely | +| | Phone, Email | | +| | Street, City, Country (2-letter code) | Output as `PostalAddress` | +| | Latitude, Longitude | Output as `GeoCoordinates` | +| | Opening Hours | One per line, e.g. `Mo-Fr 09:00-17:00` | +| | Price Range | e.g. `$$` | +| | Areas Served | Comma-separated codes, output as `Country` objects | +| | Social / Profile URLs | One per line, output as `sameAs` | +| | Logo | Output as `logo` and `image` | + +Business schema is printed on the homepage only (first page, not paginated). + +## FAQ schema and the `[seo_faq]` shortcode + +The meta box stores question and answer pairs and prints them as `FAQPage` JSON-LD in the page head. + +Google requires FAQ markup to match content that is **visible on the page**. Display the same Q&As with the shortcode: + +``` +[seo_faq] ``` -## Configuration & Developer Hooks +Or for a specific post: -The plugin provides filters and actions so developers can modify output or integrate with other plugins: +``` +[seo_faq id="123"] +``` -- Filter `aseo_meta_title` — modify the computed SEO title -- Filter `aseo_meta_description` — modify the meta description -- Filter `aseo_faq_schema` — modify the generated FAQ JSON-LD array before encoding -- Action `aseo_faq_saved` — runs after FAQ entries are saved for a post - -Example (in your theme or plugin): +In a template: ```php -add_filter('aseo_meta_title', function($title, $post_id){ - return $title . ' | My Site'; -}, 10, 2); +echo do_shortcode( '[seo_faq]' ); ``` +The shortcode renders this markup, which you can style: + +```html +<div class="advanced-seo-faq"> + <div class="advanced-seo-faq__item"> + <h3 class="advanced-seo-faq__question">…</h3> + <div class="advanced-seo-faq__answer">…</div> + </div> +</div> +``` + +Allowed HTML in answers: `p`, `br`, `ul`, `ol`, `li`, `strong`, `b`, `em`, `i`, `a[href]` and headings `h2`–`h6`. + +> **About rich results:** since August 2023, Google shows FAQ rich results only for well-known government and health authority sites. The markup remains valid structured data, but do not expect expanded FAQ listings for most sites, and there is no verified evidence that it influences AI-generated answers. + +## What gets output on the front end + +| Tag | Source | +|---|---| +| `<title>` | `pre_get_document_title` filter | +| `<meta name="description">` | Shared description resolver | +| `<link rel="canonical">` | Own output; core `rel_canonical` is removed | +| `<meta name="robots">` | Core `wp_robots` filter (adds `noindex` where needed) | +| `og:*`, `article:*`, `twitter:*` | Open Graph block (look for the `Advanced SEO Meta: Open Graph` HTML comment) | +| FAQPage JSON-LD | Singular pages with FAQ entries | +| Business JSON-LD | Homepage, when a Business Name is set | + +Noindex is applied to search results, 404 pages and posts flagged in the meta box. Paginated archives stay indexable by default (see the `advanced_seo_noindex_paginated` filter). + +## Compatibility with other SEO plugins + +To avoid duplicate tags, the plugin detects Yoast SEO, Rank Math, All in One SEO, SEOPress and The SEO Framework. When one is active: + +- the title, description, Open Graph, canonical and robots output is turned off, +- FAQ and business schema are still printed, +- an admin notice appears on the Plugins page and on the settings page. + +Override this with the `advanced_seo_force_output` filter. + +## Developer reference + +### Filters + +| Filter | Arguments | Purpose | +|---|---|---| +| `advanced_seo_post_types` | `array $post_types` | Post types that get the meta box and REST fields (default: all public types except attachments) | +| `advanced_seo_og_data` | `array $data` | Modify Open Graph data before output | +| `advanced_seo_business_schema` | `array $schema` | Modify the business schema array, e.g. add a second location | +| `advanced_seo_canonical` | `string $url, array $ctx` | Modify the canonical URL | +| `advanced_seo_noindex_paginated` | `bool $noindex` (default `false`) | Return `true` to noindex paginated archives | +| `advanced_seo_force_output` | `bool $force` (default `false`) | Return `true` to keep frontend output even if another SEO plugin is active | + +Examples: + +```php +// Limit the plugin to posts and pages only. +add_filter( 'advanced_seo_post_types', function () { + return [ 'post', 'page' ]; +} ); + +// Add a second business location. +add_filter( 'advanced_seo_business_schema', function ( $schema ) { + $schema['location'] = [ + [ '@type' => 'Place', 'name' => 'Dubai branch', + 'address' => [ '@type' => 'PostalAddress', + 'streetAddress' => 'Dubai Silicon Oasis, DDP, Building A2', + 'addressLocality' => 'Dubai', 'addressCountry' => 'AE' ] ], + ]; + return $schema; +} ); + +// Set a custom OG image for a specific page. +add_filter( 'advanced_seo_og_data', function ( $data ) { + if ( is_page( 'contact' ) ) { + $data['image'] = 'https://example.com/contact-og.jpg'; + } + return $data; +} ); +``` + +### Post meta + +| Key | Type | Description | +|---|---|---| +| `_seo_title` | string | SEO title | +| `_seo_description` | string | Meta description | +| `_seo_og_image_id` | int | Attachment ID for `og:image` | +| `_seo_faq` | array | `[ [ 'question' => '…', 'answer' => '…' ], … ]` | +| `_seo_noindex` | string | `'1'` when the post is noindexed | + +These keys are exposed through the REST API (`show_in_rest`), so they are available to the block editor and external tools. + +### Options + +`_seo_home_title`, `_seo_home_description`, `_seo_default_og_image`, `_seo_biz_type`, `_seo_biz_name`, `_seo_biz_phone`, `_seo_biz_email`, `_seo_biz_street`, `_seo_biz_city`, `_seo_biz_country`, `_seo_biz_areas`, `_seo_biz_logo`, `_seo_biz_sameas`, `_seo_biz_lat`, `_seo_biz_lng`, `_seo_biz_hours`, `_seo_biz_price` + +### Image size + +A hard-cropped `advanced_seo_og` size (1200×630) is registered. Regenerate thumbnails for existing images to benefit from it; until then the full-size image is used. + +## Troubleshooting + +**Settings → Advanced SEO does not appear** +The 4.x code is not running. Confirm that the plugin is active and that no other copy defines `Advanced_SEO_Meta` (`grep -rl "Advanced_SEO_Meta" wp-content --include=*.php`). Flush the object cache and ask your host to reset PHP opcache if the file on disk was just replaced. + +**The page still shows only four OG tags and `og:type=article`** +That is the 3.x output. See [Upgrading from 3.x](#upgrading-from-3x). + +**Duplicate title, description or OG tags** +Another SEO plugin, the theme or a code snippet is printing them as well. Disable one source. + +**No `og:image` on shares** +Set a Default OG Image under Settings → Advanced SEO, and clear the Facebook / LinkedIn sharing debugger caches. + +**FAQ rich results do not appear** +See the note [above](#faq-schema-and-the-seo_faq-shortcode); this is a Google policy and not a plugin fault. Validate the markup with Google's Rich Results Test. + +## Uninstalling + +Deleting the plugin from **Plugins → Installed Plugins** removes all of its options and all `_seo_*` post meta (titles, descriptions, images, FAQs and noindex flags). Back up your database first if you may reinstall later. Deactivating the plugin does not delete anything. + ## Changelog -- 3.0.0 — Initial release: SEO title, meta description, Open Graph, FAQ builder, JSON-LD output +### 4.1.0 + +- Fix: static front page and posts page are handled separately, so the posts page no longer inherits homepage SEO +- Fix: one shared description resolver for `description` and `og:description`; shortcodes and blocks stripped; trimmed at a word boundary +- Fix: schema JSON encoded with `JSON_HEX_TAG` and `JSON_HEX_AMP` +- Fix: saving skips revisions and unsupported post types; empty values are deleted instead of stored +- Fix: OG data filter result merged with defaults to avoid PHP notices +- New: canonical URL output (replaces the core one) and robots handling via `wp_robots` +- New: per-post noindex checkbox and exclusion from the XML sitemap +- New: detection of Yoast, Rank Math, AIOSEO, SEOPress and The SEO Framework +- New: `[seo_faq]` shortcode for the visible FAQ; basic HTML preserved in FAQ answers +- New: business schema types, `@id`, `logo`, `email`, `geo`, `openingHours`, `priceRange`, `sameAs`, `Country` objects for `areaServed` +- New: 1200×630 cropped OG image size +- New: support for all public post types and for term and author archives +- New: character counters, drag-to-reorder FAQ rows, duplicate-question warning +- New: REST / block editor exposure of the SEO meta fields +- New: translation loading, uninstall cleanup, `Requires PHP` and `Requires at least` headers + +### 4.0.0 + +- New: Settings page (homepage title and description, default OG image) +- New: per-post `og:image` override with Featured Image and default fallbacks +- New: Twitter Card tags +- New: `MedicalBusiness` JSON-LD on the homepage +- New: media picker for images + +### 3.0.0 + +- Initial release: SEO title, meta description, Open Graph, FAQ builder and FAQPage JSON-LD ## Support -Open an issue in the repository or contact the maintainer for feature requests and bugs. - -## Notes - -- Designed for posts and pages. Best used alongside strong on-page content and standard SEO practices. -- FAQ schema helps AI-driven search experiences surface clear Q&A content. +Open an issue in the [repository](https://git.my-dev.pro/mydev/advanced-seo-keywords/issues) for bugs and feature requests. +## License +GPL-2.0-or-later. See the plugin header for details. \ No newline at end of file diff --git a/advanced-seo-keywords.php b/advanced-seo-keywords.php index 6a0a54b..2802db8 100644 --- a/advanced-seo-keywords.php +++ b/advanced-seo-keywords.php @@ -2,8 +2,10 @@ /** * Plugin Name: Advanced SEO Meta + AI FAQ Schema * Plugin URI: https://my-dev.pro/advanced-seo-meta - * Description: Full SEO meta box (Title, Description) + built-in FAQ builder with JSON-LD Schema for AI search engines. - * Version: 3.0.0 + * 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+ @@ -15,225 +17,1156 @@ 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( 'add_meta_boxes', array( $this, 'add_meta_box' ) ); - add_action( 'save_post', array( $this, 'save_meta_data' ) ); - add_filter( 'pre_get_document_title', array( $this, 'custom_title' ), 10 ); - add_action( 'wp_head', array( $this, 'output_meta_tags' ), 1 ); - add_action( 'wp_head', array( $this, 'output_og_tags' ), 2 ); - add_action( 'wp_head', array( $this, 'output_faq_schema' ), 5 ); // High priority for AI crawlers - add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) ); + add_action( 'plugins_loaded', [ $this, 'init' ], 20 ); } - /** - * Load a tiny JS script to handle adding/removing FAQ rows in the admin. - */ - public function enqueue_admin_assets() { - wp_add_inline_script( 'jquery', ' - jQuery(document).ready(function($) { - // Add FAQ row - $(document).on("click", ".add-faq-row", function(e) { - e.preventDefault(); - var index = $(".faq-row").length; - var row = \'<div class="faq-row" style="background:#f9f9f9;padding:15px;margin-bottom:15px;border:1px solid #ddd;">\' + - \'<p><label>Question:</label><input type="text" name="faq_question[]" style="width:100%;" /></p>\' + - \'<p><label>Answer:</label><textarea name="faq_answer[]" rows="2" style="width:100%;"></textarea></p>\' + - \'<button class="remove-faq-row button button-small">Remove Question</button>\' + - \'</div>\'; - $(this).before(row); - }); - // Remove FAQ row - $(document).on("click", ".remove-faq-row", function(e) { - e.preventDefault(); - $(this).closest(".faq-row").remove(); - }); - }); - ' ); + 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 ); + } } - /** - * Add the main SEO + FAQ meta box. - */ + 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 & AI FAQ Schema', 'advanced-seo-meta' ), - array( $this, 'render_meta_box' ), - ['post', 'page'], + __( 'Advanced SEO & FAQ Schema', 'advanced-seo-meta' ), + [ $this, 'render_meta_box' ], + $this->post_types(), 'normal', 'default' ); } - /** - * Render the meta box (Title, Description, FAQ builder). - */ - public function render_meta_box( $post ) { - wp_nonce_field( 'advanced_seo_nonce', 'advanced_seo_nonce' ); + 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(); + } - // Get saved values - $seo_title = get_post_meta( $post->ID, '_seo_title', true ); - $seo_description = get_post_meta( $post->ID, '_seo_description', true ); - $faq_data = get_post_meta( $post->ID, '_seo_faq', true ); - if ( ! is_array( $faq_data ) ) $faq_data = array(); + 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, .seo-field textarea { width: 100%; max-width: 700px; } + .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> - <!-- 1. SEO Title --> <div class="seo-field"> - <label for="seo_title"><?php esc_html_e( 'SEO Title (For Google search results)', 'advanced-seo-meta' ); ?></label> - <input type="text" id="seo_title" name="seo_title" value="<?php echo esc_attr( $seo_title ); ?>" placeholder="e.g., Comprehensive Genomic Profiling (CGP) & WES for Precision Oncology" /> + <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> - <!-- 2. Meta Description --> <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" rows="3"><?php echo esc_textarea( $seo_description ); ?></textarea> + <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;" /> - <!-- 3. FAQ Builder (For AI Search Engines) --> - <h3 style="margin-top:0;"><?php esc_html_e( 'FAQ Schema for AI Search (Google SGE, Bing Chat)', 'advanced-seo-meta' ); ?></h3> - <p class="description"><?php esc_html_e( 'Add questions and answers here. This will be output as JSON-LD structured data so AI engines can display your answers directly in search results.', 'advanced-seo-meta' ); ?></p> + <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 ) ) : ?> - <?php foreach ( $faq_data as $faq ) : ?> - <div class="faq-row"> - <p><label>Question:</label><input type="text" name="faq_question[]" value="<?php echo esc_attr( $faq['question'] ); ?>" style="width:100%;" /></p> - <p><label>Answer:</label><textarea name="faq_answer[]" rows="2" style="width:100%;"><?php echo esc_textarea( $faq['answer'] ); ?></textarea></p> - <button class="remove-faq-row button button-small"><?php esc_html_e( 'Remove Question', 'advanced-seo-meta' ); ?></button> - </div> - <?php endforeach; ?> - <?php else : ?> - <!-- Default Example Pre-filled (Your Oncology Content) --> - <div class="faq-row"> - <p><label>Question:</label><input type="text" name="faq_question[]" value="What is Comprehensive Genomic Profiling (CGP) in oncology?" style="width:100%;" /></p> - <p><label>Answer:</label><textarea name="faq_answer[]" rows="2" style="width:100%;">Comprehensive Genomic Profiling (CGP) is a next-generation sequencing test that analyzes all classes of genomic alterations across hundreds of cancer-associated genes to identify targeted therapy options, immunotherapy biomarkers, and clinical trial opportunities for cancer patients.</textarea></p> - <button class="remove-faq-row button button-small">Remove Question</button> - </div> - <div class="faq-row"> - <p><label>Question:</label><input type="text" name="faq_question[]" value="What is the difference between WES (Whole Exome Sequencing) and CGP?" style="width:100%;" /></p> - <p><label>Answer:</label><textarea name="faq_answer[]" rows="2" style="width:100%;">Whole Exome Sequencing (WES) sequences all protein-coding regions of the entire genome, covering ~20,000 genes. Comprehensive Genomic Profiling (CGP) focuses specifically on a curated panel of known cancer-driver genes, providing deeper coverage (higher read depth) for those specific genes, making it more sensitive for detecting low-frequency tumor mutations in clinical oncology.</textarea></p> - <button class="remove-faq-row button button-small">Remove Question</button> - </div> - <div class="faq-row"> - <p><label>Question:</label><input type="text" name="faq_question[]" value="How does precision medicine use genomic profiling?" style="width:100%;" /></p> - <p><label>Answer:</label><textarea name="faq_answer[]" rows="2" style="width:100%;">Precision medicine uses genomic profiling to identify specific genetic mutations driving a patient's disease. By matching these mutations with FDA-approved targeted therapies or immunotherapies, clinicians can deliver highly personalized treatment plans that improve efficacy and reduce adverse side effects compared to traditional chemotherapy.</textarea></p> - <button class="remove-faq-row button button-small">Remove Question</button> - </div> - <div class="faq-row"> - <p><label>Question:</label><input type="text" name="faq_question[]" value="Is CGP the same as standard clinical genetics testing?" style="width:100%;" /></p> - <p><label>Answer:</label><textarea name="faq_answer[]" rows="2" style="width:100%;">No. Standard clinical genetics testing typically looks for inherited germline mutations (e.g., BRCA1/2). CGP analyzes somatic (tumor-acquired) mutations within the cancer tissue itself. While both fall under clinical genetics, CGP is specifically used for guiding oncology treatment decisions, whereas standard testing assesses hereditary cancer risk.</textarea></p> - <button class="remove-faq-row button button-small">Remove Question</button> - </div> - <?php endif; ?> + <?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> - <button class="add-faq-row button button-primary"><?php esc_html_e( '+ Add New FAQ', 'advanced-seo-meta' ); ?></button> + <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 } - /** - * Save all the new fields. - */ + 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['advanced_seo_nonce'] ) || ! wp_verify_nonce( $_POST['advanced_seo_nonce'], 'advanced_seo_nonce' ) ) return; + 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; - // Save Title & Description - if ( isset( $_POST['seo_title'] ) ) update_post_meta( $post_id, '_seo_title', sanitize_text_field( $_POST['seo_title'] ) ); - if ( isset( $_POST['seo_description'] ) ) update_post_meta( $post_id, '_seo_description', sanitize_textarea_field( $_POST['seo_description'] ) ); + 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'] ) ); + } - // Save FAQ Array - $questions = isset( $_POST['faq_question'] ) ? array_map( 'sanitize_text_field', $_POST['faq_question'] ) : array(); - $answers = isset( $_POST['faq_answer'] ) ? array_map( 'wp_kses_post', $_POST['faq_answer'] ) : array(); // Allow basic HTML for answers + // 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 = array(); - for ( $i = 0; $i < count( $questions ); $i++ ) { - if ( ! empty( $questions[ $i ] ) && ! empty( $answers[ $i ] ) ) { - $faq_pairs[] = array( - 'question' => $questions[ $i ], - 'answer' => $answers[ $i ] - ); + // 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 ) ); } } - update_post_meta( $post_id, '_seo_faq', $faq_pairs ); - } - /** - * Override the <title> tag. - */ - public function custom_title( $title ) { - if ( is_singular() ) { - $custom = get_post_meta( get_queried_object_id(), '_seo_title', true ); - if ( ! empty( $custom ) ) return $custom; + // 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'] ) ); } - return $title; } - /** - * Output Description & Keywords. - */ - public function output_meta_tags() { - if ( ! is_singular() ) return; - $id = get_queried_object_id(); - if ( $desc = get_post_meta( $id, '_seo_description', true ) ) echo '<meta name="description" content="' . esc_attr( $desc ) . '" />' . "\n"; - // (Optional: We leave keywords empty intentionally, but if you insist, uncomment below) - // if ( $kw = get_post_meta( $id, '_seo_keywords', true ) ) echo '<meta name="keywords" content="' . esc_attr( $kw ) . '" />' . "\n"; + 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; } - /** - * Output Open Graph (Facebook/LinkedIn). - */ - public function output_og_tags() { - if ( ! is_singular() ) return; - $id = get_queried_object_id(); - $post = get_post( $id ); - $title = get_post_meta( $id, '_seo_title', true ) ?: $post->post_title; - $desc = get_post_meta( $id, '_seo_description', true ) ?: wp_trim_words( $post->post_content, 30 ); - echo '<meta property="og:title" content="' . esc_attr( $title ) . '" />' . "\n"; - echo '<meta property="og:description" content="' . esc_attr( $desc ) . '" />' . "\n"; - echo '<meta property="og:url" content="' . esc_url( get_permalink() ) . '" />' . "\n"; - echo '<meta property="og:type" content="article" />' . "\n"; + 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 : []; } - /** - * Output JSON-LD FAQ Schema (The secret weapon for AI search). - */ public function output_faq_schema() { if ( ! is_singular() ) return; - $id = get_queried_object_id(); - $faq_data = get_post_meta( $id, '_seo_faq', true ); - if ( empty( $faq_data ) || ! is_array( $faq_data ) ) return; - - $schema = array( - '@context' => 'https://schema.org', - '@type' => 'FAQPage', - 'mainEntity' => array() - ); + $faq_data = $this->get_faq( get_queried_object_id() ); + if ( empty( $faq_data ) ) return; + $main_entity = []; foreach ( $faq_data as $faq ) { - $schema['mainEntity'][] = array( + $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' => $faq['question'], - 'acceptedAnswer' => array( + 'name' => $q, + 'acceptedAnswer' => [ '@type' => 'Answer', - 'text' => $faq['answer'] - ) - ); + 'text' => $a, + ], + ]; } - echo '<script type="application/ld+json">' . json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . '</script>' . "\n"; + 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(); \ No newline at end of file +new Advanced_SEO_Meta(); +register_uninstall_hook( __FILE__, [ 'Advanced_SEO_Meta', 'uninstall' ] );