没有完整的代码,但我知道您可以将其粘在一起。:)
查找未附加图像的所有帖子ID(借用自wp-admin/upload.php
):
global $wpdb;
$lost = $wpdb->get_col( "
SELECT ID FROM $wpdb->posts
WHERE post_type = \'attachment\' AND post_parent > \'0\'
AND post_parent NOT IN (
SELECT ID FROM $wpdb->posts
WHERE post_type NOT IN ( \'attachment\', \'" . join( "\', \'", get_post_types( array( \'public\' => false ) ) ) . "\' )
)
" );
获取所有帖子ID的图像URL:由于这些附件没有父级,其URL等效于
get_the_guid()
(这是GUID看起来像URL的两个原因之一,我不喜欢这样)。
$urls = array ();
foreach ( $lost as $id )
$urls[ $id ] = get_the_guid( $id );
现在查找带有这些图像的帖子,并将这些图像附加到这些帖子上:
global $wpdb;
foreach ( $urls as $id => $url )
{
$posts = get_posts( array ( \'s\' => $url, \'numberposts\' => 1 ) );
if ( ! $posts )
continue;
$parent_id = $posts[0]->ID;
$wpdb->query(
$wpdb->prepare(
"UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = \'attachment\' AND ID = %d",
$parent_id,
$id
)
);
}
未测试,仅作为提示。