Custom WordPress REST wp-json endpoint

This code creates a WordPress REST API endpoint that retrieves raw template code from post metadata. It:

  1. Finds posts by ID or slug
  2. Extracts serialized template data from _bricks_page_settings meta
  3. Returns raw code as plain text or 404 errors
  4. Bypasses WordPress’ default JSON formatting prints the code or string or content exactly !

frontend remote request example : https://localhost.localhost/wp-json/custom/v1/template-code/{Post_ID_Numeric}

ofcourse this may create cors problem depending on yoru hosting default setup be sure to setup your htaccess for remote domain implementations.



// Hook into the REST API initialization action.
add_action( 'rest_api_init', 'register_raw_template_code_route' );

function register_raw_template_code_route() {
    register_rest_route( 'custom/v1', '/template-code/(?P<identifier>[a-zA-Z0-9-_]+)', [
        'methods'             => 'GET',
        'callback'            => 'get_raw_template_code',
        'permission_callback' => '__return_true', // Allow public access or adjust for your needs.
        'args'                => [
            'identifier' => [
                'required'          => true,
                'validate_callback' => 'validate_identifier',
            ],
        ],
    ]);
}

/**
 * Validate the identifier parameter.
 *
 * @param mixed $param Value of the parameter.
 * @return bool
 */
function validate_identifier( $param ) {
    return preg_match( '/^[a-zA-Z0-9-_]+$/', $param );
}

/**
 * Callback function to retrieve and return the raw template_code.
 *
 * @param WP_REST_Request $request Request object.
 * @return string|WP_Error
 */
function get_raw_template_code( $request ) {
    $identifier = $request['identifier'];

    // Determine if the identifier is numeric (ID) or a slug.
    if ( is_numeric( $identifier ) ) {
        $post = get_post( intval( $identifier ) );
    } else {
        $post = get_page_by_path( $identifier, OBJECT, [ 'post', 'page' ] );
    }

    // If post not found, return an error.
    if ( ! $post ) {
        return new WP_Error( 'no_post', 'Post not found', [ 'status' => 404 ] );
    }

    // Retrieve the _bricks_page_settings meta field.
    $page_settings = get_post_meta( $post->ID, '_bricks_page_settings', true );

    if ( is_serialized( $page_settings ) ) {
        $page_settings = maybe_unserialize( $page_settings );
    }

    // Check if 'template_code' exists.
    if ( isset( $page_settings['template_code'] ) && ! empty( $page_settings['template_code'] ) ) {
        // Return the template_code as plain text.
        header( 'Content-Type: text/plain' );
        echo $page_settings['template_code'];
        exit;
    }

    return new WP_Error( 'no_template_code', 'No Template Code Found', [ 'status' => 404 ] );
}