Retrieve language of a WordPress post using the WordPress API

Tiempo de lectura: < 1 minuto

html
Copy code

// Get the post language using SQL query
global $wpdb;
$language = $wpdb->get_var($wpdb->prepare("
    SELECT wp_terms.slug
    FROM {$wpdb->posts} AS wp_posts
    JOIN {$wpdb->term_relationships} AS wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
    JOIN {$wpdb->terms} AS wp_terms ON (wp_term_relationships.term_taxonomy_id = wp_terms.term_id)
    JOIN {$wpdb->term_taxonomy} AS wp_term_taxonomy ON (wp_terms.term_id = wp_term_taxonomy.term_id)
    WHERE wp_posts.ID = %d
    AND wp_term_taxonomy.taxonomy = 'language'
", $post->ID));

// Add the language to the response object
$response->data['language'] = $language;

return $response;
}
add_filter('rest_prepare_post', 'custom_rest_prepare_post', 10, 3);

In this code, we are using the rest_prepare_post filter to intercept the response from the WordPress API before it is sent to the client. Then, we execute the SQL query inside the custom_rest_prepare_post function to get the post language using the $wpdb class, which provides an interface to interact with the WordPress database.

Finally, we add the obtained language to the response object using the key 'language'.

Once you have added this code to your functions.php file or your custom plugin, when making a request to the WordPress API to get the posts, the 'language' field will be included in the response along with the other post data.

Now, when making the request to the WordPress API, it returns the following:

"tags": [
        1528,
        1012,
        826,
        1525,
        1527,
        819,
        1538,
        813,
        1526,
        1524,
        1543,
        1541
    ],
    "language": "es",

Leave a Comment