functions.php
PHP<?php
add_action( 'admin_enqueue_scripts', 'my_books_admin_assets' );
function my_books_admin_assets( $hook ) {
if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
return;
}
wp_enqueue_script(
'my-cfs-rakuten-books',
get_stylesheet_directory_uri() . '/js/cfs-rakuten-books.js',
array( 'jquery' ),
'1.0.0',
true
);
wp_localize_script( 'my-cfs-rakuten-books', 'myBooksApi', array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'my_fetch_rakuten_book' ),
) );
}
add_action( 'wp_ajax_my_fetch_rakuten_book', 'my_fetch_rakuten_book' );
function my_fetch_rakuten_book() {
check_ajax_referer( 'my_fetch_rakuten_book', 'nonce' );
if ( ! current_user_can( 'edit_posts' ) ) {
wp_send_json_error( array( 'message' => '権限がありません。' ), 403 );
}
$isbn = preg_replace( '/\D+/', '', wp_unslash( $_POST['isbn'] ?? '' ) );
if ( 13 !== strlen( $isbn ) ) {
wp_send_json_error( array( 'message' => 'ISBNは13桁で入力してください。' ), 400 );
}
if ( ! defined( 'MY_RAKUTEN_APPLICATION_ID' ) ||
! defined( 'MY_RAKUTEN_ACCESS_KEY' ) ) {
wp_send_json_error( array( 'message' => 'API設定がありません。' ), 500 );
}
$url = add_query_arg( array(
'format' => 'json',
'applicationId' => MY_RAKUTEN_APPLICATION_ID,
'isbn' => $isbn,
), 'https://openapi.rakuten.co.jp/services/api/BooksBook/Search/20170404' );
$response = wp_safe_remote_get( $url, array(
'timeout' => 10,
'headers' => array( 'accessKey' => MY_RAKUTEN_ACCESS_KEY ),
) );
if ( is_wp_error( $response ) ||
200 !== wp_remote_retrieve_response_code( $response ) ) {
wp_send_json_error( array( 'message' => '書籍情報を取得できませんでした。' ), 502 );
}
$json = json_decode( wp_remote_retrieve_body( $response ), true );
$book = $json['Items'][0]['Item'] ?? array();
if ( ! $book ) {
wp_send_json_error( array( 'message' => '該当する書籍がありません。' ), 404 );
}
$image_url = remove_query_arg( '_ex', $book['largeImageUrl'] ?? '' );
wp_send_json_success( array(
'bookname' => sanitize_text_field( $book['title'] ?? '' ),
'subtitle' => sanitize_text_field( $book['subTitle'] ?? '' ),
'caption' => sanitize_textarea_field( $book['itemCaption'] ?? '' ),
'author' => sanitize_text_field( $book['author'] ?? '' ),
'size' => sanitize_text_field( $book['size'] ?? '' ),
'bookurl' => esc_url_raw( $book['itemUrl'] ?? '' ),
'fee' => absint( $book['itemPrice'] ?? 0 ),
'buyday' => sanitize_text_field( $book['salesDate'] ?? '' ),
'publisher' => sanitize_text_field( $book['publisherName'] ?? '' ),
'bookimage' => esc_url_raw( $image_url ),
) );
}