【问题标题】:Is there any way to get a WordPress category name from the post title?有没有办法从帖子标题中获取 WordPress 类别名称?
【发布时间】:2014-02-28 01:20:56
【问题描述】:

我将一个博客导入 WordPress,它有 300 多个帖子。我注意到它没有将类别放入 WordPress 帖子中,但它确实导入了所有类别名称。幸运的是,类别名称在帖子名称中(例如,“科学 - 地球是圆的”将是帖子标题,“科学”将是类别)。由于类别都存在,有什么方法可以运行一个脚本来查看帖子标题以查看是否有任何类别与标题中的文本匹配,如果是,请将其设置为类别?

【问题讨论】:

  • 这绝对是可能的。不过,我无法从头顶写下代码。您也可以编写一个 MySQL 插入查询来执行此操作。会有点棘手,但也有可能。对于 mysql 查询,您需要执行“插入选择”
  • 啊,那会很完美。我什至没有考虑过使用 mysql 查询。现在正在努力:p

标签: wordpress wordpress-theming


【解决方案1】:

编辑 2

这是一个修改后的选择查询,它根据词条是否在标题中来匹配词条和帖子:

select p.id, tt.term_taxonomy_id, t.term_id,  t.name, p.post_title
from wp_terms t 
join wp_posts p on INSTR(p.post_title, t.name)
join wp_term_taxonomy tt on tt.term_id = t.term_id 
where p.post_type = 'post'

这是您要使用的插入查询(请注意,如果由于主键约束而插入重复的 object_id 和 term_taxonomy_id 对,此查询将引发错误):

insert into wp_term_relationships (object_id, term_taxonomy_id, term_order)
    select p.id, tt.term_taxonomy_id, 0
    from wp_terms t 
    join wp_posts p on INSTR(p.post_title, t.name)
    join wp_term_taxonomy tt on tt.term_id = t.term_id 
    where p.post_type = 'post'

如果确实遇到主键约束错误,可以使用insert ignore

insert ignore into wp_term_relationships (object_id, term_taxonomy_id, term_order)
    select p.id, tt.term_taxonomy_id, 0
    from wp_terms t 
    join wp_posts p on INSTR(p.post_title, t.name)
    join wp_term_taxonomy tt on tt.term_id = t.term_id 
    where p.post_type = 'post'

编辑 1:

这是一个可能对您有用的查询:

insert into wp_term_relationships (object_id, term_taxonomy_id, term_order)
    select p.id, tt.term_taxonomy_id, 0 
    from wp_posts p 
    join wp_terms t on t.name = substring_index(p.post_title, ' ',  1)
    join wp_term_taxonomy tt on tt.term_id = t.term_id 
    where p.post_type = 'post'

在这里,我假设标题与您的示例类似。您可能需要调整分隔符。

此外,我会自行运行选择查询来测试您要返回的数据,并确保您没有收到重复数据和其他数据。是的,一定要先备份你的数据库。

select p.id, tt.term_taxonomy_id, 0 
from wp_posts p 
join wp_terms t on t.name = substring_index(p.post_title, ' ',  1)
join wp_term_taxonomy tt on tt.term_id = t.term_id 
where p.post_type = 'post'

这里还有一个更好的调试结果选择查询:

select p.id, tt.term_taxonomy_id, t.term_id, substring_index(p.post_title, ' ',  1) 
from wp_posts p 
join wp_terms t on t.name = substring_index(p.post_title, ' ',  1)
join wp_term_taxonomy tt on tt.term_id = t.term_id 
where p.post_type = 'post'

【讨论】:

  • 如果我的标题是“晚餐吃中餐”并且存在“中餐”类别,那么 mysql 查询会将其设置为类别吗?或者它会寻找一个名为“吃”的类别?
  • 是的,我设置的方式是 Eat。您能否提供一些类别可以位于何处的示例?也许我可以提供一个查询
  • 你有多少个类别。如果您没有数百个类别,则可以进行更多硬编码。
  • 是的,基本上每个标题都是“为您的商店观看 {Quick And Easy} 教程”,括号中的单词就是类别,不管有多少单词,如果这有意义的话。每篇文章都以 watch 开头。我有大约 50 个类别。
  • 我明白你的意思。我有另一个查询想法。给我几分钟时间把它写下来。但基本上你可以根据你的类别对标题进行“短语匹配”。
猜你喜欢
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
相关资源
最近更新 更多