Run a function on all posts

时间:2019-06-13 作者:Wojciech

我有一个函数,我计算标题中的字母,并将其相加_product_meta_title key, 当我添加新产品时,一切正常,但我有500个产品没有此密钥。所以我需要在所有帖子上运行我的函数一次。

function save_post_title_length_meta( $post_id, $post, $update ) {

/*
 * In production code, $slug should be set only once in the plugin,
 * preferably as a class property, rather than in each function that needs it.
 */
$post_type = get_post_type($post_id);

$title = get_post_field( \'post_name\', $post_id );

$title_length = strlen( $title );


// If this isn\'t a \'product\' post, don\'t update it.
if ( "product" != $post_type ) return;

// - Update the post\'s metadata.

if ( $title ) {
    update_post_meta( $post_id, \'_product_title_length\', $title_length );
}}
我正在使用此操作运行我的函数

add_action( \'save_post\', \'save_post_title_length_meta\', 10, 3 );
如何运行它,以便它将影响我现有的所有帖子的wp加载,初始化?关于从哪里开始有什么建议吗?

谢谢

1 个回复
最合适的回答,由SO网友:ChristopherJones 整理而成

这里是一个可以放入函数的代码段,而不是挂接到init或wp\\u load。php或主题文件。我把它放在一个$\\u GET后面,这样当你准备好的时候,你只能打一次。类似于https://domain.com/page/?update_post_meta

// Hide it from the public
if(isset($_GET[\'update_post_meta\'])){

  // Let\'s query all of the product post_type.
  $product_args = array(
    \'post_type\' => \'product\',
    \'posts_per_page\' => -1
  );
  $product_query = new WP_Query($product_args);

  while( $product_query->have_posts()): $product_query->the_post();

    $title_length = strlen($post->post_name);

    // - Update the post\'s metadata.
    if ( $post->post_name ) {
      update_post_meta( $post->ID, \'_product_title_length\', $title_length );
    }

  endwhile; 

}
如果要在尚未编辑的特定帖子上运行此操作,可以更新$product_args 数组中包含日期范围。

希望这有帮助!!

相关推荐

Query posts by Post title

我使用下面的ACF查询生成一个列表,效果很好。然而,现在我想按标准WP“post title”而不是ACF自定义字段“datum”对列表进行排序我该怎么做?// args $args = array( \'posts_per_page\' => 999, \'post_type\' => \'lezing\', \'orderby\' => \'meta_value\', \'order\' => \'ASC\',