【问题标题】:How to remove width and height attributes from multiple posts in Wordpress (MySQL)如何从 Wordpress (MySQL) 中的多个帖子中删除宽度和高度属性
【发布时间】:2023-04-05 23:06:01
【问题描述】:

所以我有数以千计的 Wordpress 帖子,其中包含我想要删除的宽度和高度属性。例如:

img class="aligncenter size-full wp-image-21011999" title="sometitle" 
alt="somealt" src="http://mysite.com/blabla/somefile.jpg" width="xxx" height="xxx"

正如我提到的,我想删除 width="xxx" height="xxx" 并且我想直接从 MySQL 中删除它们,不想使用任何 PHP 函数或类似函数。

有没有可以通过 PhpMyadmin 运行的查询?

是否有任何正则表达式可以用于每个帖子不同的 xxx。

谢谢!

【问题讨论】:

  • 你不能从这个文件中手动删除它们吗?只需转到这个你有宽度和高度的文件并删除它们
  • 不,因为有很多帖子,所以我需要花几天时间。
  • 我的意思是它只有一个文件生成这些图像,
  • 宽高总是3位数吗?
  • @goodmood 不幸的是,这不是 Wordpress 的运作方式。我可以删除未来帖子的高度和宽度属性,但我需要一种方法将它们从旧帖子中删除。

标签: mysql regex wordpress phpmyadmin


【解决方案1】:

您可以编写一个小的 PHP 脚本(当然在 WordPress 之外),使用 Regex 可以轻松完成此任务。

<?php

$host = "hostname";
$user = "username";
$pass = "password";
$db   = "database";

mysql_connect($host, $user, $pass);
mysql_select_db($db);

$pattern = "/width|height=\"[0-9]*\"/";

$query = "SELECT ID, post_content FROM wp_posts";
while ($row = mysql_fetch_assoc($query)) {
    if (preg_match($pattern, $row['post_content']))
    {
        $row['post_content'] = preg_replace($pattern, "", $row['post_content']);
        mysql_query("UPDATE wp_posts SET post_content=" . $row['post_content'] . "WHERE ID=" . $row['ID'];
    }
}

?>

无论如何我都会这样做。我假设当您说“没有 PHP 函数”时,您的意思是您希望数据库中的数据永久更新,而不是每次加载页面时都即时更新。这应该可以解决问题。编写一个原始 SQL 查询来处理这个问题可能要复杂得多。

您无需在 WordPress 中执行此操作。您甚至可以在不同的主机上运行它,前提是该主机具有数据库访问权限。

注意:我还没有测试过这些。如果您使用它,我会确保在您的数据库的一小部分上运行它,然后再将其应用到整个站点。

【讨论】:

    【解决方案2】:

    我使用了这个脚本,但它有一些错误。我已经纠正并使用了它。有用。确保表名 (wpfs_posts) 对应于您的表名和帖子。总是有备份。

    <?php
    
    $host = "localhost";
    $user = "nameuser";
    $pass = "password";
    $db   = "namedb";
    
    mysql_connect($host, $user, $pass);
    mysql_select_db($db);
    
    $pattern = "/width|height=\"[0-9]*\"/";
    
    $query = "SELECT ID, post_content FROM wpfs_posts";
    $result = mysql_query($query);
    while ($row = mysql_fetch_assoc($result)) {
        if (preg_match($pattern, $row['post_content']))
        {
            $row['post_content'] = preg_replace($pattern, "", $row['post_content']);
            $row['post_content']=mysql_real_escape_string($row['post_content']);
            mysql_query("UPDATE wpfs_posts SET post_content='" . $row['post_content'] . "' WHERE ID=" . $row['ID']);
        }
    }
    
    ?>
    

    【讨论】:

    • 上面的代码仍然有问题,当我运行它时,它会导致宽度值没有被删除,但适用于高度。所以我将模式更改为 $pattern = "/width=\"[0-9]*\"|height=\"[0-9]*\"/"; 现在它适用于宽度和高度
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 2019-05-26
    • 2014-07-03
    相关资源
    最近更新 更多