Post rankmath title tag and meta description using WP REST API?

#639820
  • Resolved Kasper
    Rank Math free

    I made this thread (https://support.rankmath.com/ticket/rankmath-wordpress-rest-api/?view=all&unm=321289) some time ago, and now i have a follow up question. Does this look correct (code below)? Is that how i shall change the postmeta data?

    And also, how to make a POST call for defining the “Primary term” (primary category, which defines how the breadcrumbs looks like (see here: https://support.rankmath.com/ticket/how-to-make-term-primary-via-api/)). The primary term is a rankmath field, right?

    Script:

    import requests

    # Define the WordPress site URL
    WORDPRESS_URL = ‘https://your-wordpress-site.com’

    # Define the Rank Math metadata keys
    RANK_MATH_TITLE_KEY = ‘rank_math_title’
    RANK_MATH_DESCRIPTION_KEY = ‘rank_math_description’

    def update_rank_math_metadata(post_id, title, description):
    # Build the URL for the WordPress REST API endpoint
    endpoint = f'{WORDPRESS_URL}/wp-json/wp/v2/posts/{post_id}’

    # Define the metadata to update
    metadata = {
    RANK_MATH_TITLE_KEY: title,
    RANK_MATH_DESCRIPTION_KEY: description
    }

    # Prepare the data to be sent as JSON
    data = {‘meta’: metadata}

    try:
    # Send a PATCH request to update the post metadata
    response = requests.patch(endpoint, json=data)

    # Check if the request was successful
    if response.status_code == 200:
    print(f’Successfully updated Rank Math metadata for post {post_id}’)
    else:
    print(f’Failed to update Rank Math metadata for post {post_id}. Status code: {response.status_code}’)
    except requests.exceptions.RequestException as e:
    print(f’An error occurred: {e}’)

    # Usage example
    if __name__ == ‘__main__’:
    post_id_to_update = 123 # Replace with the actual post ID
    new_title = ‘New Title’
    new_description = ‘New Meta Description’
    update_rank_math_metadata(post_id_to_update, new_title, new_description)

Viewing 12 replies - 1 through 12 (of 12 total)
  • Hello,

    Thank you for your query and we are so sorry about the trouble this must have caused.

    The code you shared does not register the custom postmeta data, which is required since the data from our plugin is not automatically registered into the RESP API.

    After registering the metadata you can submit the postmeta like you would normally with a request as illustrated here in the handbook from WordPress: https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/

    You can also reference this to see the properties available including the meta one after the fields are registered correctly: https://developer.wordpress.org/rest-api/reference/posts/

    Don’t hesitate to get in touch if you have any other questions.

    Kasper
    Rank Math free

    Please give an example based on the code i provided.

    Kasper
    Rank Math free

    and also, what is the term called for the Primary category?

    Kasper
    Rank Math free

    Look here: https://imgur.com/a/uyK6Du8
    Im writing in python. And i try to add the meta data, and i am able to create the post, but the title tag and description are not added when i run the code.

    Kasper
    Rank Math free

    Do i have to register the meta key in the REST API first? Please look if this makes sense. I am writing in python.

    import requests
    import json
    
    # Define your WordPress site's URL and authentication credentials
    wordpress_url = 'https://your-wordpress-site.com/wp-json/wp/v2'
    wordpress_username = 'your-username'
    wordpress_password = 'your-password'
    
    # Define the custom metadata key you want to register
    custom_meta_key = '_custom_meta_key'
    
    # Create the data for registering the custom metadata key
    register_meta_data = {
        'post_type': 'my_custom_post_type',
        'meta_key': custom_meta_key,
        'schema': {
            'single': True,
            'type': 'string',
            'show_in_rest': True,
        },
    }
    
    # Register the custom metadata key via a POST request
    register_meta_url = f'{wordpress_url}/register-meta'
    response = requests.post(register_meta_url, auth=(wordpress_username, wordpress_password), json=register_meta_data)
    
    if response.status_code == 200:
        print(f"Successfully registered custom metadata key: {custom_meta_key}")
    else:
        print(f"Failed to register custom metadata key: {response.text}")
    Kasper
    Rank Math free

    Please help me out here. Here is my latest development on this issue…

    I want to be able to specify the Rank math title tag and rank math meta description when I publish wordpress posts using the WP REST API. I have followed your article (https://badlywired.com/2018/01/getting-post-meta-via-wordpress-rest-api/) and created my own plugin (see code below). And then, I have also tried to publish a post using python, using the code further below. However, it doesn’t work somehow. According to you guys, the meta field is named “rank_math_title”, but when i type that into my script, i get an error

    “Failed to create post. Status Code: 403
    Response: {“code”:”rest_cannot_update”,”message”:”Sorry, you are not allowed to edit the _rank_math_title custom field.”,”data”:{“key”:”_rank_math_title”,”status”:403}}”

    When i type “_rank_math_title” into the plugin, and “rank_math_title” in the POST call (python script), i can publish a post, but it has not inserted the title tag into the rank math field, when i look up in the wp admin editor… This is really confusing to be honest.

    Plugin code:

    <?php
    /**
     * Plugin Name:       Rest API Custom Meta Field
     * Plugin URI:        https://website.com/
     * Description:       Register post meta field
     * Version:           1.0
     * Author:            X
     * Author URI:        https://website.com/
     *
     */
    if ( ! defined( 'WPINC' ) ) {
    	die;
    }
    add_action( 'rest_api_init', 'register_posts_meta_field' );
    
    function register_posts_meta_field() {
        $object_type = 'post';
        $title_tag = array( // Validate and sanitize the meta value.
            // Note: currently (4.7) one of 'string', 'boolean', 'integer',
            // 'number' must be used as 'type'. The default is 'string'.
            'type'         => 'string',
            // Shown in the schema for the meta key.
            'description'  => 'A meta key associated with a string meta value.',
            // Return a single value of the type.
            'single'       => true,
            // Show in the WP REST API response. Default: false.
            'show_in_rest' => true,
        );
        register_meta( $object_type, '_rank_math_title', $title_tag );
    }

    Python script:

    import requests
    def create_post(username, password, base_url, title, slug, status, categories, title_tag):
        post_data = {
            "title": title,
            "slug": slug,
            "status": status,
            "categories": categories,
            "meta": {
                "rank_math_title": title_tag,
            }
        }
    
        try:
            # Send the HTTP request
            url = f"{base_url}posts"
            response = requests.post(url, auth=(username, password), json=post_data)
            
            # Check the response
            if response.status_code == 201:
                print('Post created successfully')
                print('Post ID:', response.json().get('id'))
            else:
                print('Failed to create post. Status Code:', response.status_code)
                print('Response:', response.text)
        except requests.exceptions.RequestException as e:
            print('An error occurred while making the request:', str(e))
    
    create_post("XXXX", "XXX", "https://website.com/wp-json/wp/v2/", "hej", "hej", "draft", "13", "THIS IS A TITLE TAG")
    Kasper
    Rank Math free

    I have fixed it myself now, but what is the post meta field called for rank math focus keyword?

    Hello,

    Our team is specialized only with PHP so any advice we might be able to give is related to that language.

    The custom meta fields from our plugin need to be registered as we mentioned before and to register for example the title this code can be added:

    
    add_action( 'rest_api_init', 'adding_rank_math_meta_rest' );
    
    function adding_rank_math_meta_rest() {
    	register_rest_field( 'post',
    		'rank_math_title',
    		array(
    			'type' => 'string',
    			'single' => true,
    			'show_in_rest' => true
    		)
    	);
    }
    

    After that has been registered, the data for this can be passed into the meta array with a code similar to this:

    
    wp_remote_post(
    		'https://my-domain.com/wp-json/wp/v2/posts',
    		array(
    			'headers' => array(
    				'Authorization' => 'Basic'
    			),
    			'body' => array(
    				'title'   => 'Title of my post',
    				'status'  => 'draft',
    				'meta' => array(
    					'rank_math_title' => 'SEO title'
    				)
    			)
    		)
    );
    

    As we mentioned before, all this is PHP code and if you are using Python you need to adapt these procedures to your programming language of choice.

    Thank you.

    Kasper
    Rank Math free

    Hi again,

    What is the meta field name for the RankMath focus keyword? I have made it work now, but I need to know what the meta field name is for the RankMath focus keyword?

    Hello,

    That field has the key of rank_math_focus_keyword in the postmeta table.

    Don’t hesitate to get in touch if you have any other questions.

    Kasper
    Rank Math free

    Thanks, How can i see a list of all possible fields?

    Hello,

    We don’t have a list publicly available with all the custom metadata fields but if you are looking for any in particular you can either look for the ones that start with the prefix rank_math_ in the postmeta table or just ping us here on the forums and we’ll let you know.

    Thank you.

    Hello,

    Since we did not hear back from you for 15 days, we are assuming that you found the solution. We are closing this support ticket.

    If you still need assistance or any other help, please feel free to open a new support ticket, and we will be more than happy to assist.

    Thank you.

Viewing 12 replies - 1 through 12 (of 12 total)

The ticket ‘Post rankmath title tag and meta description using WP REST API?’ is closed to new replies.