繁体   English   中英

为 WordPress 内容中的标签添加 WordPress 分类标签

[英]Add A WordPress Taxonomy Tag for Hashtags in WordPress Content

WordPress 分类法有助于 SEO,它们使包含大量帖子的网站易于排序。 每当保存帖子时,我们如何自动将任何以“#”开头的单词转换为 WordPress 标签。

我的网站有 100 多个帖子,作者不喜欢放置标签。 使用标签系统可以确保他们喜欢放置标签。

对于每个 WordPress 保存后,我想查找以“#”开头的单词,例如“An #Apple A Day”并将#Apple 转换为默认的 WordPress 标签。 另外,我想对所有帖子类型都这样做。

我在评论中找到了一个很好的解释,但是因为我不擅长 PHP,所以我不能用 WordPress 帖子的内容来做。

通过在带有井号标签的评论中写入 wordpress 帖子,添加分类标签

我试图用 wp_insert_post_data 来做,但它不起作用。

首先,您必须为 wordpress 构建一个插件,该插件与已发布的帖子或更新帖子挂钩,您可以参考这里
之后,您可以在他们在 post_content 上找到 hastag 时添加标签,代码如下所示

function post_published_notification( $ID, $post ) {
    $content = $post->post_content;
    preg_match_all('/( #\w+)/', $content, $matches, PREG_PATTERN_ORDER);
    if(isset($matches[1])){
        foreach($matches[1] as $matchKey){
            wp_set_post_tags( $ID, trim($matchKey), true);
        }
    }
}
add_action( 'publish_post', 'post_published_notification', 10, 2 );

如果你使用边境邮政也许你可以使用这个

function post_published_from_frontier($my_post){
    $content = $my_post->post_content;
    $ID = $my_post->ID;
    preg_match_all('/( #\w+)/', $content, $matches, PREG_PATTERN_ORDER);
    if(isset($matches[1])){
        foreach($matches[1] as $matchKey){
            wp_set_post_tags( $ID, trim($matchKey), true);
        }
    }
}
add_action('frontier_post_post_save', post_published_from_frontier, 10 ,2 );

您可以更改 add_action 优先级的参数参考this并将帖子中的所有hastag更改为url 您可以使用这样的代码

function old_wp_content( $content ) { 
    $content =  preg_replace('/ #([A-Za-z0-9\/\.]*)/', ' <a target=\"_blank\" href=\"https://milyin.com/hashtag/$1\">$1</a>', $content);
    return $content;
}
add_filter( 'the_content', 'old_wp_content' ); 

因此,如果我们将所有代码合并到一个插件中,我们可以像这样使用它

<?php
function post_published_notification( $ID, $post ) {
    $content = $post->post_content;
    preg_match_all('/( #\w+)/', $content, $matches, PREG_PATTERN_ORDER);
    if(isset($matches[1])){
        foreach($matches[1] as $matchKey){
            wp_set_post_tags( $ID, trim($matchKey), true);
        }
    }
}
add_action( 'publish_post', 'post_published_notification', 10, 2 );

function post_published_from_frontier($my_post){
    $content = $my_post->post_content;
    $ID = $my_post->ID;
    preg_match_all('/( #\w+)/', $content, $matches, PREG_PATTERN_ORDER);
    if(isset($matches[1])){
        foreach($matches[1] as $matchKey){
            wp_set_post_tags( $ID, trim($matchKey), true);
        }
    }
}
add_action('frontier_post_post_save', post_published_from_frontier, 10 ,2 );

function old_wp_content( $content ) { 
    $content =  preg_replace('/ #([A-Za-z0-9\/\.]*)/', ' <a target=\"_blank\" href=\"https://milyin.com/hashtag/$1\">$1</a>', $content);
    return $content;
}
add_filter( 'the_content', 'old_wp_content' ); 

我的主题和页面 css 无法正常工作,并且颜色 ID 的主题标签“#”例如颜色:#85776 被视为主题标签。 如何解决?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM