我在媒体编辑页面上添加了一个自定义字段“立即购买”链接,但我无法像其他帖子类型那样保存该数据。添加/编辑/更新媒体/附件后是否会触发其他挂钩?
我正在使用此功能:
function update_attachment_extra_info( $post_id ) {
// code to update data
}
add_action( \'save_post\', \'update_attachment_extra_info\' );
但这个钩子不会被触发。我在媒体编辑页面上添加了一个自定义字段“立即购买”链接,但我无法像其他帖子类型那样保存该数据。添加/编辑/更新媒体/附件后是否会触发其他挂钩?
我正在使用此功能:
function update_attachment_extra_info( $post_id ) {
// code to update data
}
add_action( \'save_post\', \'update_attachment_extra_info\' );
但这个钩子不会被触发。下面的示例添加了一个名为Buy Now的自定义媒体字段。此示例通过ajax将自定义字段的值保存在媒体覆盖屏幕以及媒体编辑屏幕(非ajax)上。
编辑:添加了临时检查和清理。
/**
* Add custom field to media.
*/
add_filter( \'attachment_fields_to_edit\', \'wpse256463_attachment_fields\', 10, 2 );
function wpse256463_attachment_fields( $fields, $post ) {
$meta = get_post_meta( $post->ID, \'buy_now\', true );
$fields[\'buy_now\'] = [
\'label\' => __( \'Buy Now\', \'text-domain\' ),
\'input\' => \'text\',
\'value\' => $meta,
\'show_in_edit\' => true,
\'extra_rows\' => [
\'nonce\' => wp_nonce_field(
\'update_attachment_buy_now\', // Action.
\'nonce_attachment_buy_now\', // Nonce name.
true, // Output referer?
false // Echo?
),
],
];
return $fields;
}
/**
* Update custom field within media overlay (via ajax).
*/
add_action( \'wp_ajax_save-attachment-compat\', \'wpse256463_media_fields\', 0, 1 );
function wpse256463_media_fields() {
$nonce = $_REQUEST[\'nonce_attachment_buy_now\'] ?? false;
// Bail if the nonce check fails.
if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, \'update_attachment_buy_now\' ) ) {
return;
}
// Bail if the post ID is empty.
$post_id = intval( $_POST[\'id\'] );
if ( empty( $post_id ) ) {
return;
}
// Update the post.
$meta = $_POST[\'attachments\'][ $post_id ][\'buy_now\'] ?? \'\';
$meta = wp_kses_post( $meta );
update_post_meta( $post_id, \'buy_now\', $meta );
clean_post_cache( $post_id );
}
/**
* Update media custom field from edit media page (non ajax).
*/
add_action( \'edit_attachment\', \'wpse256463_update_attachment_meta\', 1 );
function wpse256463_update_attachment_meta( $post_id ) {
$nonce = $_REQUEST[\'nonce_attachment_buy_now\'] ?? false;
// Bail if the nonce check fails.
if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, \'update_attachment_buy_now\' ) ) {
return;
}
$buy_now = isset( $_POST[\'attachments\'][ $post_id ][\'buy_now\'] )
? wp_kses_post( $_POST[\'attachments\'][ $post_id ][\'buy_now\'] )
: false;
update_post_meta( $post_id, \'buy_now\', $buy_now );
return;
}
在将例如文件附加到帖子时,如何在事后编辑/删除它们?在帖子编辑器中找不到任何内容。谢谢