wordpress - 如何更新网站上所有产品的自定义元数据(从 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 种产品?或者也许还有另一种方法可以实现我需要的目标。请帮我弄清楚。
解决方案
您可以尝试在 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() 这有助于重置自定义查询并且不会影响主查询。
推荐阅读
- android - Toast 在 Android API 28 中显示不到一秒钟
- android - 如何将 GitHub 存储库下载到我当前正在处理的 Andriod Studio 项目中?
- python - 使用 pandas 查找具有给定范围的列的长度
- sql - SQL 帮助 - 在当前记录时间戳之前查找顺序
- image - 如何在 react-native 中成功缓存最常用的数据(图像和文本)
- r - 在闪亮的 R 中显示来自网络的图像
- python - OSError: [Errno 1] 不允许操作
- go - Go中使用递归和并发的第N个斐波那契数
- python - 在使用 keras Lambda 时,如何处理“TypeError: Object arrays are not supported”?
- python - Python 给了我索引号而不是列表中的输入。