2014-04-03 12 views
7

Sto lavorando al mio primo plug-in WP e sono bloccato.WordPress Ottieni Post Meta dalla funzione di richiamata

Ho creato un campo personalizzato (campo 1) nella pagina di posta sotto l'editor di contenuti. Salva correttamente. :)

Ho creato un campo personalizzato (campo 2) all'interno del popup della libreria multimediale quando si aggiungono i supporti. Salva correttamente. :)

Quello che sto volendo fare, è utilizzare il valore dal campo 1 come valore predefinito per il campo 2.

Sono sospettare che il problema risiede nella funzione di callbackattachment_fields_to_edit .

Penso che $ post è ora riferisce al "post file allegato" vero e proprio, piuttosto che il post stesso, in modo da quando sto riferimento i miei valori salvati:

$post_meta = get_post_meta($post->ID); 

è in realtà tirando tutte le meta associato a quell'allegato e non al post corrente. È possibile estrarre il meta dal post effettivo?

Questo codice è dal Codex:

function my_add_attachment_location_field($form_fields, $post) { 
    $field_value = get_post_meta($post->ID, 'location', true); 
    $form_fields['location'] = array(
     'value' => $field_value ? $field_value : '', 
     'label' => __('Location'), 
     'helps' => __('Set a location for this attachment') 
    ); 
    return $form_fields; 
} 
add_filter('attachment_fields_to_edit', 'my_add_attachment_location_field', 10, 2); 

function my_save_attachment_location($attachment_id) { 
    if (isset($_REQUEST['attachments'][$attachment_id]['location'])) { 
     $location = $_REQUEST['attachments'][$attachment_id]['location']; 
     update_post_meta($attachment_id, 'location', $location); 
    } 
} 
add_action('edit_attachment', 'my_save_attachment_location'); 

Come dovrei get_post_meta per il post corrente che stiamo inserendo l'allegato in? Ciò dovrebbe accadere nella funzione callback my_add_attachment_location_field nel codice del codice sopra.

Grazie!

+0

hai accesso al tuo database? – David

+0

in realtà dove vuoi utilizzare questo, come l'immagine in primo piano o per immagini aggiuntive? – David

+0

immagini aggiuntive – Aaron

risposta

1

Un modo mi viene in mente:

$ actual_post_id = $ post-> post_parent;

Poi si può fare:

get_post_meta ($ actual_post_id)

+0

Grazie, ma questo non sembra funzionare. Ho anche cercato in giro un po 'e non riesco a fare progressi. – Aaron

+0

Hmmm ... Vorrei var_dump ($ post) e vedere se la proprietà post_parent è effettivamente impostata. Se continua a non funzionare, prova questo https://codex.wordpress.org/Function_Reference/get_post_ancestors. – Edenbauer

+0

Grazie! Penso che $ post sia in realtà un "post" completamente separato per l'immagine/allegato e non il vero post stesso? Non riesco a echeggiare l'ID del post effettivo all'interno del popup della libreria multimediale a causa di questo. Sembra che la funzione a cui si fa riferimento stia volendo l'ID postale, ma ci provo. – Aaron

1

Si può provare la seguente:

/** 
* Display custom 'location' attachment field 
*/ 

function so_22850878_attachment_fields_to_edit($form_fields, $post) 
{ 
    $field_value = get_post_meta($post->post_parent, 'location', true); 

    $form_fields['location'] = array(
     'value' => $field_value ? $field_value : '', 
     'label' => __('Location'), 
     'helps' => __('Set a location for this attachment') 
    ); 

    return $form_fields; 
} 

add_filter('attachment_fields_to_edit', 
      'so_22850878_attachment_fields_to_edit', 10, 2); 

e

/** 
* Edit attachment fields 
*/ 

function so_22850878_edit_attachment($attachment_id) 
{ 
    $p = get_post($attachment_id); 

    if (isset($_REQUEST['attachments'][$attachment_id]['location'])) 
    { 
     $location = $_REQUEST['attachments'][$attachment_id]['location']; 

     // Save the value of the 'location' attachment field 
     // to the 'location' post meta of the post parent if it exists: 

     if(! is_null($p) 
      && 0 < $p->post_parent 
     ) 
      update_post_meta($p->post_parent, 
           'location', 
           sanitize_text_field($location) 
      ); 
    } 
} 

add_action('edit_attachment', 'so_22850878_edit_attachment'); 

per aggiornare il valore meta del post genitore location dal popup multimediale.

Si potrebbe anche voler controllare questo fuori, se si modifica l'allegato direttamente dalle pagine libreria multimediale:

/** 
* Save attachment fields 
*/ 

function so_22850878_attachment_fields_to_save($post, $attachment) 
{ 
    $p = get_post($post['ID']); 

    // Save the value of the 'location' attachment field 
    // to the 'location' post meta of the post parent if it exists: 

    if(isset($attachment['location']) 
     && ! is_null($p) 
     && 0 < $p->post_parent 
    ) 
     update_post_meta($p->post_parent, 
          'location', 
          sanitize_text_field($attachment['location']) 
     ); 

    return $post; 
} 

add_action('attachment_fields_to_save', 
      'so_22850878_attachment_fields_to_save', 10, 2); 

io non sono sicuro di che tipo di flusso di lavoro che avete in mente, ma penso che ci sia un problema con la tua idea, se ho capito bene:

quando si aggiorna il campo location nel popup dei media, sembra che si desidera aggiornare il post meta valore location per il parent post. Ma poiché la schermata di modifica dei post non si aggiorna quando si inserisce l'immagine nell'editor dei post, il valore location verrà sovrascritto con il vecchio valore quando si aggiorna il post.

Quindi mi chiedo se è possibile utilizzare invece un valore meta meta nascosto, ad esempio _location?

Spero che questo aiuti.

0

ok prova in un altro modo ...... non sarai facilmente in grado di ottenere il post id mentre sei nel navigatore. Im non sicuro di quello che la posizione è, ma se si desidera salvare le immagini come messaggio meta, io uso questo ............

passi:

1.Creare un nuovo file js + visita http://jsfiddle.net/dheffernan/BB37U/2/ e copia il js lì nel file js. chiamalo miu_script.js o se vuoi cambiarlo devi fare alcune modifiche al codice qui sotto. Salvarlo nella cartella Plugin (cambia percorso qui sotto se si desidera spostare nella sottocartella

  1. inserire nel seguente codice nelle vostre funzioni -. Salverà la posizione dell'immagine come url serializzato e in un campo chiamato "_images" cambia di nuovo se vuoi modificando il codice

  2. Ci possono essere degli errori qui sotto, ho avuto questo in formato Oop quindi fammi sapere se ci sono problemi ... Se ci sono, nota errori php, se no errori php ma funziona con dosaggi, controlla la console in chrome o firefox. Posso eseguire il debug.

nel vostro funzioni PHP

function add_image_meta_box() { 
    add_meta_box(
       'multi_image_upload_meta_box' 
       , __('Upload Multiple Images', 'miu_textdomain') 
       , 'render_meta_box_content' 
       , $post_type 
       , 'advanced' 
       , 'high' 
     ); 
} 

add_action('add_meta_boxes', 'add_image_meta_box'); 




function render_meta_box_content($post) { 

    wp_nonce_field('miu_inner_custom_box', 'miu_inner_custom_box_nonce'); 

    $value = get_post_meta($post->ID, '_images', true); // <-- change field if wanted, there is 1 more below that will need the same name 

    $metabox_content = '<div id="miu_images"></div><input type="button" onClick="addRow()" value="Add Image" class="button" />'; 
    echo $metabox_content; 

    $images = unserialize($value); //<--- when using the images use this!! 

    $script = "<script> 
     itemsCount= 0;"; 
    if (!empty($images)) 
    { 
     foreach ($images as $image) 
     { 
      $script.="addRow('{$image}');"; 
     } 
    } 
    $script .="</script>"; 
    echo $script; 
} 





function save_image($post_id){ 

    if (!isset($_POST['miu_inner_custom_box_nonce'])) 
     return $post_id; 

    $nonce = $_POST['miu_inner_custom_box_nonce']; 

    if (!wp_verify_nonce($nonce, 'miu_inner_custom_box')) 
     return $post_id; 

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) 
     return $post_id; 


    if ('page' == $_POST['post_type']) { 

     if (!current_user_can('edit_page', $post_id)) 
      return $post_id; 
    } else { 

     if (!current_user_can('edit_post', $post_id)) 
      return $post_id; 
    } 

    $posted_images = $_POST['miu_images']; 
    $miu_images = array(); 
    foreach ($posted_images as $image_url) { 
     if(!empty ($image_url)) 
      $miu_images[] = esc_url_raw($image_url); 
    } 


    update_post_meta($post_id, '_images', serialize($miu_images));<--if you changed this above.......make sure they match 
    } 

    add_action('save_post', 'save_image'); 


    function enqueue_scripts($hook){ 
    if ('post.php' != $hook && 'post-edit.php' != $hook && 'post-new.php' != $hook) 
     return; 
    wp_enqueue_script('miu_script', plugin_dir_url(__FILE__) . 'miu_script.js', array('jquery')); //<--this is the path!!! change if wanted (prob a good idea to add to js folder) 
} 
    add_action('admin_enqueue_scripts', 'enqueue_scripts'); 
0

solo una soluzione semplice

function my_add_attachment_location_field($form_fields, $post) { 
    $field_value = get_post_meta($post->ID, 'location', true); 

    $default = get_post_meta($_REQUEST['post_id'] , 'location', true) ? get_post_meta($_REQUEST['post_id'] , 'location', true): "Location Not Yet Set"; 

    $form_fields['location'] = array(
     'value' => $field_value ? $field_value : $default, 
     'label' => __('Location'), 
     'helps' => __('Set a location for this attachment') 
    ); 
    return $form_fields; 
} 
add_filter('attachment_fields_to_edit', 'my_add_attachment_location_field', 10, 2); 

lavorare bene con il mio plug

$ _REQUEST [ 'post_id'] è effettivo wp postale ID e con get_post_meta voi può ottenere la tua posizione di metabox .. :)

0

Non so se sto solo indovinando. puoi usare questa funzione

wp_reset_query(); 
    global $post; 
    $post->ID // retrive the global $post id; 
Problemi correlati