如何对Word帖子内容进行分类

时间:2018-01-26 作者:Donovan

我有个问题!我有我的网站和wordpress。我只有一个类别,我想有5个类别。问题是我已经发表了7000多篇文章。我怎样才能使用一个单词的内容和一个新的类别的关系。

Examplecat(Post\\u内容的单词)--->cat(新类别)

请问,“SQL查询”如何?谢谢

2 个回复
SO网友:WebElaine

我个人觉得使用内置的WP函数比直接运行MySQL查询更容易,所以这里有一个选项:

<?php
global $wpdb;
// replace \'yoursearchword\' with whatever you\'re looking for.
// the two % symbols are to find the word no matter what comes before or after.
$query = "SELECT * FROM wp_posts WHERE post_content LIKE %yoursearchword%";
$posts = $wpdb->get_results($query);
foreach($posts as $post) {
    // replace with the desired category ID number.
    wp_set_post_categories($post->ID, array(1));
}
?>
出于SEO的目的,最好只为每个帖子分配一个类别,这就是此代码所实现的。每次运行它时,如果找到搜索词,所有类别都将被指定的类别覆盖。如果您希望帖子能够分为多个类别,请添加true 该函数将附加(添加其他)类别,而不是覆盖。

wp_set_post_categories($post->ID, array(1), true);

SO网友:Vlad Olaru

我不建议您在暴露于各种数据损坏时使用直接SQL方法。

最好的方法是创建一个只运行一次的PHP函数并执行该任务。您可能会遇到一些超时问题,但可以通过临时设置非常高的PHP超时值来克服这些问题。

首先,您应该确保在WP admin中正确创建了新类别。然后在数组中记住它们的ID。

为了让您开始,这是我将使用的功能,连接到WP admin dashboard中,因此它只在您转到该页面时启动。

function wp1234_attach_posts_to_new_categories() {
    $categories_mapping = array(
        \'targetword1\' => \'101\', //this is a category ID
        \'targetword2\' => \'102\', //this is another category ID
        \'targetword3\' => \'103\', //this is yet another category ID
    );

    // Grab all the posts and cycle through them
    $args = array(
        \'post_type\' => \'post\',
        \'posts_per_page\' => -1,
        \'post_status\' => \'publish\',
        \'suppress_filters\' => true,
        \'ignore_sticky_posts\' => true,
        \'no_found_rows\' => true,
        \'cache_results\' => false, // there is no need to cache this
    );
    $new_query = new WP_Query();
    foreach ( $new_query->query( $args ) as $post ) {
        if ( ! empty( $post->post_content ) ) {
            foreach ( $categories_mapping as $word => $category_id ) {
                if ( false !== strpos( $post->post_content, $word ) ) {
                    // We have found the word in the content
                    // Attach the post to the category, by appending to existing categories - the last parameter
                    wp_set_post_categories( $post->ID, array( absint( $category_id ) ), true );

                    // We will stop at the first found word
                    break;
                }
            }
        }
    }

    // Leave a sign that we have done something
    print( PHP_EOL . \'### ATTACHED POSTS TO CATEGORIES ###\' . PHP_EOL );
}
// This action gets run only on the WP admin dashboard page
add_action( \'wp_dashboard_setup\', \'wp1234_attach_posts_to_new_categories\' );
完成后,移除add_action 至少这样你就不会重击你的网站了。

如果有帮助,请告诉我。

结束