본문 바로가기

wordpress/wordpress기초

워드프레스 - 테마 만들기 - 책 정보 저장

반응형

save_post

저장할 필드값을 $_POST로 받으면 된다. 

 

functions.php

<?php
include 'functions-post-type.php';
include 'functions-setup.php';
include 'functions-taxonomy.php';
include 'functions-meta-box.php';
include 'functions-save.php';

 

functions-save.php

<?php
add_action('save_post_book', function(){
    var_dump($_POST);
});

 

POST 타입을 어떠한 방식으로 받아오는지 확인하기위해 var_dump를 사용해준다.

 

베르나르 베르베르의 개미에 대한 책 정보를 기입해 준다.

 

 

 

book-detail.php 

meta[내용] 방식으로 데이터를 받아오기때문에 meta안에 array를 생성해서 각자 받아온다

 

따라서 meta에 접근해서 데이터를 저장하는 방식으로 진행하면 된다. 

 

 

 

functions-save.php

<?php
add_action('save_post_book', function(){
    var_dump($_POST['meta']);
    exit;
});

post meta 

post 테이블 컬럼에는 없지만 post 관련해 필요한 갑승ㄹ 저장하는 DB 테이블, 워드프레스를 블로그 툴 이상으로 만드는데 핵심 기능 

 

 

update_post_meta(int $post_id, string $meta_key, mixed $meta_value, mixed $prev_value =');

 

get_post_meta(100);

100번 포스트의 메타값을 배열로 모두 가져온다

get_post_meta(100, 'price');

100번 포스트의 가격을 배열로 모두 가져온다.

get_post_meta(100, 'price', true)

100번 포스트의 가격을 문자열로 가져온다. 

 

functions-save.php

<?php
add_action('save_post_book', function(){
    update_post_meta( $_POST['ID'], 'price', $_POST['meta']['price']);
});

해당 내용대로 변경후 

 

 

를 입력하고 수정을 진행하면 

 

 

DB에 price가 key값으로 추가되고 value값으로 15000 이 추가된것을 확인할수 있다. 

 

이제 해당 부분들을 일괄처리하기 위해 

 

functions-save.php

<?php
add_action('save_post_book', function(){
    foreach($_POST['meta'] as $key => $value){
        var_dump($key, $value);
    }
});

업데이트를 누르고 나면 해당과 같이 나오게 된다 

 

functions-save.php

<?php
add_action('save_post_book', function($post_id){
    if(!empty($_POST['meta'])){
    foreach($_POST['meta'] as $key => $value){
        // update_post_meta($_POST['ID'], $key, $value);
        update_post_meta($post_id, $key, $value);
    }
    // 인자값을 여러개 받는경우 accepted_args를 넣어줘야한다(마지막 인자)
}});

DB에 위와 같이 들어가게 된다.

 

 

get_post_metapost_idkeysingle )

첫번째에는 인자값, 두번째에는 키값, 세번째에는 하나의 값만 가져오는경우에는 true로 지정해준다 

 

 

book-detail.php

<?php
// var_dump(get_post_meta($_GET['post'], 'price', true));
// echo get_the_ID();
?>

<table class="form-table">
    <tbody>
        <tr>
            <th><label for="subtitle_head">앞부제</label></th>
            <td>
                <input type="text" name="meta[subtitle_head]" id="subtitle_head" class="regular-text"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'subtitle_head', true)) ?>"
                >
            </td>
        </tr>
        <tr>
            <th><label for="subtitle_tail">뒷부제</label></th>
            <td>
                <input type="text" name="meta[subtitle_tail]" id="subtitle_tail" class="regular-text"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'subtitle_tail', true)) ?>"
                >
            </td>
        </tr>
        <tr>
            <th><label for="price">가격</label></th>
            <td>
                <input type="tel" name="meta[price]" id="price" class="regular-text"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'price', true)) ?>"
                 pattern="[0-9]+" title="숫자로만 적어주세요">
            </td>
        </tr>
        <tr>
            <th><label for="published_date">발행일</label></th>
            <td>
                <input type="date" name="meta[published_date]" id="published_date" class="regular-text"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'published_date', true)) ?>"
                >
            </td>
        </tr>
        <tr>
            <th><label for="pages">페이지수</label></th>
            <td>
                <input type="tel" name="meta[pages]" id="pages" class="small-text" pattern="[0-9]+" title="숫자로만 적어주세요"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'pages', true)) ?>"
                >
            </td>
        </tr>
    </tbody>
</table>

 

esc_attr

html의 속성값을 사용해서 값을 넣어줄때 해당 워드프레스해서 지원해주는 함수를 사용한다. 

 

 

값을 업데이트할 시에도 정상적으로 값을 가져온다. 

 

목차도 수정해준다

book-toc.php

<div class="postbox">
    <h2>목차</h2>
    <hr style="margin:0;"/>
    <div class="inside">
        <?php
        $meta_toc = esc_attr( get_post_meta(get_the_ID(), 'toc', true));
        wp_editor($meta_toc, 'book_toc', [
            'textarea_name' => 'meta[toc]'
        ]);
        ?>
    </div>
</div>

첫번째 부분인 ''에 위와같이 똑같이 넣어주면 목차도 동일하게 나오는것을 확인 할 수 있다. 

 

 

 

 

필드 추가하기 

meta 정보 필드 추가하기

ISBN(isbn), 저자소개(author_intro), 역자소개(translator_intro)

 

먼저 ISBN을 추가해준다 

 

book_detail.php

<?php
// var_dump(get_post_meta($_GET['post'], 'price', true));
// echo get_the_ID();
?>

<table class="form-table">
    <tbody>
        <tr>
            <th><label for="subtitle_head">앞부제</label></th>
            <td>
                <input type="text" name="meta[subtitle_head]" id="subtitle_head" class="regular-text"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'subtitle_head', true)) ?>"
                >
            </td>
        </tr>
        <tr>
            <th><label for="subtitle_tail">뒷부제</label></th>
            <td>
                <input type="text" name="meta[subtitle_tail]" id="subtitle_tail" class="regular-text"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'subtitle_tail', true)) ?>"
                >
            </td>
        </tr>
        <tr>
            <th><label for="price">가격</label></th>
            <td>
                <input type="tel" name="meta[price]" id="price" class="regular-text"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'price', true)) ?>"
                 pattern="[0-9]+" title="숫자로만 적어주세요">
            </td>
        </tr>
        <tr>
            <th><label for="published_date">발행일</label></th>
            <td>
                <input type="date" name="meta[published_date]" id="published_date" class="regular-text"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'published_date', true)) ?>"
                >
            </td>
        </tr>
        <tr>
            <th><label for="pages">페이지수</label></th>
            <td>
                <input type="tel" name="meta[pages]" id="pages" class="small-text" pattern="[0-9]+" title="숫자로만 적어주세요"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'pages', true)) ?>"
                >
            </td>
        </tr>

        <tr>
            <th><label for="isbn">ISBN</label></th>
            <td>
                <input type="text" name="meta[isbn]" id="isbn" class="regular-text"
                value="<?= esc_attr(get_post_meta(get_the_ID(), 'isbn', true)) ?>"
                >
            </td>
        </tr>

        
    </tbody>
</table>

 

저자와 역자소개는 길어지므로 text 관련을 사용해야하므로 

function-meta-box.php를 활용한다 

 

book-author-intro와 book-translator-intro를 추가해준다. 

function-meta-box.php

<?php
add_action('add_meta_boxes_book', function () {
    add_meta_box('book-detail', '책 상세 정보', function () {
        include 'meta-box/book-detail.php';
    }, 'book');
});

add_action('edit_form_advanced', function () {
    if (get_current_screen()->post_type === 'book') {
        include 'meta-box/book-toc.php';
        include 'meta-box/book-author-intro.php';
        include 'meta-box/book-translator-intro.php';
    }
});

 

book-author-intro.php

<div class="postbox">
    <h2>저자소개</h2>
    <hr style="margin:0;"/>
    <div class="inside">
        <?php
        $book_author_intro = get_post_meta(get_the_ID(), 'book_author_intro', true);
        wp_editor($book_author_intro, 'book_author_intro', [
            'textarea_name' => 'meta[book_author_intro]',
            'textarea_rows' => 5
        ]);
        ?>
    </div>
</div>

book-translator-intro.php 

<div class="postbox">
    <h2>역자소개</h2>
    <hr style="margin:0;"/>
    <div class="inside">
        <?php
        $book_translator_intro = get_post_meta(get_the_ID(), 'book_translator_intro', true);
        wp_editor($book_translator_intro, 'book_translator_intro', [
            'textarea_name' => 'meta[book_translator_intro]',
            'textarea_rows' => 5
        ]);
        ?>
    </div>
</div>

editor을 사용할때는 esc_attr을 사용하지 않는다(에디터가 자동으로 해준다)

 

정상적으로 삽입이 되어있고 결과물 또한 정상적으로 나오게 된다. 

 

 

반응형