惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
美团技术团队
WordPress大学
WordPress大学
酷 壳 – CoolShell
酷 壳 – CoolShell
G
Google Developers Blog
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
J
Java Code Geeks
Martin Fowler
Martin Fowler
M
MIT News - Artificial intelligence
IT之家
IT之家
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
Google DeepMind News
Google DeepMind News
小众软件
小众软件
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
腾讯CDC
B
Blog

Jeremy Carlson

Excluding a directory from WordPress – Jeremy Carlson Reorganize your WordPress files to make your life easier – Jeremy Carlson Pay attention. – Jeremy Carlson A SASS Mixin to accommodate @font-face fallbacks – Jeremy Carlson Can I use type in an image? – Jeremy Carlson Creating a site structure for the future – Jeremy Carlson Running a Successful Business with the Add-On Model – Jeremy Carlson What I Learned About WordPress Development by Interviewing 15 of the Best WordPress Developers – Jeremy Carlson Quirky Client Communication and How to Fix It – Jeremy Carlson
Convert Post Metadata into Tags (Terms) – Jeremy Carlson
Jeremy · 2017-10-13 · via Jeremy Carlson

There are times when you need to re-organize how your WordPress post data is saved. In my case, I recently wanted to change some metadata into an actual term relationship for a number of posts. This snippet took all of my `vendor` posts, which had post metadata `vendor_markets` and `vendor_category`, and properly categorized them.

Now, some notes:

  1. This is definitely rough code, and you’d need to refine for your own purposes.
  2. This should be run on a specific template page just once.
  3. BACKUP before you use something like this!
  4. I’d recommend commenting out parts like `wp_set_post_terms` until you confirm it’s working the way you want it to.

All righty then…

/*
 * Convert all vendors' post metadata for markets and categories
 * to taxonomic relationship
 */
$query = new WP_Query(
  array( 
    'post_type' => array('vendor'),
    'posts_per_page' => -1, // get all vendors
    'orderby'   => 'meta_value_num',
    'order'			=> 'DESC',
  ) 
);


if ( $query->have_posts() ) {
  while( $query->have_posts() ) {
    $query->the_post();

    $id = get_the_ID();
    $markets = get_post_meta( $id, 'vendor_markets', true );
    $category = get_post_meta( $id, 'vendor_category', true );

    echo $id . ' ' . get_the_title() . ' ' . implode('|', $markets) . ' ' . implode('|', $category);
  
    if( ! empty( $markets ) ) {
      $markets = array_map( 'intval', $markets );
      wp_set_post_terms( $id, $markets, 'market' );
    }

    if( ! empty( $category ) ) {
      $category = array_map( 'intval', $category );
      wp_set_post_terms( $id, $category, 'offering' );
    }
    echo "\n";
  }
}