0

使用过滤器/挂钩,我将如何用从自定义分类中选择的任何术语替换 wordpress 帖子的标题。

希望所附图片能解释我正在尝试做的事情。

在此处输入图像描述

假设我选择了“Powerchrono” - 我希望将帖子的标题替换为所选术语,并且它是父项。

任何帮助将非常感激。

我显然也希望帖子的网址也得到更新。

4

1 回答 1

2

我不能保证这会直接工作,因为它未经测试。但这应该让你开始:

函数.php

<?php
add_action('save_post', 'update_term_title');
function update_term_title($post_id)
{
    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) 
        return;
    if(!current_user_can('edit_post', $post_id))
        return;

    //Replace 'manufacturer' with whatever your custom taxonomy slug is
    $terms = wp_get_post_terms($post_id, 'manufacturer');

    if(empty($terms))
        return;

    $title = false;
    foreach($terms as $term)
    {
        if($term->parent)
        {
            $parent = get_term($term->parent, 'manufacturer');
            $title = $term->name.' '.$parent->name;
            break;
        }
    }
    /*Default to first selected term name if no children were found*/
    $title = $title ? $title : $terms[0]->name;

    /*We must disable this hook and reenable from within
    if we don't want to get caught in a loop*/
    remove_action('save_post', 'update_term_title');
    $update = array(
        'ID'=>$post_id,
        'post_name'=>sanitize_title_with_dashes($title),
        'post_title'=>$title
    );
    wp_update_post($update);
    add_action('save_post', 'update_term_title');
}
?>
于 2012-10-22T18:16:16.823 回答