Wordpress 将图像链接从附件页更改为图像URL

Wordpress 将图像链接从附件页更改为图像URL,wordpress,Wordpress,正在查找将所有图像链接从WordPress中的附件页更新到图像文件的SQL查询。WordPress附件页是动态生成的。对于任何附件(上传的文件),始终存在可通过$ID检索的附件页面,其中$ID是wp\u posts数据库中的附件ID,且post\u type设置为attachment。它是guid字段,但始终设置为可通过的直接URL,例如 然而,如果发布的帖子附带了媒体,并且在URL上打开了永久链接,那么这些帖子总是会变成漂亮的帖子,例如以 我必须假设您遇到了一个问题,即您的帖子和页面中的所有附

正在查找将所有图像链接从WordPress中的附件页更新到图像文件的SQL查询。

WordPress附件页是动态生成的。对于任何附件(上传的文件),始终存在可通过$ID检索的附件页面,其中
$ID
wp\u posts
数据库中的附件ID,且
post\u type
设置为
attachment
。它是
guid
字段,但始终设置为可通过的直接URL,例如

然而,如果发布的帖子附带了媒体,并且在URL上打开了永久链接,那么这些帖子总是会变成漂亮的帖子,例如以

我必须假设您遇到了一个问题,即您的帖子和页面中的所有附件都包装在锚链接中,这些锚链接指向附件页面,而不是直接路径。这是一个关于文章内容的问题,以及图像是如何首先插入到文章中的,与数据库中数据的结构无关

wp\u posts.post\u content
字段包含这些附件URL。可以直接将这些URL转换为直接URL,但这是一项相当棘手的任务,因为您不知道生成了哪种类型的附件URL。一种肮脏的方法是解析每个帖子/页面的内容,寻找包装了
的图像,因此使用API是一种方法

例如,下面是可以在主题的
functions.php
中运行的代码草图。事先备份你的数据库,我不能保证这不会在我们面前爆炸

<?php
add_action( 'init', function() {
    $posts = get_posts( array(
        'posts_per_page' => -1, // Get all posts with
        'post_type' => array( 'any' ), // any post type
        's' => 'rel="attachment' // with our target pages
    ) );

    foreach ( $posts as $post ) {
        $dom = new DOMDocument();
        $dom->loadHTML( $post->post_content ); // Parse the content
        foreach ( $dom->getElementsByTagName( 'a' ) as $a ) {
            if ( $a->getAttribute( 'rel' ) && strpos( $a->getAttribute( 'rel' ), 'attachment' ) !== false ) {
                // Good candidate, replace rel and href by those in image
                $src = $a->getElementsByTagName( 'img' )->item( 0 )->getAttribute( 'src' ); // get the src
                $a->setAttribute( 'href', $src ); // set the href to the src
                $a->removeAttribute( 'rel' ); // Cleanup rel
            }
        }
        // Strip the extras
        $content = preg_replace( '#<!DOCTYPE.*?>\n#', '', str_replace( array( '<html><body>', '</body></html>' ), '', $dom->saveHTML() ) );

        // Save the post back
        wp_update_post( array( 'ID' => $post->ID, 'post_content' => $content ) );
    }
} );

详细说明你的问题!