php 创建帖子时自动生成分类术语

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 创建帖子时自动生成分类术语相关的知识,希望对你有一定的参考价值。

<?php

/**
 * Auto Gen Project Agency Taxonomy when an agency is created
 * @link https://gist.githubusercontent.com/brenna/7377802/raw/a5092e5b4bd2a094a6534d73e9f2f81f26783744/wp-autopopulate-taxonomy
 * 
 */
function FS__Update_Project_Agency_Terms($post_id) {
  
  // Only update terms if it's the post type we want
  if ( 'agencies' != get_post_type($post_id)) {
    return;
  }
  
  // Don't create or update terms for system generated posts
  if (get_post_status($post_id) == 'auto-draft') {
    return;
  }

  $tax        = 'project_agency';
  $meta_field = 'agency_post_id';
      
  /*
  * Grab the post title and slug to use as the new 
  * or updated term name and slug
  */
  $term_title = get_the_title($post_id);
  $term_slug  = get_post( $post_id )->post_name;
  
  /*
  * Check if a corresponding term already exists by comparing 
  * the post ID to all existing terms `agency_post_id` meta field
  */
  $existing_terms = get_terms($tax, [
    'hide_empty' => false
  ]);
  
  foreach($existing_terms as $term) {
    $agency_id = get_term_meta($term->term_id, $meta_field, true);
    if ($agency_id == $post_id) {
      //term already exists, so update it and be done
      wp_update_term($term->term_id, $tax, [
        'name' => $term_title,
        'slug' => $term_slug
      ]);
      return;
    }
  }
  
  /* 
  * If we didn't find a match above, this is a new post, 
  * so create a new term. If success, then add the term
  * ID as meta field.
  */
  $term = wp_insert_term($term_title, $tax, [
    'slug' => $term_slug
  ]);

  if ( ! is_wp_error( $term ) ) {
    $term_id = isset( $term['term_id'] ) ? $term['term_id'] : 0;
    if ( $term_id ) {
      add_term_meta ($term_id, $meta_field, $post_id);
    }
  }
}
  
add_action('save_post', 'FS__Update_Project_Agency_Terms');

以上是关于php 创建帖子时自动生成分类术语的主要内容,如果未能解决你的问题,请参考以下文章

php 显示每个分类术语存档页面中的所有帖子

WordPress 根据分类术语显示相关帖子

使用 taxonomy-tax_slug.php 模板为所有分类术语创建档案

php 按分类标准获取帖子的主要术语。如果使用Yoast主要术语,请将其返回,否则回退到第一学期。

php 使用show_on_cb根据分配了分类术语的帖子/页面显示/隐藏CMB字段

根据自定义分类术语显示帖子