I need to add a feature called Kanji to Kana converter to my WordPress website. I’m using the Code Snippets plugin to inject scripts into my site.
After researching for a whole night, I found a free API (Yahoo! JAPAN Japanese Language Processing API).
Here is the documentation page for that API: API Documentation.
I don’t know what to do next.
Looking for a solution. Thanks in advance.
I asked ChatGPT for assistance, and it provided me with a PHP code snippet to inject through the Code Snippets plugin. Here is the code I received:
function kanji_to_kana_converter($query) {
$appId = 'your-client-id';
$url = 'https://jlp.yahooapis.jp/JIMService/V2/conversion';
$params = json_encode([
'id' => '1234-1',
'jsonrpc' => '2.0',
'method' => 'jlp.jimservice.conversion',
'params' => [
'q' => $query,
'format' => 'hiragana',
'mode' => 'kanakanji',
'option' => ['hiragana', 'katakana', 'alphanumeric', 'half_katakana', 'half_alphanumeric'],
'dictionary' => ['base', 'name', 'place', 'zip', 'symbol'],
'results' => 999
]
]);
$args = [
'body' => $params,
'headers' => [
'Content-Type' => 'application/json',
'User-Agent' => 'Yahoo AppID: ' . $appId,
],
'method' => 'POST',
];
$response = wp_remote_post($url, $args);
if (is_wp_error($response)) {
return 'Request failed';
}
$body = wp_remote_retrieve_body($response);
return json_decode($body, true);
}
function display_converter_shortcode($atts) {
$atts = shortcode_atts(['query' => ''], $atts, 'kanji_to_kana');
$result = kanji_to_kana_converter($atts['query']);
return '<pre>' . print_r($result, true) . '</pre>';
}
add_shortcode('kanji_to_kana', 'display_converter_shortcode');
I expected this code to allow users to enter Kanji text and receive the Kana conversion directly on my website using a shortcode. However, I have not been able to get it to work. The page either shows nothing or does not execute the expected functionality.
Could someone guide me on what might be going wrong and how to correctly implement this feature?
Bibek Sapkota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.