【问题标题】:Using update_post_meta when creating a subscription product in WooCommerce在 WooCommerce 中创建订阅产品时使用 update_post_meta
【发布时间】:2020-06-16 20:35:45
【问题描述】:

我目前正在创建一个从他们的车牌收集数据的插件。一切正常。帖子被创建,我收到了创建帖子的 ID 等等。但是在我的函数的最后..我想更新帖子元这样做:

update_post_meta($product_id, '_regular_price', '0');
update_post_meta($product_id, '_subscription_period_interval', '1');
update_post_meta($product_id, '_subscription_period', 'week');

但是什么也没发生。我尝试再次运行该函数,将代码放在其他地方,并且我在代码中尝试了多个位置。甚至尝试为这 3 行本身创建一个全新的功能。还是没有运气。

我尝试从我刚刚创建的帖子中返回帖子元数据。查看返回的数据,我看到我的 post_meta 已设置,但是当从 WordPress 帖子类型存档访问帖子时,帖子元被重置/忽略。

这就是我所面临的:

如您所见,正在设置帖子元数据,但在查看我的存档时...未设置。 我什至尝试使用 sleep(3) 来确保帖子是在 update_post_meta 之前创建的。没有运气。

关于如何解决此问题的任何想法或提示?

我想通过将这 3 行添加到示例中来添加它:functions.php,然后硬编码 id 就可以了。所以简短的版本是,在创建帖子时,即使 id 设置正确,这 3 行也不做任何事情。所以在创建帖子等时它必须是一些东西......

编辑

您要求查看 product_id 的设置位置:

 $post_data = array(
        'post_author'   => $author,
        'post_name'     => $postname,
        'post_title'    => $data['title'],
        'post_content'  => $data['content'],
        'post_excerpt'  => $data['excerpt'],
        'post_status'   => 'draft',
        'ping_status'   => 'closed',
        'post_type'     => 'product',
    );

    // Creating the product (post data)
    $product_id = wp_insert_post( $post_data );

WordPress #WooCommerce

【问题讨论】:

  • 请分享整个函数,这样人们就可以看到你从哪里得到$product_id,以及你是如何触发整个函数的。
  • @HowardE 完成。不是整个功能,而是我如何检索 ID。我还可以确认正在设置 ID。
  • 这些字段是通过 ACF 插件添加的吗?
  • @CBroe 否。我遇到问题的 3 行不是 acf 字段。但是,我在同一个文件中的其他地方确实有 acf 字段。
  • 您确定 product_id 获取的是整数而不是 0 或 wp_error?

标签: php wordpress woocommerce product woocommerce-subscriptions


【解决方案1】:

首先,您似乎正在尝试创建一个简单的订阅产品......所以您忘记设置产品类型subscription 以及与产品订阅价格相关的一些其他内容。:

$post_data = array(
    'post_author'   => $author,
    'post_name'     => $postname,
    'post_title'    => $data['title'],
    'post_content'  => $data['content'],
    'post_excerpt'  => $data['excerpt'],
    'post_status'   => 'draft',
    'ping_status'   => 'closed',
    'post_type'     => 'product',
);


// Creating the product (from post data)
$product_id = wp_insert_post( $post_data );

// Set the product type   <====   <====   <====   Missing
wp_set_object_terms( $product_id, 'subscription', 'product_type' ); //  <==  Missing

$product_price = 0;

update_post_meta($product_id, '_regular_price', $product_price);
update_post_meta($product_id, '_price', $product_price); //  <==   <==   <==  Missing
update_post_meta($product_id, '_subscription_price', $product_price); // <==  Missing 

update_post_meta($product_id, '_subscription_period', 'week');
update_post_meta($product_id, '_subscription_period_interval', '1');

现在应该可以更好地工作了。

【讨论】:

    猜你喜欢
    • 2017-06-18
    • 2019-10-14
    • 1970-01-01
    • 2019-12-09
    • 2014-06-20
    • 2021-01-25
    • 2017-12-03
    • 2019-07-29
    • 2017-03-11
    相关资源
    最近更新 更多