在通过 DOMDocument 操作 html 后返回字符串


Returning the string after manipulating html by DOMDocument

我有一个wordpress页面,我必须在其中将用户放置的图像标签替换为他在WordPress管理器中选择的特色图像。

到目前为止,我所做的是获取整页内容并替换了图像标签 src 属性。但是我没有办法将操纵的 html 返回到 $page->post_content以便我在页面上看到所需的结果。这是我到目前为止完成的代码。

        // Calling about page
        if($page->ID == 7){
            $image = wp_get_attachment_image_src( get_post_thumbnail_id(7), 'single-post-thumbnail' );
            $dom = new DOMDocument();
            @$dom->loadHTML($page->post_content);
            $imgs = $dom->getElementsByTagName("img");
            foreach($imgs as $img){
                $img->setAttribute( 'src' , $image[0] );
            }
        }
        echo $page->post_content; //It is still showing the old image.
你必须

content_save_pre过滤post_content

function replace_content_image($page)
    {
       if($page->ID == 7){
            $image = wp_get_attachment_image_src( get_post_thumbnail_id(7), 'single-post-thumbnail' );
              $dom = new DOMDocument();
              @$dom->loadHTML($page->post_content);
              $imgs = $dom->getElementsByTagName("img");
              foreach($imgs as $img){
                 $img->setAttribute( 'src' , $image[0] );
              }
               return $page->post_content;
   }    
add_filter( 'the_content', 'replace_content_image');

愿这对你有所帮助