본문 바로가기

wordpress/wordpress기초

워드프레스 - 테마 만들기 - 카카오 API로 책 가져오기 2

반응형

ajax 사용하기

 

ajax 사용

관리자단

add_action( 
    'wp_ajax_{my_action}', 
    function () {
        // ...
        die();
    }
);
$.get(ajaxurl, {
    action: 'my_action',
    key: value
});

 

비관리자단

add_action( 
    'wp_ajax_nopriv_{my_action}', 
    function(){
        // ...
        die();
    } 
);
$.get(ajaxurl, {
    action: 'my_action',
    key: value
});

 

import-books-result.php

<div class="wrap">
    <?php
    if ($response_code !== 200) {
    ?>

        <h2>에러 : <?= $body->errorType ?></h2>
        <p><?= $body->message ?></p>
    <?php
    } else {
    ?>
        <h2>검색 결과</h2>

        <table class="widefat striped">
            <thead>
                <tr>
                    <th scope="col">표지</th>
                    <th scope="col">제목</th>
                    <th scope="col">저자</th>
                    <th scope="col">출판사</th>
                    <th scope="col">발행일 </th>
                    <th scope="col"> </th>
                </tr>
            </thead>
            <tbody>
                <?php

                foreach ($body->documents as $book) { ?>
                    <tr>
                        <td><img height="100" src="<?= $book->thumbnail ?>"> </td>
                        <td><?= $book->title ?></td>
                        <td><?= implode(', ', $book->authors) ?></td>
                        <td><?= $book->publisher ?></td>
                        <td nowrap><?= date('Y-m-d', strtotime($book->datetime)) ?></td>
                        <td nowrap><button class="button js-import" 
                        data-book="<?=base64_encode(json_encode($book)) ?>"
                        >임포트</button></td>
                    </tr>

                <?php
                }
                ?>
            </tbody>
        </table>
    <?php
    }
    ?>
</div>

 

ImportBooks.php

<?php
class ImportBooks
{
    function __construct()
    {
        add_action('admin_menu', [$this, 'addMenu']);
        add_action('admin_enqueue_scripts', [$this, 'scripts']);
        add_action('wp_ajax_import_books', [$this, 'import']);
    }

    public function addMenu()
    {
        add_submenu_page(
            "edit.php?post_type=book",
            "책 가져오기",
            "가져오기",
            "publish_posts",
            "import-books",
            function () {
                if ($_SERVER['REQUEST_METHOD'] === 'GET') {
                    include get_template_directory() . '/admin-pages/import-books-form.php';
                }
                if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                    $this->result();
                }
            }

        );
    }
    public function result()
    {
        $response = $this->get($_POST['query']);
        $response_code = wp_remote_retrieve_response_code($response);
        $response_message = wp_remote_retrieve_response_message($response);
        $headers = wp_remote_retrieve_headers($response);
        $body = json_decode(wp_remote_retrieve_body($response));

        include get_template_directory() . '/admin-pages/import-books-result.php';
    }


    public function get($query)
    {
        $url = "https://dapi.kakao.com/v3/search/book?";
        $query_string = http_build_query([
            'query' => $query,
        ]);

        // var_dump($url, $query_string);
        $args = [
            'httpversion' => '1.1',
            'headers' => [
                'Authorization' => 'KakaoAK ' . KAKAO_REST_API_KEY
            ]
        ];

        $response = wp_remote_get($url . $query_string, $args);
        return $response;
    }

    public function scripts()
    {
        $current_screen = get_current_screen();
        if ($current_screen->id === 'book_page_import-books') {
            wp_enqueue_script(
                'import-books',
                get_template_directory_uri() . '/js/import-books.js',
                ['jquery'],
                '1.0',
                true
            );
        }
    }
    public function import(){
        $book = json_decode(base64_decode($_POST['base64EncodedBook']));
        //book을 insert 하면된다
        $result = [
            'result' => 1,
            'message' => $book ->title . ' 입력 완료.'
        ];

        echo json_encode($result);
        die();
    }
}

new ImportBooks();

 

import를 누르면 정상적으로 해당 내용들이 ajax로 요청이된다. 

 

 

책 저장하기

ImportBooks.php

<?php
class ImportBooks
{
    function __construct()
    {
        add_action('admin_menu', [$this, 'addMenu']);
        add_action('admin_enqueue_scripts', [$this, 'scripts']);
        add_action('wp_ajax_import_books', [$this, 'import']);
    }

    public function addMenu()
    {
        add_submenu_page(
            "edit.php?post_type=book",
            "책 가져오기",
            "가져오기",
            "publish_posts",
            "import-books",
            function () {
                if ($_SERVER['REQUEST_METHOD'] === 'GET') {
                    include get_template_directory() . '/admin-pages/import-books-form.php';
                }
                if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                    $this->result();
                }
            }

        );
    }
    public function result()
    {
        include get_template_directory() . '/admin-pages/import-books-form.php';
        $response = $this->get($_POST['query']);
        $response_code = wp_remote_retrieve_response_code($response);
        $response_message = wp_remote_retrieve_response_message($response);
        $headers = wp_remote_retrieve_headers($response);
        $body = json_decode(wp_remote_retrieve_body($response));

        include get_template_directory() . '/admin-pages/import-books-result.php';
    }


    public function get($query)
    {
        $url = "https://dapi.kakao.com/v3/search/book?";
        $query_string = http_build_query([
            'query' => $query,
        ]);

        // var_dump($url, $query_string);
        $args = [
            'httpversion' => '1.1',
            'headers' => [
                'Authorization' => 'KakaoAK ' . KAKAO_REST_API_KEY
            ]
        ];

        $response = wp_remote_get($url . $query_string, $args);
        return $response;
    }

    public function scripts()
    {
        $current_screen = get_current_screen();
        if ($current_screen->id === 'book_page_import-books') {
            wp_enqueue_script(
                'import-books',
                get_template_directory_uri() . '/js/import-books.js',
                ['jquery'],
                '1.0',
                true
            );
        }
    }
    public function import(){
        $book = json_decode(base64_decode($_POST['base64EncodedBook']));
        //book을 insert
        //저자, 역자
        try{
            $post_id = wp_insert_post([
                'post_title' => $book->title,
                'post_content' => $book->contents,
                'post_status' => 'publish',
                'post_type' =>'book'
            ], true);
            if(is_wp_error( $post_id )){
                $wp_error = $post_id;
                throw new Exception($wp_error -> get_error_message());
            }
            $response = [
                'result' => 'success',
                'message' => $book ->title . ' 입력 완료.'
            ];
        }catch(\Exception $e){
            $response = [
                'result' => 'fail',
                'message' => $e -> getMessage()
            ];
        }
       

        echo json_encode($response);
        die();
    }
}

new ImportBooks();

 

import-books.js

jQuery(".js-import").click(function () {
    var $ = jQuery,
    base64EncodedBook = $(this).data('book');

  $.post(
    ajaxurl,
    {
      action: "import_books",
      base64EncodedBook: base64EncodedBook
    },
    function (response) {
      console.log(response);
      if(response.result === 'success'){
          alert(response.message);
      }
    }, 'json');
});

 

 

임포트를 누르면 

 

 

 

 

 

 

 

정상적으로 내용들이 잘 담기게 된다. 

 

2. 저자와 역자를 저장하기 

 

taxonomy - term

taxonomy는 term 그안의 세부내용들을 term이라고 한다.

 

 

ImportBooks.php

 

 

 

<?php
class ImportBooks
{
    function __construct()
    {
        add_action('admin_menu', [$this, 'addMenu']);
        add_action('admin_enqueue_scripts', [$this, 'scripts']);
        add_action('wp_ajax_import_books', [$this, 'import']);
    }

    public function addMenu()
    {
        add_submenu_page(
            "edit.php?post_type=book",
            "책 가져오기",
            "가져오기",
            "publish_posts",
            "import-books",
            function () {
                if ($_SERVER['REQUEST_METHOD'] === 'GET') {
                    include get_template_directory() . '/admin-pages/import-books-form.php';
                }
                if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                    $this->result();
                }
            }

        );
    }
    public function result()
    {
        include get_template_directory() . '/admin-pages/import-books-form.php';
        $response = $this->get($_POST['query']);
        $response_code = wp_remote_retrieve_response_code($response);
        $response_message = wp_remote_retrieve_response_message($response);
        $headers = wp_remote_retrieve_headers($response);
        $body = json_decode(wp_remote_retrieve_body($response));

        include get_template_directory() . '/admin-pages/import-books-result.php';
    }


    public function get($query)
    {
        $url = "https://dapi.kakao.com/v3/search/book?";
        $query_string = http_build_query([
            'query' => $query,
        ]);

        // var_dump($url, $query_string);
        $args = [
            'httpversion' => '1.1',
            'headers' => [
                'Authorization' => 'KakaoAK ' . KAKAO_REST_API_KEY
            ]
        ];

        $response = wp_remote_get($url . $query_string, $args);
        return $response;
    }

    public function scripts()
    {
        $current_screen = get_current_screen();
        if ($current_screen->id === 'book_page_import-books') {
            wp_enqueue_script(
                'import-books',
                get_template_directory_uri() . '/js/import-books.js',
                ['jquery'],
                '1.0',
                true
            );
        }
    }
    public function import()
    {
        $book = json_decode(base64_decode($_POST['base64EncodedBook']));
        //book을 insert
        //저자, 역자
        try {
            $post_id = $this->insertBook($book);

            //저자 역자 지정
            if (!empty($book->authors)) {
                $this->insertAuthors($post_id, $book);
            }
            if (!empty($book->translators)) {
                $this->insertTranslators($post_id, $book);
            }


            $response = [
                'result' => 'success',
                'message' => $book->title . ' 입력 완료.'
            ];
        } catch (\Exception $e) {
            $response = [
                'result' => 'fail',
                'message' => $e->getMessage()
            ];
        }


        echo json_encode($response);
        die();
    }

    private function insertBook($book)
    {
        $post_id = wp_insert_post([
            'post_title' => $book->title,
            'post_content' => $book->contents,
            'post_status' => 'publish',
            'post_type' => 'book'
        ], true);
        if (is_wp_error($post_id)) {
            $wp_error = $post_id;
            throw new Exception('책 입력중 에러' . $wp_error->get_error_code() . ": " . get_error_message());
        }

        return $post_id;
    }

    private function insertAuthors($post_id, $book)
    {
        $result =  wp_set_post_terms($post_id, $book->authors, 'book_author', true);
        if ($result === false) {
            throw new Exception('저자 입력중 post_id에 0이 들어왔습니다');
        }

        if (is_wp_error($result)) {
            $wp_error = $result;
            throw new Exception('저자 입력중 에러' . $wp_error->get_error_code() . ": " . get_error_message());
        }
        return $result;
    }

    private function insertTranslators($post_id, $book)
    {
        $result =  wp_set_post_terms($post_id, $book->translators, 'book_translator', true);
        if ($result === false) {
            throw new Exception('역자 입력중 post_id에 0이 들어왔습니다');
        }

        if (is_wp_error($result)) {
            $wp_error = $result;
            throw new Exception('역자 입력중 에러' . $wp_error->get_error_code() . ": " . get_error_message());
        }
        return $result;
    }
}

new ImportBooks();

 

 

 

 

 

반응형