php - wordpress - 在保存后自动插入术语 slug 作为标签

标签 php wordpress

更新,代码现在可以工作了。

我有以下代码,但显然它没有按预期工作。它应该只从分类法 TAXONOMY_NAME 中获取自定义帖子类型 CUSTOM_POST_TYPE 的术语并添加为标签。


add_action('save_post','add_tags_auto');
function add_tags_auto($id) {

    $terms = get_the_terms( $post->id, 'TAXONOMY_NAME' ); // get an array of all the terms as objects.
    $add_tags = array();

    foreach( $terms as $term ) {
        $add_tags[] = $term->slug; // save the slugs in an array
    }
    $temp = array();
    $tags = get_the_tags($id);
    if ($tags) {
    foreach ($tags as $tag)
        $temp[] = $tag->name;
    }
    $tags = $temp;

    $post = get_post($id);

    if ($post->post_type != 'CUSTOM_POST_TYPE')
        return false;

    foreach ($add_tags as $t)
        if (!in_array($t,$tags))
            wp_add_post_tags($id,$add_tags);
}

最佳答案

这是未经测试的,但它应该是朝着正确方向迈出的一步,我已经做了一些调整并发表评论:

<?php
add_action('save_post','add_tags_auto');
function add_tags_auto($post_id) {
    $post = get_post($post_id);

    // bail if this isn't a type of post we want to auto-tag
    if($post->post_type != 'CUSTOM_POST_TYPE')
        return false;

    // --------------------------------------------------
    // get the list of tag names from the post
    // --------------------------------------------------
    $tagNames = array();
    $tags     = get_the_tags($post_id);

    foreach($tags as $tag)
        $tagNames[] = $tag->name;

    // --------------------------------------------------
    // get the list slugs from terms in the post, any
    // slugs that aren't alredy a tag, will be marked for
    // addition automatically
    // --------------------------------------------------
    $tagsToAdd = array();
    foreach(get_the_terms($post_id, 'TAXONOMY_NAME') as $term)
        if(!in_array($term->slug, $tagNames))
            $tagsToAdd[] = $term->slug;

    // if we have some new tags to add, let's do that now
    if(!empty($tagsToAdd))
        wp_add_post_tags($post_id, implode(',', $tagsToAdd));
}

我在您的代码中看到的一个潜在问题是设置 $post after 尝试使用它。我很确定在函数的第一行调用 $post->id 时,PHP 会发出警告,指出 $post 不是对象。因此,我将对 get_post 的调用移到了函数的顶部。

我添加的一个小调整是如果帖子不是所需的类型则提前返回。最好尽快执行此操作,而不是花时间进行可能会被进一步检查丢弃的计算。

我还合并了 foreach 循环的数量并重命名了一些变量以进行说明。我在您的原始代码中看到的唯一可能未按预期工作的另一件事是对 wp_add_post_tags 的调用,it's documented以逗号分隔的字符串作为第二个参数,而不是数组。

关于php - wordpress - 在保存后自动插入术语 slug 作为标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8437382/

相关文章:

wordpress - 完整的 Magento/Wordpress 集成

javascript - 更改文本区域值不起作用

php - 找不到类 'Db'

javascript - 将 GoogleGraph 保存为矢量图像

php - 一次从多个 url 获取 XML 数据失败

jquery - 使用 Data Cycle FX 的 jQuery 旋转木马菜单内的中心事件 li 元素

php - 从州代码获取发货州的名称,或者如果用户在 WooCommerce 中键入该名称

mysql - 按缺少值过滤结果

php - 递归php/mysql函数问题

php - 避免重复值并在 mysql 数据库中的同一行中获取其他数据集