פונקציה יצירת פוסט ב WORDPRESS
יצירת פוסט.
הפונקציה המרכזית ששולחת פוסט
מקבלת ב post מערך ומחזירה את ה id של הפוסט
<?php wp_insert_post( $post, $wp_error ); ?>
דוגמא לשימוש:
// Create post object $post_arg = array( 'post_title' => 'My post', 'post_content' => 'This is my post.', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array(8,39) ); $post_id = wp_insert_post( $post_arg );
הקוד מכניס פוסט ל DB עם הנתונים שיש במערך ובמשתנה post_id אנחנו מקבלים את ה id של הפוסט שאיתו אפשר להשתמש כדי לעשות כל מיני תוספות לפוסט כמו הוספת\עדכון meta דאטה שנראה בהמשך.
טבלת wp_postmeta מחזיקה את השדות הנוספים שיש לפוסט היא מחזיקה את זה כ key ו value, בדרך כלל שומרים שם עוד שדות למשל אם אנחנו רוצים להוסיף לפוסט עוד שדה שמציין כותרת משנה אז אפשר לשמור ב wp_postmeta .
לעוד דוגמאות ולעוד שדות שאפשר להזין במערך, ניתן להיכנס לאתר הרשמי של wordpress לחצו פה.
יצירת\עדכון meta דאטה
<?php add_post_meta($post_id, $meta_key, $meta_value, $unique); ?> <?php update_post_meta($post_id, $meta_key, $meta_value, $prev_value); ?>
דוגמא:
<?php
if ( ! add_post_meta( 7, 'fruit', 'banana', true ) ) {
update_post_meta ( 7, 'fruit', 'banana' );
}
בדוגמא מוסיפים מאטה דאטה אם ה key לא קיים אחרת מעדכנים. יש להשים לב שהמספר 7 הוא ה post_id כפי שהזכרנו קודם ניתן לקבל אותו בהוספה.
פונקציה יצירת תמונה ראשית לפוסט ב WORDPRESS
תמונה ראשית.
<?php wp_insert_attachment( $attachment, $filename, $parent_post_id ); ?>
דוגמא:
// $filename should be the path to a file in the upload directory. $filename = '/path/to/uploads/2013/03/filename.jpg'; // The ID of the post this attachment is for. $parent_post_id = 37; // Check the type of file. We'll use this as the 'post_mime_type'. $filetype = wp_check_filetype( basename( $filename ), null ); // Get the path to the upload directory. $wp_upload_dir = wp_upload_dir(); // Prepare an array of post data for the attachment. $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ), 'post_content' => '', 'post_status' => 'inherit' ); // Insert the attachment. $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id ); // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once( ABSPATH . 'wp-admin/includes/image.php' ); // Generate the metadata for the attachment, and update the database record. $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $parent_post_id, $attach_id );