我尝试添加尽可能少的人工输入的产品。 因此,我正在寻找一种解决方案,以抓住添加的产品图片中的标题标签,然后将其放在保存产品之前或之后的“产品名称”字段中。任何实现此目的的尝试都将失败,因为WordPress“认为”没有标题(因此不会产生任何错误)。至少我认为是这种情况。
查看该字段的屏幕截图
我尝试使用在SO上找到的代码片段,并将其重新设计为可行的解决方案,但我做对了。
这是我想出的代码:
function fcsp_set_title_on_save( $post_id ) {
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
$filemeta = wp_get_attachment_metadata( $post_thumbnail_id, FALSE );
// Set this variable to false initially.
static $updated = false;
// If title has already been set once, bail.
if ( $updated ) {
return;
}
// Since we're updating this post's title, set this
// variable to true to ensure it doesn't happen again.
$updated = true;
$title = $filemeta['image_meta']['title'];
// Update the post's title.
wp_update_post( [
'ID' => $post_id,
'post_title' => $title,
] );
}
add_action( 'save_post', 'fcsp_set_title_on_save' );
任何想法如何实现这一目标?
答案 0 :(得分:0)
如果您使用的是woocommerce,请将此代码放在function.php中(我认为,而不是自定义帖子类型)
if(class_exists('WC_Admin_Meta_Boxes')) {
class wcsave extends WC_Admin_Meta_Boxes {
public function __construct() {
add_action( 'save_post', array( $this, 'save_meta_boxes' ), 1, 2 );
add_action( 'woocommerce_process_product_meta', 'WC_Meta_Box_Product_Data::save', 10, 2 );
}
public function save_meta_boxes( $post_id, $post ) {
//$_POST enter your post data here, this will help to control the post request from product woocommerce
//if product is updating don't execute image title code section
if(!empty($post->post_title)) {
return;
}
//if new product is being added.
if(!empty($_POST['post_ID']) && $post_id == $_POST['post_ID']) {
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
$attachment_data = get_post( $post_thumbnail_id,OBJECT );
$title = count($attachment_data) > 0 ? $attachment_data->post_title : "PRODUCT-".$post_id;
remove_action( 'save_post', array( $this, 'save_meta_boxes' ) , 1, 2 );
wp_update_post( [
'ID' => $post_id,
'post_title' => $title,
'post_status' => $post->post_status
] );
// re-hook this function
add_action( 'save_post', array( $this, 'save_meta_boxes' ) , 1, 2 );
}
}
}
new wcsave();
}
但是请注意,由于我已经测试过,您至少还需要其他一些信息以及要上传的产品图片(例如产品说明),剩下的它将图片名称保存为产品标题。
谢谢