我正在尝试从我的wordpress媒体库中删除重复的图像。
帖子本身并不重复,但每个帖子的每个附件图片都会出现两次。
我已经环顾四周,但没有一个人能够得到明确的答案。有些人说使用过这样的东西:
<?php
$p = get_posts(array('numberposts'=> -1));
foreach($p as $t) {
$s = get_children(array('post_type' => 'attachment', 'numberposts' => -1 ));
foreach ($s as $u) {
var_dump($u);
}
}
?>
但似乎仍然有点缺失,比如这给我带来了附件列表,但我仍然不知道如何比较它们。
在我看来,我需要使用一些SQL查询并直接从数据库中删除媒体文件。我不太确定如何解决这个问题。
从理论上讲,我需要尝试查找帖子,foreach post get attachments,if attachment filename == filename然后删除文件名。
帮助表示感谢。
答案 0 :(得分:1)
在主题文件夹中创建一个文件,然后在该粘贴中创建第一种或第二种解决方案:
第一种方式(与其标题比较 - 推荐):
<?php
require('../../../wp-blog-header.php');
global $wpdb;
$querys = $wpdb->get_results(
"
SELECT a.ID, a.post_title, a.post_type
FROM $wpdb->posts AS a
INNER JOIN (
SELECT post_title, MIN( id ) AS min_id
FROM $wpdb->posts
WHERE post_type = 'attachment'
GROUP BY post_title
HAVING COUNT( * ) > 1
) AS b ON b.post_title = a.post_title
AND b.min_id <> a.id
AND a.post_type = 'attachment'
");
echo "<style>td {padding:0 0 10px;}</style>";
echo "<h2>DUPLICATES</h2>\n";
echo "<table>\n";
echo "<tr><th></th><th>Title</th><th>URL</th></tr>\n";
foreach ( $querys as $query )
{
$attachment_url = wp_get_attachment_url($query->ID);
$delete_url = get_delete_post_link($query->ID);
$delete_url = get_delete_post_link($query->ID);
echo "<tr>
<td><a style=\"color: #FFF;background-color: #E74C3C;text-decoration: none;padding: 5px;\" target=\"_blank\" href=\"".$delete_url."\">DELETE</a></td>
<td>".get_the_title($query->ID)."</td>
<td><a href=\"".$attachment_url."\">".$attachment_url."</a></td>
</tr>\n";
}
echo "</table>";
?>
第二种方式(与其网址比较) 它的工作方式是,它相互检查每个文件。因此,如果你有一个像file.jpg和file1.jpg这样的文件,那么它会将它们作为重复项捕获。此外,如果你有一个像file1.jpg和file11.jpg这样的文件,那么它会将它们作为重复项捕获,即使它们可能是完全不同的文件。 :
<?php
require('../../../wp-blog-header.php');
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'orderby' => 'name',
'order' => 'ASC',
'post_status' => null,
'post_parent' => null, // any parent
);
$newArray = array();
$attachments = get_posts($args);
$attachments2 = $attachments;
if ($attachments){
foreach($attachments as $post){
$attachment_url = wp_get_attachment_url($post->ID);
$delete_url = get_delete_post_link($post->ID);
$newArray[] = array("att_url" => $attachment_url, "del_url" => $delete_url);
}
echo "<table>";
$newArray2 = $newArray;
echo "<tr><td><h2>DUPLICATES</h2></td></tr>";
foreach($newArray as $url1){
$url_del = $url1['del_url'];
$url1 = $url1['att_url'];
$url11 = substr($url1,0,strrpos($url1,"."));
foreach($newArray2 as $url2){
$url2 = $url2['att_url'];
$url2 = substr($url2,0,strrpos($url2,".") - 1);
if($url2 == $url11)
{
echo "<tr><td><a href=\"".$url_del."\">DELETE</a></td><td><a href=\"".$url1."\">".$url1."</a></td></tr>";
}
}
}
echo "</table>";
echo "<table>";
echo "<tr><td><h2>ALL ATTACHMENTS</h2></td></tr>";
foreach($attachments as $tst1){
echo "<tr><td>".$tst1->guid."</td></tr>";
}
echo "</table>";
}
?>
然后尝试在浏览器中访问该文件,它会显示所有重复项的列表。