首页 > 解决方案 > 从 wordpress 中的内容自动生成标签

问题描述

我的 WordPress 网站内容的每一行都有一些单词,我想要一个代码来自动将内容中的每一行转换为标记(每一行而不是每个单词),假设我的内容是这样的:

Beagle puppy
Costumes
Wales
Dogs

我想要每一行的标签:比格犬小狗、服装、威尔士、狗

我不想使用插件,因为我使用了一些但它需要一个关键字列表来匹配内容。我不想使用任何关键字列表来匹配内容。是否可以将内容中的每一行转换为一个标签?

标签: wordpresstags

解决方案


假设您的意思是您的意思 - 例如,源帖子仅包含要转换的行,这些行将不包含要处理的其他奇数/不适当的字符,等等 - 以下将起作用。如果您需要转换帖子的一部分或以其他方式定义的其他元素,或者将行作为标签附加到当前帖子等,那么您需要清楚地提供这些详细信息。

  1. 将短代码 [convert_post_lines_to_tags] 放在新的输出帖子中。
  2. 保存草稿并预览(很明显,简码还不能运行)
  3. 将函数添加到您的主题 functions.php
  4. 在指示处提供“$source_post_id”。
  5. 重新加载输出帖子
    add_shortcode( 'convert_post_lines_to_tags', 'convert_post_lines_to_tags' ) ;

    function convert_post_lines_to_tags() {

        $source_post_id = '' ; //Provide ID Number of post with lines to be converted

        $i = 0 ;
        $newTags = 'New tags inserted: <br />' ;

        //TIL - PHP requires double quotes to replace escaped characters
        $post_content = str_replace( 
            array( "\r\n", "\r" ), ',', get_post( $source_post_id )->post_content 
        ) ; 

        $post_line_array = explode( ',', $post_content ) ;

        foreach ( $post_line_array as $line_tag ) { 

            $tag = wp_insert_term( $line_tag, 'post_tag' ) ;

            if ( ! is_wp_error( $tag ) ) {

                $i++ ; 
                $newTags .= $i . '. ' . get_term( $tag['term_id'] )->name . '<br />' ;
            } 

        } 

        return $newTags ;

    }

推荐阅读