首页 > 解决方案 > 如何更新网站上所有产品的自定义元数据(从 Dokan 添加供应商名称)?

问题描述

网站上有 Dokan 插件。现在我需要将 vendor_name 添加到每个产品中,例如自定义元字段。我试图做这样的事情:

$args = array(
   'post_type' => 'product',
   'posts_per_page' => -1
);

 $products = new WP_Query( $args );
    if ( $products->have_posts() ):
       while ( $products->have_posts() ):
          
           $vendor_id = get_post_field( 'post_author', get_the_id() );
           $vendor = new WP_User($vendor_id);
           $store_info  = dokan_get_store_info( $vendor_id );
           $store_name  = $store_info['store_name'];   

           $productID = $product->get_id();
           update_post_meta( $productID, 'vendor_name', $store_name );
           $products->the_post();
       endwhile;
  endif;

因此,我想更新所有产品的元数据。但是当我将此代码添加到functions.php 时,该站点只是停止加载,或者更确切地说它加载了,但速度很慢。没有错误。虽然我可能错了。也许问题不在于代码,而在于网站上有超过 18,000 种产品?或者也许还有另一种方法可以实现我需要的目标。请帮我弄清楚。

标签: wordpresswoocommerce

解决方案


您可以尝试在 wordpress 操作上运行此代码并检查一些查询参数,使其不会在正常视图中加载。这是一次性过程,这意味着您可以自己运行此脚本。

add_action( 'wp', function(){
    if( isset( $_REQUEST['add_vendor_meta'] ) && $_REQUEST['add_vendor_meta'] == 'true' ){
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1
        );

        $products = new WP_Query( $args );
        if ( $products->have_posts() ):
            while ( $products->have_posts() ):
                $products->the_post();
                $vendor_id = get_post_field( 'post_author', get_the_id() );
                $vendor = new WP_User($vendor_id);
                $store_info  = dokan_get_store_info( $vendor_id );
                $store_name  = $store_info['store_name'];   

                $productID = $product->get_id();
                update_post_meta( $productID, 'vendor_name', $store_name );

            endwhile;
            wp_reset_postdata();
        endif;
    }
} );

并且还要确保在 while 循环结束后添加 wp_reset_postdata() 这有助于重置自定义查询并且不会影响主查询。


推荐阅读