且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-30 15:09:04

首先,您必须为wordpress构建一个插件,该插件可以链接到已发布的帖子或更新的帖子,您可以参考

first you must to build an plugin for wordpress that hook into the published post or an update post you can refer into this
after that you can add tag whenever they find hastag on post_content and the code goes like this

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 );

如果您使用边境哨所,也许您可​​以使用此

if you use frontier post maybe you can use this

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优先级的参数 并将帖子中的所有hastag更改为url,您可以使用如下代码

you can change the parameter of add_action priority refer to this and to change all of the hastag in the post into url you can use the code like this

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' ); 

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

so if we combine all of the code into one plugin we can use it like this

<?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' );