web-dev-qa-db-fra.com

Ajouter automatiquement une légende d'image avec les valeurs d'un champ post-parent?

j'ai un champ déroulant personnalisé sur le post et je voudrais obtenir la valeur de ce champ personnalisé et l'insérer sur chaque champ de légende d'image téléchargés sur le post actuel.

Je cherchais un moyen de le faire et en ai trouvé quelques exemples, mais pas un seul travail. Ce matin, j'ai trouvé un filtre Wordpress appelé attachment_fields_to_save. À ma grande surprise, le codex était un exemple de ce que je cherchais presque, mais je ne travaillais pas.

C'est le code

function insert_custom_default_caption($post, $attachment) {
if ( substr($post['post_mime_type'], 0, 5) == 'image' ) {
    if ( strlen(trim($post['post_title'])) == 0 ) {
        $post['post_title'] = preg_replace('/\.\w+$/', '', basename($post['guid']));
        $post['errors']['post_title']['errors'][] = __('Empty Title filled from filename.');
    }

    // captions are saved as the post_excerpt, so we check for it before overwriting
    // if no captions were provided by the user, we fill it with our default
    if ( strlen(trim($post['post_excerpt'])) == 0 ) {
        $post['post_excerpt'] = 'default caption';
    }
}

return $post . $attachment;
}

add_filter('attachment_fields_to_save', 'insert_custom_default_caption', 10, 2);

Quelqu'un peut-il m'aider à voir ce qui ne va pas avec ce code?

1
christianpv

Dans le filtre, vous devrez trouver le post-parent de $post, obtenir la valeur du champ personnalisé de post-parent, puis ajouter cette valeur à $post['post_excerpt'] (où la légende est stockée):

add_filter('attachment_fields_to_save', 'wpse_insert_custom_caption', 10, 2);
function insert_custom_default_caption($post, $attachment) {

    //Check if the $post is attached to a parent post
    if( $post->post_parent ) {
        //Custom field of the attachment's parent post
        $custom_caption = get_post_meta( $post->post_parent, 'parent_custom_field', true );

        //captions are saved as the post_excerpt
        if ( !empty $custom_caption ) ) {
            $previous_caption = $post['post_excerpt'];
            $post['post_excerpt'] = $previous_caption.$custom_caption;
        }

    }

    return $post;
}
2
cybmeta