php - WooCommerce:在保存帖子之前更新字段值
问题描述
我在 WooCommerce 中有一个额外的自定义字段(高级自定义字段)来显示一些产品亮点。这些突出显示在 HTML 中的格式如下:
<li>Supports thousands of apps</li>
<li>1080p maximum display resolution</li>
<li>Supports both 2.4 Ghz and 5 Ghz Wi-Fi networks</li>
<li>Supports iOS</li>
我需要它们的格式如下:
<g:product_highlight>Supports thousands of apps</g:product_highlight>
<g:product_highlight>1080p maximum display resolution</g:product_highlight>
<g:product_highlight>Supports both 2.4 Ghz and 5 Ghz Wi-Fi networks</g:product_highlight>
<g:product_highlight>Supports iOS</g:product_highlight>
基本上我只需要更改标签并将内容保存在第二个元字段中。
我找到了一个文档来更新特定字段的值并在保存帖子时触发操作。
我的片段如下所示:
add_action('acf/save_post', 'my_acf_save_post', 5);
function my_acf_save_post( $post_id ) {
// Get previous values.
$prev_values = get_fields( $post_id );
// Get submitted values.
$values = $_POST['acf'];
// Check if a specific value was updated.
if( isset($_POST['acf']['product_details_usp']) ) {
$field_key = "product_details_usp_google";
$value = "some new string";
update_field( $field_key, $value, $post_id );
}
}
我要更改数据的元字段是product_details_usp
. 我现在想更改该字段中的数据(下一步)并将其保存在product_details_usp_google
.
但它不起作用。没有数据从一个字段传输到另一个字段。我的代码有什么问题吗?
解决方案
我找到了一个基于来自 LoicTheAztec 的答案的解决方案
add_action( 'save_post', 'update_usp_google_shopping' );
function update_usp_google_shopping( $post_id ){
// Only for shop order
if ( 'product' != $_POST[ 'post_type' ] )
return $post_id;
// Checking that is not an autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user’s permissions (for 'shop_manager' and 'administrator' user roles)
if ( ! current_user_can( 'edit_shop_order', $post_id ) && ! current_user_can( 'edit_shop_orders', $post_id ) )
return $post_id;
// Updating custom field data
if( isset( $_POST['acf'] ) ) {
// The new value
$value = 'Test';
// OR Get an Order meta data value ( HERE REPLACE "meta_key" by the correct metakey slug)
// $value = get_post_meta( $post_id, 'meta_key', true ); // (use "true" for a string or "false" for an array)
// Replacing and updating the value
update_post_meta( $post_id, 'product_details_usp_google', $value );
}
}
代码将 Test 值添加到新的自定义字段。
推荐阅读
- twilio - 使用 Angular 将屏幕共享添加到 Twilio Video 应用程序
- git - 将特定的 SVN 分支迁移到 GIT(2018 年迁移的主干)
- cypress - 如何使用柏树中的包含来断言是否存在特定字符串?
- php - PHPSpreadsheet 无法在 Excel 中获取注释
- java - Jetty 11 - HTTP/1.1 到 HTTP/2 升级,handler 怎么写?
- javascript - 在 TypeScript 中的另一个类型别名中传播类型别名
- weka - 在 Weka 中打开 CSV 数据集时,如何将属性转换为“日期”类型?
- python - 如何在networkx中找到几何子图的最近邻?
- c# - 不能在同一帧缝合网格
- tkinter - 如何使 tkinter 小部件全局化