<?php /** * Plugin Name: Rank Math API Manager Extended v1.3 * Description: Manages the update of Rank Math metadata (SEO Title, SEO Description, Canonical URL) via the REST API for WordPress posts and WooCommerce products. * Version: 1.3 * Author: Phil - https://inforeole.fr */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } class Rank_Math_API_Manager_Extended { public function __construct() { add_action('rest_api_init', [$this, 'register_meta_fields']); add_action('rest_api_init', [$this, 'register_api_routes']); } /** * Registers the Rank Math meta fields in the REST API for posts and products (if WooCommerce is active). */ public function register_meta_fields() { $meta_fields = [ 'rank_math_title' => 'SEO Title', 'rank_math_description' => 'SEO Description', 'rank_math_canonical_url' => 'Canonical URL' ]; // Register meta for posts by default. $post_types = ['post']; // If WooCommerce is active, add the 'product' post type. if ( class_exists('WooCommerce') ) { $post_types[] = 'product'; } foreach ( $post_types as $post_type ) { foreach ( $meta_fields as $key => $description ) { register_post_meta( $post_type, $key, [ 'show_in_rest' => true, 'single' => true, 'type' => 'string', 'auth_callback' => [$this, 'check_update_permission'], 'description' => $description, ] ); } } } /** * Registers the REST API route to update Rank Math meta fields. */ public function register_api_routes() { register_rest_route( 'rank-math-api/v1', '/update-meta', [ 'methods' => 'POST', 'callback' => [$this, 'update_rank_math_meta'], 'permission_callback' => [$this, 'check_update_permission'], 'args' => [ 'post_id' => [ 'required' => true, 'validate_callback' => function( $param ) { return is_numeric( $param ) && get_post( $param ); } ], 'rank_math_title' => [ 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ], 'rank_math_description' => [ 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ], 'rank_math_canonical_url' => [ 'type' => 'string', 'sanitize_callback' => 'esc_url_raw', ], ], ] ); } /** * Updates the Rank Math meta fields via the REST API. */ public function update_rank_math_meta( WP_REST_Request $request ) { $post_id = $request->get_param( 'post_id' ); $fields = ['rank_math_title', 'rank_math_description', 'rank_math_canonical_url']; $result = []; foreach ( $fields as $field ) { $value = $request->get_param( $field ); if ( $value !== null ) { $update_result = update_post_meta( $post_id, $field, $value ); $result[ $field ] = $update_result ? 'updated' : 'failed'; } } if ( empty( $result ) ) { return new WP_Error( 'no_update', 'No metadata was updated', ['status' => 400] ); } return new WP_REST_Response( $result, 200 ); } /** * Checks if the current user has permission to update the meta fields. */ public function check_update_permission() { return current_user_can( 'edit_posts' ); } } new Rank_Math_API_Manager_Extended();