我在帖子上有一个自定义下拉字段,我想从该自定义字段中获取值,并将其插入上传到当前帖子的每个图像标题字段中。
我一直在寻找一种方法来做到这一点,并找到了几个例子,但没有一个工作。今天早上我发现了一个Wordpress过滤器,名为attachment\\u fields\\u to\\u save。令我惊讶的是,在抄本上有一个例子,几乎和我在寻找的东西一样,但我没有工作。
这是代码
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);
有人能帮我看看那个代码有什么问题吗?
SO网友:cybmeta
在过滤器中,您需要找到$post
, 获取父帖子的自定义字段的值,然后将该值添加到$post[\'post_excerpt\']
(存储标题的位置):
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;
}