สอนสร้าง Plugin WordPress (18) : ตัวอย่าง Save Post Meta ลง Database เเละการดึงข้อมูลมาแสดง

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: สอนสร้าง Plugin WordPress (18) : ตัวอย่าง Save Post Meta ลง Database เเละการดึงข้อมูลมาแสดง

Re: สอนสร้าง Plugin WordPress (18) : ตัวอย่าง Save Post Meta ลง Database เเละการดึงข้อมูลมาแสดง

โดย mindphp » 25/10/2016 9:42 pm

รวมกระทู้ บทความสอนสร้าง Plugin WordPress
https://www.mindphp.com/forums/viewtopic ... 25&t=36079

สอนสร้าง Plugin WordPress (18) : ตัวอย่าง Save Post Meta ลง Database เเละการดึงข้อมูลมาแสดง

โดย thatsawan » 25/10/2016 12:03 pm

ตัวอย่างการใช้งาน
เราจะใช้คำสั่ง update_post_meta เพื่อบันทึกข้อมูลจาก Fields

โค้ด: เลือกทั้งหมด

/**
 * Save post metadata when a post is saved.
 */
function save_meta($post_id) {
  
    if ( isset( $_POST['my_meta_box_text'] ) ) {
        update_post_meta( $post_id, 'my_meta_box_text', sanitize_text_field( $_POST['my_meta_box_text'] ) );
    }
    
    if ( isset( $_POST['custom_fields_text'] ) ) {
        update_post_meta( $post_id, 'custom_fields_text', sanitize_text_field( $_POST['custom_fields_text'] ) );
    }
}
add_action( 'save_post', 'save_meta' );
* ตัวอย่างการรับค่าจาก Fields เพื่อมา Save

โค้ด: เลือกทั้งหมด

get_post_meta($post->ID)
* จะเป็นการดึงข้อมูลที่บันทึกมาแสดง

โค้ด: เลือกทั้งหมด

function custom_meta_box_markup($post)
{ 
    $data_meta = get_post_meta($post->ID);

   echo ' <label for="my_meta_box_text">Text Label</label>
    <input type="text" name="my_meta_box_text" id="my_meta_box_text" value="'. $data_meta['my_meta_box_text'][0] .'" />';

  
  //wp_nonce_field(basename(__FILE__),'add_custom_meta_box');

    echo ' <div class="mata-editor">';
    $content = get_post_meta($post->ID,'custom_fields_text',true);
    $editor_id = 'custom_fields_text';

    
    $setting = array(
          'textarea_rows' => 8, 
          'media_buttons' => false, // show button add media

      );
    wp_editor( $content, $editor_id, $setting );

    echo '</div>';
}

function add_custom_meta_box()
{
    add_meta_box("demo-meta-box", "Custom Meta Box", "custom_meta_box_markup", "book", "normal", "high", null);
}

add_action("add_meta_boxes", "add_custom_meta_box");

/**
 * Save post metadata when a post is saved.
 */
function save_meta($post_id) {
  
    if ( isset( $_POST['my_meta_box_text'] ) ) {
        update_post_meta( $post_id, 'my_meta_box_text', sanitize_text_field( $_POST['my_meta_box_text'] ) );
    }
    
    if ( isset( $_POST['custom_fields_text'] ) ) {
        update_post_meta( $post_id, 'custom_fields_text', sanitize_text_field( $_POST['custom_fields_text'] ) );
    }
}
add_action( 'save_post', 'save_meta' );

 
รูปภาพ
รูปภาพ

ข้างบน