我正在寻找一个MySQL查询,该查询将查找具有自定义字段“meta\\u key\\u I\\u want\\u to\\u find”的所有帖子,然后如果检测到自定义字段,则向该帖子添加一个类别。类别已经创建,所以我只需要找到带有该Meta\\u键的所有帖子,然后将类别添加到其中。
我想的是这样的:
<?php
$username="MY_MYSQL_USERNAME";
$password="MY_MYSQL_PASSWORD";
$hostname="MY_DATABASE_HOSTNAME"; //Your Database hostname usually
$database="MY_DATABASE_NAME";
$my_text = "meta_key_I_want_to_find"; // What I\'m searching for
$my_category = \'8\'; // The category to add it to
// Connect to MySQL and the database and verify:
mysql_connect($hostname,$username,$password) or die(mysql_error());
echo "<p>Connected to MySQL.";
mysql_select_db($database) or die(mysql_error());
echo "<br />Connected to " . $database . "</p>";
// Verify what we\'re looking for, for troubleshooting:
echo "<p><b>Looking for " . $my_text . "</b></p>";
// Get the ID field (which is WordPress\'s post
// number) from any posts that have your text:
$query = "SELECT ID FROM wp_posts WHERE post_content LIKE \'%$my_text%\'";
// Take those results and go through them:
$result = mysql_query($query) or die(mysql_error());
// While there are results...
while($row = mysql_fetch_array($result))
{
// Verify what we\'re doing -- changing post
// number such-and-such...
$thisPostHasIt = $row[\'ID\'];
echo "<p>Row " . $row[\'ID\'] . " contains it, so...<br />";
// In the wp_term_relationships table,
// update the category number ("term_taxonomy_id")
// with the category number you specified -- but only
// in one of the "result" rows.
// We look for "object_id" to equal one of those
// rows. (The object_id field refers to the WordPress
// post number, just as the ID field did. Why two
// different names? Who knows?)
mysql_query("UPDATE wp_term_relationships SET term_taxonomy_id=\'$my_category\' WHERE object_id = \'$thisPostHasIt\'");
// And tell us about it:
echo "Changing post number " . $thisPostHasIt . " to category number ". $my_category . "</p>";
}
echo "<p><b>All done!</b></p>";
//found on http://wordpress.org/support/topic/mysql-query-to-search-posts-and-change-categories
?>
。。。我只需要能够找到具有特定meta\\u键的所有帖子,然后向其中添加一个类别,而不是查找字符串并替换它。非常感谢您的任何建议!