=== Native Content Relationships ===
Contributors: chetanupare
Tags: relationships, content, posts, users, terms
Requires at least: 5.0
Tested up to: 7.0
Requires PHP: 7.4
Stable tag: 1.1.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Donate link: https://buymeacoffee.com/chetanupare
Plugin URI: https://chetanupare.github.io/WP-Native-Content-Relationships/

[![Good First Issues](https://img.shields.io/github/issues/chetanupare/WP-Native-Content-Relationships/good%20first%20issue)](https://github.com/chetanupare/WP-Native-Content-Relationships/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)

Connect your posts, users, and terms with a simple interface. Show related content that keeps readers engaged and increases pageviews.

== Description ==

**Connect posts, users, and terms with a visual drag-and-drop interface. No coding required.**

Native Content Relationships gives you a visual relationship builder right inside WordPress. Search for any post, page, user, or term — click to connect. Done.

**See it in action:**

1. Open any post or page
2. Find the "Relationships" box below the editor
3. Type to search — thumbnails appear as you type
4. Click a result to connect it
5. Drag to reorder your relationships
6. Use the Gutenberg block or Elementor dynamic tag to display them on the frontend

**No code. No shortcodes to remember. No complex setup.**

**What you get:**

* **Visual post editor** — Search, thumbnails, drag-and-drop sorting in the classic and block editors
* **User profile relationships** — Connect users to their favorite posts, bookmarks, or contributions
* **Term relationships** — Link categories, tags, or custom taxonomies to content
* **Gutenberg block** — Drop a "Related Content" block that shows live previews in the editor
* **Elementor dynamic tags** — Display related posts, users, or terms with Elementor's visual builder
* **Shortcodes** — `[naticore_related_posts]` for theme developers
* **Widget** — Add to any sidebar or widget area
* **WooCommerce** — Link products to accessories, guides, or related items
* **Works with any theme** — No forced layouts, no template overrides needed
* **Fast** — Dedicated database table, not slow post meta queries
* **Translation ready** — WPML and Polylang compatible

**Perfect for:**

* Bloggers who want to keep readers on their site longer
* Online stores linking products to accessories or guides
* Course creators connecting lessons to courses
* News sites linking related articles
* Any site that needs to show "related content"

**Why choose this over ACF or JetEngine?**

* **Faster** — Custom database table with composite indexes, not post meta bloat
* **Simpler** — One plugin, one table, no field configuration needed
* **Lighter** — No dependency on ACF, JetEngine, or any other plugin
* **More flexible** — Connect posts to users, terms to posts, users to posts — not just post-to-post
* **Better performance** — Sub-2ms queries even with 1M+ relationships

== Key Features ==

• Visual search with thumbnails in the post editor  
• Drag-and-drop relationship sorting  
• One-way or bidirectional relationships  
• Gutenberg block with live preview  
• Elementor dynamic tags for posts, users, and terms  
• Shortcodes and widgets  
• Many-to-many relationships between posts, users, and terms  
• Indexed database table for fast queries  
• WooCommerce product relationships  
• REST API for headless setups  
• Multilingual-ready (WPML / Polylang)  
• Works with any theme — no template overrides

== Supported Relationship Types ==

• Post ↔ Post  
• Post ↔ User  
• Post ↔ Term  
• User ↔ Post  
• Term ↔ Post  

== Common Use Cases ==

**Posts**
• Products → Accessories  
• Courses → Lessons  
• Articles → Related content  

**Users**
• Favorite posts  
• Bookmarked content  
• Multiple authors or contributors  

**Terms**
• Featured categories  
• Curated collections  
• Semantic grouping beyond default taxonomies  

== Admin Interface ==

• Relationship management in post editor  
• User profile relationship management  
• Term editor relationship support  
• AJAX-powered search with thumbnails for posts, users, and terms  
• Modern UI matching WordPress admin style  

== Integrations ==

• WooCommerce (product relationships)  
• WPML / Polylang (relationship mirroring)  
• Elementor (dynamic content support)  
• Gutenberg (related content block)  
• Advanced Custom Fields (one-time migration tool)  

== Page Builder Integration =

**Elementor:**
* **Compatible with:** Elementor 2.0+
* **Features:** Comprehensive Dynamic Tags suite for relationships
* **Auto-detected:** Yes (no configuration needed)
* **Tested up to:** Elementor 3.20

**Elementor Dynamic Tags:**
* **Related Posts**: Display related posts with customizable output formats
* **Related Users**: Display users with relationships (favorites, bookmarks, etc.)
* **Related Terms**: Display taxonomy terms with relationships
* **Flexible Output**: IDs, titles, links, avatars, count-only options
* **Direction Support**: Both outgoing and incoming relationships
* **Native Controls**: Relationship type selector with validation

**Gutenberg:**
* **Compatible with:** WordPress 5.0+ (Core)
* **Features:** "Related Content" block with live preview in editor
* **Always available:** Yes (core WordPress feature)
* **Tested up to:** WordPress 7.0 

= Shortcodes =

Use these in posts, pages, or widgets. They use the current post ID when not specified.

*Related posts (default: type=related_to, limit=5):*
[naticore_related_posts type="related_to" limit="5" order="date" layout="list" title="Related Content" class="my-class"]

*Related users (default: type=authored_by):*
[naticore_related_users type="authored_by" limit="10" order="name" layout="list" title="Authors"]

*Related terms (default: type=categorized_as):*
[naticore_related_terms type="categorized_as" limit="5" order="name" layout="grid" title="Categories"]

**Attributes (all shortcodes):**
* type – Relationship type slug (e.g. related_to, parent_of, authored_by, categorized_as)
* limit – Number of items (1–50), default 5
* order – Sort: date, title (posts) or name (users/terms)
* post_id – Post ID; omit to use current post
* layout – list or grid
* title – Heading text above the list (optional)
* class – Extra CSS class(es) for the wrapper
* show_thumbnail – 1 to show post thumbnail (posts shortcode only), default 0
* excerpt_length – Number of words for excerpt (0 = hide), default 0

= Widget =

**Related Content (NCR)** is available under Appearance → Widgets. Add it to any sidebar or widget area.

* **Title** – Optional widget title (leave blank to use the shortcode's default "Related Content" heading)
* **Relationship type** – e.g. Related To, Parent Of, Depends On
* **Number of items** – 1–50
* **Order by** – Date or Title
* **Post ID (optional)** – Leave 0 to use the current post; set a post ID to show relations for a specific post

Output matches the shortcode (same markup and styles when the shortcode CSS is enqueued).

== Installation ==

1. Upload the plugin to `/wp-content/plugins/native-content-relationships/`
2. Activate the plugin from the Plugins menu
3. Database tables are created automatically
4. Configure settings under **Settings → Content Relationships**

== Frequently Asked Questions ==

= Does this replace WooCommerce linked products? =
No. It complements WooCommerce and can optionally sync relationships.

= Can I migrate from ACF relationship fields? =
Yes. A one-time migration tool is included.

= Does this work with page builders? =
Yes. The plugin is editor-agnostic and works with Elementor, Gutenberg, and others.

= Does this support users and terms? =
Yes. Full support for post–user and post–term relationships is included.

= Does this send data externally? =
No. All data is stored locally in your WordPress database.

== Developer Guide (Advanced) ==

This section is intended for developers who want programmatic control.

= Core API =

Add a relationship:
`wp_add_relation( $from_id, $to_id, $type );`

Get related items:
`wp_get_related( $id, $type );`

Check relationship:
`wp_is_related( $from_id, $to_id, $type );`

Remove relationship:
`wp_remove_relation( $from_id, $to_id, $type );`

= WP_Query Integration =

new WP_Query( array(
'post_type' => 'post',
'content_relation' => array(
'post_id' => 123,
'type' => 'related_to',
),
) );


= REST API =

Endpoints available under:
`/wp-json/naticore/v1/`

• Create relationships  
• Fetch related content  
• Delete relationships  

**Embed relations in core REST responses (headless):**  
Add `?naticore_relations=1` to any core resource request to include a `naticore_relations` array in the response. Works with:
• `GET /wp-json/wp/v2/posts/<id>?naticore_relations=1`
• `GET /wp-json/wp/v2/users/<id>?naticore_relations=1`
• `GET /wp-json/wp/v2/categories/<id>?naticore_relations=1` (and other taxonomies)
Each relation item includes `to_id`, `to_type`, `type`, and optional `title`/`display_name`/`name`. Opt-in only so default requests stay fast.

= Hooks & Filters =

Actions:
• `naticore_relation_added`
• `naticore_relation_removed`
• `naticore_after_duplicate_post` – fired after copying relations from one post to another (args: from_post_id, to_post_id, result array)

Filters:
• `naticore_relation_is_allowed`
• `naticore_get_related_args`

**Duplicate post:** Use helper `naticore_copy_relations( $from_post_id, $to_post_id, $relation_types = null )` to copy relationships when duplicating a post. Returns array with keys `copied`, `skipped`, `errors`. Out-of-the-box integration: Yoast Duplicate Post, Post Duplicator (metaphorcreations), Copy & Delete Posts (Inisev).

= Elementor Integration =

This plugin provides comprehensive Elementor Dynamic Tags for displaying relationships in Elementor-powered designs.

**Available Dynamic Tags:**

* **Related Posts** (ncr-related-posts)
  - Display posts related to the current post
  - Supports all post-to-post relationship types
  - Output formats: IDs, titles, links, count
  - Direction control: outgoing/incoming

* **Related Users** (ncr-related-users)
  - Display users with relationships to posts
  - Supports user relationship types (favorites, bookmarks, etc.)
  - Output formats: IDs, names, emails, avatars, profile links
  - Direction control: posts-to-users/users-to-posts

* **Related Terms** (ncr-related-terms)
  - Display taxonomy terms with relationships
  - Supports term relationship types (categories, tags, etc.)
  - Output formats: IDs, names, slugs, archive links
  - Direction control: posts-to-terms/terms-to-posts

**Usage Examples:**

*Display related post IDs:*
```
[ncr-related-posts relationship_type="related_to" output_format="ids" limit="5"]
```

*Display user avatars:*
```
[ncr-related-users relationship_type="favorite_posts" output_format="avatar_images" avatar_size="48"]
```

*Display term links:*
```
[ncr-related-terms relationship_type="categorized_as" output_format="term_links" limit="10"]
```

*Get count of related items:*
```
[ncr-related-posts relationship_type="related_to" output_format="count"]
```

**Advanced Features:**
- **Context-aware**: Automatically detects current post, user, or term context
- **Fallback content**: Display custom text when no relationships found
- **Pagination support**: Limit results for performance
- **Ordering options**: Sort by date, title, or random
- **Multi-language**: Works with WPML/Polylang translations

**Integration Benefits:**
- **Native Elementor experience**: Tags appear in Elementor's Dynamic Tags panel
- **No templates forced**: Users control output format and styling
- **Performance optimized**: Uses cached relationship data
- **Optional dependency**: Only loads when Elementor is active

= WP-CLI =

• List relationships  
• Add / remove relationships  
• Integrity checks  

== Stability & Backward Compatibility ==

**Schema stable from 1.x onward. Backward compatibility guaranteed.**

* **Database schema stability** — The relationship table and `NCR_SCHEMA_VERSION` are stable in the 1.x line.
* **Backward compatibility promise** — Public PHP APIs will not be removed or changed in breaking ways within the 1.x branch.
* **Versioning policy** — 1.x = stable core. Minor/patch releases may add features and fix bugs; they will not break existing integrations.

== Performance ==

* **Index Optimization**: Built on composite covering indexes for fast queries.
* **Micro-Optimized Validations**: SQL-native validations ensure sub-2ms P95 latency even at 1M+ rows.
* **Object Cache Integration**: Full compatibility with object cache.

**Benchmarks confirm stable performance with 1,000,000+ relationship rows under InnoDB.**
[View Full Performance Report](https://github.com/chetanupare/WP-Native-Content-Relationships/blob/main/docs/PERFORMANCE.md)

== ACF Migration ==

If you store relationships in **Advanced Custom Fields** relationship fields or standard Post Meta, you can migrate to Native Content Relationships for better performance.
[Migration guide](https://github.com/chetanupare/WP-Native-Content-Relationships/blob/main/docs/migration/from-acf.md)

== Screenshots ==

1. Settings screen  
2. Relationship overview  

== Changelog ==

= 1.1.0 =
* Feature: AI-powered relationship suggestions using WordPress 7.0 AI Client
* Feature: Settings option to enable/disable AI suggestions (Settings > Content Relationships)
* Feature: AI analyzes post content for semantic relationship suggestions
* Improved: Falls back to category/tag matching when AI is unavailable
* Improved: Visual AI badge in admin when suggestions come from AI

= 1.0.31 =
* Fix: CSS class name mismatch in admin meta box (ncore- → naticore-) — meta box now styles correctly
* Improved: Search results now show post thumbnails for better visual identification
* Improved: Gutenberg block now shows live preview of related content instead of placeholder
* Improved: Readme rewritten for better clarity and user focus
* Updated: Tested up to WordPress 7.0

= 1.0.30 =
* WordPress 7.0 compatibility: Updated Tested up to 7.0
* Fix: Remove IF NOT EXISTS from dbDelta() to ensure schema updates work correctly
* Fix: Add DEFAULT NULL to nullable columns in database schema
* Improved: Renamed wp_* global functions to ncr_* prefix (backward-compatible wrappers retained)
* Improved: Replaced wp_verify_nonce() with hash_equals() pattern for modern nonce verification
* Improved: Replaced json_encode() with wp_json_encode() for WordPress coding standards

= 1.0.29 =
* Feature: Added Lightweight Relationship Metadata API (`wp_content_relationmeta` table).
* Feature: Added Advanced WP_Query arguments (`content_relation` with nested OR/AND logic and type exclusions).
* Update: Improved documentation highlighting enterprise-grade features and ACF migration.

= 1.0.28 =
* WP_Query: Registered query vars, documented relation args, added ncr_skip_relationship_query filter for core migration path.

= 1.0.27 =
* Code quality: PHPCS compliance (WordPress coding standards); 0 errors.

= 1.0.26 =
* New: Playground Live Preview blueprint (assets/blueprints/blueprint.json) for Try in Playground on WordPress.org.

= 1.0.25 =
* Fix: Resolved WordPress.org SVN stable tag recognition issue.
* Deployment: Updated stable tag to ensure proper plugin directory deployment.

= 1.0.24 =
* Translations: Added Spanish (es_ES), German (de_DE), French (fr_FR), and Portuguese (pt_BR) support.
* Localization: Included master `.pot` file for community translations.
* Core: Improved internationalization (i18n) for admin interfaces.

= 1.0.23 =
* Clean Release: Removed development artifacts (docs, tests, benchmarks) from distribution.
* Documentation: Updated readme to link to external performance report.
* Infrastructure: Verified 1M row benchmarks (see GitHub).

= 1.0.22 =
* Infrastructure-Grade Benchmarks: Refined docs/PERFORMANCE.md with high-fidelity metrics.
* Enhanced Benchmarking Suite: Support for Mean/P95 latency and buffer pool warming.
* Performance: Validated sub-2ms P95 latency at 1M rows.

= 1.0.21 =

= 1.0.20 =
* **NEW**: Schema Versioning Guard (`NCR_SCHEMA_VERSION` 1.1)
* **NEW**: Micro-Optimized Query Layer with composite indexes for 1M+ rows
* **NEW**: WordPress Site Health integration for relationship integrity
* **DEV**: Formalized database upgrade routine

= 1.0.19 =
* **PERFORMANCE**: Implemented chunked integrity processing to support 100k+ relationships
* **PERFORMANCE**: SQL-native duplicate detection to minimize PHP memory overhead
* **IMPROVED**: Streamed WP-CLI output for real-time progress during check/fix
* **FIX**: Resolved "Stable Tag" race conditions in SVN deployment pipeline

= 1.0.18 =
* **NEW**: Relationship Integrity Engine with modular helper system
* **NEW**: Expanded integrity checks (orphans, unregistered types, constraints, directional consistency)
* **IMPROVED**: WP-CLI command `wp content-relations check` with `--fix` and `--verbose` reporting
* **DEV**: New `includes/helpers/integrity-helpers.php` for modular data validation

= 1.0.17 =
* **REFINED**: Standardized relationship error codes with `ncr_` prefix (e.g. `ncr_max_connections_exceeded`)
* **SECURITY**: Implemented relationship registry locking to prevent late/unsafe registrations after `init:20`
* **DOCS**: Added architectural notes regarding future atomic write considerations

= 1.0.16 =
* **NEW**: Formal Relationship Type Registry with `ncr_get_registered_relation_types()`
* **NEW**: Enforced Directional Logic (blocked reverse writes for one-way types)
* **NEW**: Relationship constraints support with `max_connections` (e.g. "One Post to One Author")
* **NEW**: REST API endpoint `GET /naticore/v1/types` to expose registry
* **IMPROVED**: Enhanced verification layer in REST relationship creation

= 1.0.15 =
* **NEW**: Formal Relationship Type Registration API for developers
* **NEW**: Added `ncr_register_relation_type` helper with schema validation
* **NEW**: Strict validation for relationship object combinations
* **IMPROVED**: Refactored internal type mapping for better maintainability

= 1.0.14 =
* **NEW**: Integrated Import/Export as a dedicated settings tab
* **NEW**: Added empty state UI for cleaner Relationship Overview experience
* **NEW**: Added dismissible post-activation notice with documentation links
* **IMPROVED**: Moved Relationship Overview from Tools to Settings menu for better organization
* **FIX**: Resolved CSS specificity issues in card-based settings layout

= 1.0.13 =
* **NEW**: Comprehensive CONTRIBUTING.md guidelines and security policy
* **NEW**: Issue templates, automation, and contributor guidelines
* **FIX**: CodeQL syntax errors and duplicate workflow fixes
* **FIX**: Deprecated function usage and i18n inconsistencies
* **IMPROVED**: Updated Elementor tag names to naticore- prefix
* **IMPROVED**: Code quality standards and PHPDoc documentation

= 1.0.12 =
* **NEW**: Comprehensive Elementor Dynamic Tags integration
* **NEW**: Related Posts Dynamic Tag with multiple output formats
* **NEW**: Related Users Dynamic Tag with avatar and profile support
* **NEW**: Related Terms Dynamic Tag with taxonomy filtering
* **NEW**: Direction control for all relationship types (outgoing/incoming)
* **NEW**: Flexible output formats (IDs, titles, links, avatars, count)
* **NEW**: Context-aware relationship detection
* **NEW**: Performance optimized with caching integration
* **IMPROVED**: Enhanced Elementor integration with native controls
* **IMPROVED**: Updated documentation with Elementor examples  

= 1.0.11 =
• Added full post-to-term and term-to-post relationships  
• Improved database indexing  
• Updated documentation  

= 1.0.10 =
• Added full post-to-user and user-to-post relationships  
• User profile relationship UI  

= 1.0.0 =
• Initial release  

== Contributing ==

Contributions are welcome.  
GitHub: https://github.com/chetanupare/WP-Native-Content-Relationships

== License ==

GPLv2 or later
