【问题标题】:Copy post meta custom field to other custom field将帖子元自定义字段复制到其他自定义字段
【发布时间】:2018-09-05 13:01:26
【问题描述】:

如何在一篇文章中将值从帖子元复制到其他归档元? 例如:

copy value from custom_field_1 (if exist) or custom_field_2 (if exist) to custom_ field_3

field1 或 field2 中只有一个具有值,而字段 3 始终具有从 fiel1 或 field2 复制的 e 值。

所有自定义字段都在一个帖子(woo 产品)元中。

【问题讨论】:

    标签: php wordpress methods woocommerce custom-fields


    【解决方案1】:

    您可以通过两种方式做到这一点:

    1) 旧方式来自$product_id 动态产品ID(或订单ID)

    if( ( $value = get_post_meta( $product_id, 'custom_field_1', true ) || $value = get_post_meta( $product_id, 'custom_field_2', true ) ) && ! get_post_meta( $product_id, 'custom_field_3', true ) ){
        update_post_meta( $product_id, 'custom_field_3', $value );
    }
    

    2) 新方式 (since WooCommerce 3, CRUD methods) from $product, the WC_Product Object (or the from @ 987654327@WC_Order对象)

    if( ( $value = $product->get_meta( 'custom_field_1' ) || $value = $product->get_meta( 'custom_field_2') ) && ! $product->get_meta( 'custom_field_3' ) ){
        $product->update_meta_data( 'custom_field_3', $value );
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。两种方式都有效。

    【讨论】:

    • 非常感谢 LoicTheAztec。只是我复制functions.php中的第二个代码还是需要修改?
    • @Mani 你不能直接在functions.php中复制它。此代码需要放置在挂钩函数或模板中,因为您需要获取动态 $product Id 或 order Id(或动态 Product 或 Order 对象......如果此答案正在回答您的问题,请不要忘记@ 987654322@答案,谢谢。
    • 非常感谢 LoicTheAztec。你能给我一个适用于 woocommerce 商店所有产品的完整功能吗?谢谢
    • @Mani 这取决于你想在哪里显示它们以及如何...... meta_keys 是什么?您究竟想在哪里显示值?它们需要以什么 html 结构显示?
    • @LoicTheAztec 嗨。每个订单都有“delivery_time”或“time-to_send”元字段。并且其中一个总是有价值的。我需要一个自定义函数来检测“time_to_sent_”字段是否有值,将该值复制到每个 woocommerce 订单的订单自定义元数据中的“delivery_time”字段。
    猜你喜欢
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2016-06-25
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多