基于自定义字段值指定分类

时间:2017-08-06 作者:Ian S

我有一个自定义的帖子类型“蔬菜”

我有一系列用于一年中每个月的自定义字段作为复选框

我有一个自定义分类“季节”,我想根据在自定义字段中选中的框来分配它

夏季(如有)六月七月八月

秋季(如有)9月10月11月

冬季(如有)12月1月2月

春季(如有)3月4月5月

因此,可根据检查的自定义字段,将蔬菜分配为所有季节或单个季节

add_action( \'save_post\', \'assign_cat_to\', 10, 1 );

function assign_cat_to( $post_id ) {
if ( \'seasonal-product\' !== get_post_type( $post_id ) ) {
    return;
}

$term_slugs = array();

foreach ( $_POST as $field => $value ) {
    if ( 0 === strpos( $field, \'wpcf-available-in-\' ) && \'1\' === $value ) {
        $term_slugs[] = str_replace( \'wpcf-available-in-\', \'\', $field );
    }
}

if ( empty( $term_slugs ) ) {
    return;
}

$term_ids = array();

foreach ( $term_slugs as $term_slug ) {
    $term       = get_term_by( \'slug\', $term_slug, \'season\' );
    $term_ids[] = $term->term_id;
}

wp_set_object_terms( $post_id, $term_ids, \'season\' );
}
我根据实际字段和术语进行了一些更新,但我仍然不知道如何为术语指定“春、夏、秋、冬”。

或者,我可以将季节名称“春、夏、秋、冬”存储到数据库中,而不是“1”,这样会更容易写入术语slug吗?

2 个回复
SO网友:Chris Cox
/**
 * Programmatically assign taxonomy term by custom fields
 * 
 * @param int $post_id
 */
function rd_assign_taxonomies($post_id) {

    if (get_post_type($post_id) == \'vegetables\') {
        $terms = array();

        // Here we\'d check to see if the post has the specific fields, and if so add the IDs or slugs of the taxonomy terms to the $terms array
        // The exact details will depend on how the checkboxes were implemented, for example as native postmeta or ACF fields

        wp_set_object_terms( $post_id, $terms, \'seasons\', false );
    }
}

add_action(\'save_post\', \'rd_assign_taxonomies\');
SO网友:ClemC

通过编程将术语和分类法分配给您的自定义帖子怎么样wp_set_object_terms ?

add_action( \'save_post\', \'assign_cat_to\', 10, 1 );

function assign_cat_to( $post_id ) {
    if ( \'vegetables\' !== get_post_type( $post_id ) ) {
        return;
    }

    $term_slugs = array();

    foreach ( $_POST as $field => $value ) {
        if ( 0 === strpos( $field, \'available_in_\' ) && \'1\' === $value ) {
            $term_slugs[] = str_replace( \'available_in_\', \'\', $field );
        }
    }

    if ( empty( $term_slugs ) ) {
        return;
    }

    $term_ids = array();

    foreach ( $term_slugs as $term_slug ) {
        $term       = get_term_by( \'slug\', $term_slug, \'seasons\' );
        $term_ids[] = $term->term_id;
    }

    wp_set_object_terms( $post_id, $term_ids, \'seasons\' );
}

结束

相关推荐

URL rewriting taxonomy term

我正在为接下来的几个小时寻找解决方案,我不知道这是否适用。我有1个Custom Taxonomy \"Years\" 对于Post Type \"Post (default)\". 分类法有两个术语:\"2014\" 和\"2015\".我已经从类别中选择了一些帖子\"news\" 使用两个不同的分类术语。这显示了两个分类术语的所有帖子:http://website.com/category/news/ 当我想显示类别中的帖子时\"news\" 使用分类术语\"2014\" 我使用以下方法:ht