在DOMDocument操作html后返回字符串

时间:2014-11-18 12:33:49

标签: php wordpress domdocument

我有一个wordpress页面,其中我必须替换用户放置的图像标签是wordpress编辑器,其中包含他在wordpress admin中选择的特色图像。

我已经完成了整个页面内容并替换了图像标记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.

1 个答案:

答案 0 :(得分:0)

您必须使用post_content

过滤content_save_pre

作为

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');

这可以帮到你