2010-09-27 12 views
8

Sto ricevendo post_title, post_content e altre cose in $ _REQUEST, nonché un file immagine. Voglio salvare tutto ciò come un post nel database di wordpress. Ho sulla mia paginaAggiunta di Wordpress a livello di codice con allegato

<?php 
require_once("wp-config.php"); 
$user_ID; //getting it from my function 
$post_title = $_REQUEST['post_title']; 
$post_content = $_REQUEST['post_content']; 
$post_cat_id = $_REQUEST['post_cat_id']; //category ID of the post 
$filename = $_FILES['image']['name']; 

//I got this all in a array 

$postarr = array(
'post_status' => 'publish', 
'post_type' => 'post', 
'post_title' => $post_title, 
'post_content' => $post_content, 
'post_author' => $user_ID, 
'post_category' => array($category) 
); 
$post_id = wp_insert_post($postarr); 

?> 

In questo modo ottenere tutte le cose in database come post, ma non so come aggiungere l'attaccamento e la sua posta meta.

Come posso farlo? Qualcuno può aiutarmi? Sono davvero confuso e ho passato qualche giorno a cercare di risolvere questo problema.

+0

Si dovrebbe essere compresi il wp-load.php invece di file di configurazione. –

risposta

8

Per aggiungere un allegato, l'uso wp_insert_attachment():

http://codex.wordpress.org/Function_Reference/wp_insert_attachment

ESEMPIO:

<?php 
    $wp_filetype = wp_check_filetype(basename($filename), null); 
    $attachment = array(
    'post_mime_type' => $wp_filetype['type'], 
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), 
    'post_content' => '', 
    'post_status' => 'inherit' 
); 
    $attach_id = wp_insert_attachment($attachment, $filename, 37); 
    // you must first include the image.php file 
    // for the function wp_generate_attachment_metadata() to work 
    require_once(ABSPATH . "wp-admin" . '/includes/image.php'); 
    $attach_data = wp_generate_attachment_metadata($attach_id, $filename); 
    wp_update_attachment_metadata($attach_id, $attach_data); 
?> 

Per aggiungere metadati, l'uso wp_update_attachment_metadata():

http://codex.wordpress.org/Function_Reference/wp_update_attachment_metadata

<?php wp_update_attachment_metadata($post_id, $data) ?> 
+1

penso che sia solo una copia incolla da quell'URL ..... puoi dirmi come posso usare le mie variabili? Caricherà l'immagine proveniente dalla richiesta al contenuto/upload di wp ?? –

+0

$ post_content va a post_content, $ post_id si ottiene dall'inserimento di post, ecc ... –

0

Se è necessario caricare l'allegato e inserirlo nel database, è necessario utilizzare media_handle_upload(), che farà tutto ciò per voi. Tutto quello che dovete fare è dare l'indice del file nella matrice $_FILES e l'ID del parent post:

$attachment_id = media_handle_upload('image', $post_id); 

if (is_wp_error($attachment_id)) { 
     // The upload failed. 
} else { 
     // The upload succeeded! 
} 
Problemi correlati