Inquiry Regarding REST API Limitations on WordPress.com

  • Unknown's avatar

    I have been using Python to post content to my WordPress site, and I included the _yoast_wpseo_focuskw field in the meta data for the Yoast SEO plugin. However, after posting, the focus keyword does not appear in Yoast SEO. This worked correctly on my self-hosted WordPress site, but since I moved to WordPress.com hosting, it no longer shows up. What could be the reason for this?

    The blog I need help with is: (visible only to logged in users)

  • Hi there!

    Can you provide an example API call you are making?

    Also, have you tried checking the meta field in the database directly to see if the data is there? You can check the database via SSH or phpMyAdmin.

    If the API call is not failing and the data is in the database, it sounds like an object cache issue. You may need to clear cache after your updates or explicitly hook into a relevant Yoast or the save_post hook and call wp_cache_flush(). Alternatively, cache can be manually cleared from the Dashboard: https://wordpress.com/support/clear-your-sites-cache/

    Hope this helps!

  • Unknown's avatar

    Apologies for the delayed response, and I hope you don’t mind me asking additional related questions.

    Currently, I am using Jetpack SEO (on a Business Plan) as Yoast SEO was too complex to manage for my needs. However, I am facing issues with posting using Python, particularly when trying to integrate the summary, SEO title, and SEO description into Jetpack SEO.

    Below is my Python client code for creating a post:

    def post(self, post_content, gutenberg_formmatted, featured_image_id):
        LOG(f'Post를 생성합니다.')
        endpoint = f'https://public-api.wordpress.com/rest/v1.1/sites/{self.site_id}/posts/new'
    
        if not self.token:
            ERROR('액세스 토큰이 없습니다.')
            return None
    
        headers = {
            "Authorization": f"Bearer {self.token}",
            "Content-Type": "application/json"
        }
    
        tags = post_content.get('tags', None)
        LOG(f'포스트 태그: {tags}')
    
        # 포스트 데이터 초기화
        post_data = {
            "title": post_content['title'],
            "content": gutenberg_formmatted,
            "status": "draft",
            "categories": CATEGORY[post_content['category']]
        }
    
        meta = post_content.get('meta', None)
        if meta:
            focus_kw = meta.get('_yoast_wpseo_focuskw', None)
            meta_desc = meta.get('_yoast_wpseo_metadesc', None)
            seo_title = meta.get('_yoast_wpseo_title', None)
            og_title = meta.get('og_title', None)
            og_desc = meta.get('og_description', None)
            og_image = meta.get('og_image', None)
            LOG(f"SEO Title : {seo_title}")
            LOG(f"SEO 요약글 : {meta_desc}")
            LOG(f"SEO og_title : {og_title}")
            LOG(f"SEO og_desc : {og_desc}")
    
            # 'meta'와 'yoast_head_json' 섹션 추가
            post_data["metadata"] = {}
            if focus_kw:
                post_data["metadata"]["focus_keyword"] = focus_kw
            if seo_title:
                post_data["metadata"]["_jetpack_seo_title"] = seo_title
            if meta_desc:
                post_data["metadata"]["_jetpack_seo_description"] = meta_desc
                post_data["metadata"]["_jetpack_post_excerpt"] = meta_desc
    
            # Open Graph 메타 데이터 추가
            if og_title:
                post_data["metadata"]["_jetpack_social_title"] = og_title
            if og_desc:
                post_data["metadata"]["_jetpack_social_description"] = og_desc
            if og_image:
                post_data["metadata"]["_jetpack_social_image"] = og_image
    
        # 특성이미지 설정
        if featured_image_id:
            post_data['featured_media'] = featured_image_id
            post_data['featured_image'] = featured_image_id
    
        response = requests.post(endpoint, json=post_data, headers=headers)
        if response.status_code == 200:
            LOG(f"포스트가 성공적으로 생성되었습니다.")
        else:
            LOG(f"포스트 생성에 실패했습니다. 상태 코드: {response.status_code}")
  • Unknown's avatar

    In addition, I have created the following WordPress code snippet with the help of WordPress.com AI assistance. It is designed to handle Jetpack SEO metadata via the REST API:

    // Jetpack SEO 메타데이터 REST API 등록
    function register_jetpack_seo_metadata() {
        // 단일 메타데이터 필드 등록
        register_post_meta('post', '_jetpack_seo_title', array(
            'show_in_rest' => true,
            'single' => true,
            'type' => 'string',
            'auth_callback' => function() {
                return current_user_can('edit_posts');
            }
        ));
    
        register_post_meta('post', '_jetpack_seo_description', array(
            'show_in_rest' => true,
            'single' => true,
            'type' => 'string',
            'auth_callback' => function() {
                return current_user_can('edit_posts');
            }
        ));
    
        // 나머지 필드들도 동일한 방식으로 등록
        $other_fields = array(
            '_jetpack_social_title',
            '_jetpack_social_description',
            '_jetpack_social_image',
            '_jetpack_post_excerpt'
        );
    
        foreach ($other_fields as $field) {
            register_post_meta('post', $field, array(
                'show_in_rest' => true,
                'single' => true,
                'type' => 'string',
                'auth_callback' => function() {
                    return current_user_can('edit_posts');
                }
            ));
        }
    }
    remove_action('init', 'register_jetpack_seo_metadata');
    add_action('rest_api_init', 'register_jetpack_seo_metadata');
    
    // REST API로 전송된 메타데이터 처리
    function handle_jetpack_seo_metadata($post_id) {
        // REST API 요청인지 확인
        if (defined('REST_REQUEST') && REST_REQUEST) {
            // POST 데이터에서 metadata 배열 확인
            $request_data = json_decode(file_get_contents('php://input'), true);
    
            if (isset($request_data['metadata']) && is_array($request_data['metadata'])) {
                foreach ($request_data['metadata'] as $meta) {
                    if (isset($meta['key']) && isset($meta['value'])) {
                        update_post_meta($post_id, $meta['key'], sanitize_text_field($meta['value']));
                    }
                }
            }
        }
    }
    add_action('save_post', 'handle_jetpack_seo_metadata');
    
    // REST API 응답에 SEO 메타데이터 포함
    function add_seo_data_to_rest_response($response, $post, $request) {
        if (!empty($response->data)) {
            $post_id = $post->ID;
    
            // Jetpack SEO 메타데이터 수집
            $seo_data = array(
                'seo_title' => get_post_meta($post_id, '_jetpack_seo_title', true),
                'seo_description' => get_post_meta($post_id, '_jetpack_seo_description', true),
                'social_title' => get_post_meta($post_id, '_jetpack_social_title', true),
                'social_description' => get_post_meta($post_id, '_jetpack_social_description', true),
                'social_image' => get_post_meta($post_id, '_jetpack_social_image', true),
                'excerpt' => get_post_meta($post_id, '_jetpack_post_excerpt', true)
            );
    
            // 응답에 SEO 데이터 추가
            $response->data['jetpack_seo'] = $seo_data;
        }
    
        return $response;
    }
    add_filter('rest_prepare_post', 'add_seo_data_to_rest_response', 10, 3);
    
    add_action('rest_api_init', function() {
        register_rest_route('debug/v1', '/error-log', array(
            'methods' => 'GET',
            'callback' => function() {
                if (current_user_can('manage_options')) {
                    $log_file = WP_CONTENT_DIR . '/debug.log';
                    if (file_exists($log_file)) {
                        return new WP_REST_Response(
                            array('log' => file_get_contents($log_file))
                        );
                    }
                    return new WP_REST_Response(
                        array('message' => 'No log file found')
                    );
                }
                return new WP_REST_Response(
                    array('message' => 'Permission denied')
                );
            },
            'permission_callback' => function() {
                return current_user_can('manage_options');
            }
        ));
    });
  • The topic ‘Inquiry Regarding REST API Limitations on WordPress.com’ is closed to new replies.