{"id":96,"date":"2013-05-15T22:04:36","date_gmt":"2013-05-16T06:04:36","guid":{"rendered":"http:\/\/nramkumar.org\/tech\/?p=96"},"modified":"2014-02-01T00:26:27","modified_gmt":"2014-02-01T08:26:27","slug":"wordpress-hacking-hiding-images-in-a-post","status":"publish","type":"post","link":"https:\/\/nramkumar.org\/tech\/blog\/2013\/05\/15\/wordpress-hacking-hiding-images-in-a-post\/","title":{"rendered":"WordPress Hacking &#8211; Hiding Images in a Post"},"content":{"rendered":"<p>This is the last in the series where we try to get WordPress to show single-post images in the sidebar and hide them from the post content itself. In the previous two posts we saw how to write a simple WordPress plugin and sidebar widget and how to extract and display images attached to a post in the sidebar. Now, we&#8217;ll see how to hide the images from the post&#8217;s content itself so it only shows in the sidebar. After looking at <a title=\"jQuery Colorbox\" href=\"http:\/\/www.techotronic.de\/plugins\/jquery-colorbox\/\" target=\"_blank\">jQuery Colorbox<\/a>, I decided to adopt a similar approach of regex matching on the content and modifying the post&#8217;s contents.<\/p>\n<p>WordPress exposes the filter <a title=\"the_content\" href=\"http:\/\/codex.wordpress.org\/Plugin_API\/Filter_Reference\/the_content\" target=\"_blank\"><code>the_content<\/code><\/a> that allows us to hook into the post&#8217;s content and modify it as we please. We can use the <a title=\"add_filter\" href=\"http:\/\/codex.wordpress.org\/Function_Reference\/add_filter\" target=\"_blank\"><code>add_filter<\/code><\/a> function to add our content filter hook in our plugin. One thing to note is that you specify a priority to the filter and you&#8217;ll need to specify a high number so the filter runs as late as possible and filters out images. Here&#8217;s the code I used to filter out images from the post&#8217;s content:<\/p>\n<pre>function hideAllImages($content) {\r\n    global $post;\r\n\r\n    $imgfilter = array(\r\n        'order' =&gt; 'ASC',\r\n        'post_mime_type' =&gt; 'image',\r\n        'post_parent' =&gt; $post-&gt;ID,\r\n        'post_status' =&gt; 'inherit',\r\n        'post_type' =&gt; 'attachment',);\r\n\r\n    $attachments = get_children( $imgfilter );\r\n    $images = array();\r\n\r\n    if ( $attachments ) {\r\n        foreach ( $attachments as $attachment ) {\r\n            $imgUrl = wp_get_attachment_url( $attachment-&gt;ID );\r\n            if ( SidebarImage_Widget::filterImageUrl($imgUrl) ) {\r\n                $images[] = str_replace('.jpg', '', $imgUrl);\r\n            }\r\n        }\r\n    }\r\n\r\n    $imgPattern = \"\/&lt;img([^\\&gt;]*?)&gt;\/i\";\r\n    if (preg_match_all($imgPattern, $content, $imgTags)) {\r\n        foreach ($imgTags[0] as $imgTag) {\r\n            $imgSrcPattern = '\/src=\"([^\"]*?)\"\/i';\r\n            if ( preg_match($imgSrcPattern, $imgTag, $imgSources) &amp;&amp; \r\n                 !preg_match('\/style=\"display:none;\"\/i', $imgTag) ) {\r\n                $isMatch = false;\r\n                foreach ( $images as $img ) {\r\n                    $isMatch = strpos($imgSources[1], $img);\r\n                    if ( $isMatch !== false ) {\r\n                        break;\r\n                    }\r\n                }\r\n                if ( $isMatch !== false ) {\r\n                    $pattern = $imgPattern;\r\n                    $replacement = '&lt;img style=\"display:none;\" class=\"colorbox-none\" $1&gt;';\r\n                    $replacedImgTag = preg_replace($pattern, $replacement, $imgTag);\r\n                    $content = str_replace($imgTag, $replacedImgTag, $content);\r\n                }\r\n            }\r\n        }\r\n    }\r\n    return $content;\r\n}<\/pre>\n<p>We first iterate through the children of the post that are of type image to find the attached images. We strip the <code>.jpg<\/code> part of the image <code>URL<\/code> out and populate the array of attached image <code>URLs<\/code>. After that find all occurrences of <code>&lt;img&gt;<\/code> tags in the content and extract the <code>src<\/code> attribute. We see if this <code>src<\/code> is matched by any of the filtered attachment <code>URLs<\/code> that we built and if so, we hide this image by specifying <code>style=\"display:none;\"<\/code>.\u00a0 We do a prefix match on the attachment&#8217;s URI without the extension &#8211; this is because wordpress will automatically create foo_&lt;height&gt;x&lt;width&gt;.jpg files and use them for improving performance. In addition we add <code>class=\"colorbox-none\"<\/code> so these images are not picked up by colorbox for its slideshow. We use <code>filterImageUrl<\/code> to filter out emoticons and nextgen gallery thumbnails out from the attachment list so they&#8217;ll not be filtered out by this plugin. Finally, here&#8217;s the entire plugin code:<\/p>\n<pre>&lt;?php\r\n\/*\r\nPlugin Name: Sidebar Image\r\nPlugin URI: http:\/\/www.nramkumar.org\/tech\r\nDescription: Hides images from single posts and shows them in the sidebar\r\nVersion: 0.5\r\nAuthor: Ramkumar Natarajan\r\nAuthor URI: http:\/\/www.nramkumar.org\/tech\r\n*\/\r\n\r\n\/\/error_reporting(E_ALL);\r\nadd_action('widgets_init', array('SidebarImage_Widget', 'register'));\r\nadd_filter('the_content', array('SidebarImage_Widget', 'hideAllImages'), 10);\r\n\r\nclass SidebarImage_Widget extends WP_Widget {\r\n    function SidebarImage_Widget() {\r\n        parent::WP_Widget(false, 'Sidebar Image Widget');\r\n    }\r\n\r\n    function form($instance) {\r\n    }\r\n\r\n    function update($new_instance, $old_instance) {\r\n        return $new_instance;\r\n    }\r\n\r\n    function filterImageUrl($imgurl) {\r\n        return \r\n            (strpos($imgurl, '_thumb.jpg') === false) &amp;&amp;\r\n            (strpos($imgurl, 'Emoticon') === false);\r\n    }\r\n\r\n    function widget($args) {\r\n        global $post;\r\n\r\n        extract($args);\r\n\r\n        if ( is_single() ) {\r\n            echo $before_widget;\r\n            echo $before_title . 'Snapshots' . $after_title;\r\n            $imgfilter = array(\r\n                'order' =&gt; 'ASC',\r\n                'post_mime_type' =&gt; 'image',\r\n                'post_parent' =&gt; $post-&gt;ID,\r\n                'post_status' =&gt; 'inherit',\r\n                'post_type' =&gt; 'attachment',);\r\n\r\n            $attachments = get_children( $imgfilter );\r\n\r\n            if ( $attachments ) {\r\n                $images = array();\r\n                foreach ( $attachments as $attachment ) {\r\n                    $imgUrl = wp_get_attachment_url( $attachment-&gt;ID );\r\n                    if ( SidebarImage_Widget::filterImageUrl($imgUrl) ) {\r\n                        $images[] = $attachment;\r\n                    }\r\n                }\r\n\r\n                foreach ( $images as $image ) {\r\n                    $imageSrc = wp_get_attachment_image_src( $image-&gt;ID, 'medium' );\r\n                    echo '&lt;a href=\"' . wp_get_attachment_url( $image-&gt;ID ) . '\" class=\"cboxElement\"&gt;' . \r\n                         '&lt;img src=\"' . $imageSrc[0] . '\" class=\"colorbox-' . $post-&gt;ID . '\"&gt;&lt;\/a&gt;';\r\n                }\r\n            }\r\n            else {\r\n                echo __('No Images', 'text_domain');\r\n            }\r\n            echo $after_widget;\r\n        }\r\n    }\r\n\r\n    function hideAllImages($content) {\r\n        global $post;\r\n\r\n        $imgfilter = array(\r\n            'order' =&gt; 'ASC',\r\n            'post_mime_type' =&gt; 'image',\r\n            'post_parent' =&gt; $post-&gt;ID,\r\n            'post_status' =&gt; 'inherit',\r\n            'post_type' =&gt; 'attachment',);\r\n\r\n        $attachments = get_children( $imgfilter );\r\n        $images = array();\r\n\r\n        if ( $attachments ) {\r\n            foreach ( $attachments as $attachment ) {\r\n                $imgUrl = wp_get_attachment_url( $attachment-&gt;ID );\r\n                if ( SidebarImage_Widget::filterImageUrl($imgUrl) ) {\r\n                    $images[] = str_replace('.jpg', '', $imgUrl);\r\n                }\r\n            }\r\n        }\r\n\r\n        $imgPattern = \"\/&lt;img([^\\&gt;]*?)&gt;\/i\";\r\n        if (preg_match_all($imgPattern, $content, $imgTags)) {\r\n            foreach ($imgTags[0] as $imgTag) {\r\n                $imgSrcPattern = '\/src=\"([^\"]*?)\"\/i';\r\n                if ( preg_match($imgSrcPattern, $imgTag, $imgSources) &amp;&amp; \r\n                     !preg_match('\/style=\"display:none;\"\/i', $imgTag) ) {\r\n                    $isMatch = false;\r\n                    foreach ( $images as $img ) {\r\n                        \/\/ echo __('Pattern ' . $img, 'text_domain');\r\n                        $isMatch = strpos($imgSources[1], $img);\r\n                        if ( $isMatch !== false ) {\r\n                            break;\r\n                        }\r\n                    }\r\n                    if ( $isMatch !== false ) {\r\n                        $pattern = $imgPattern;\r\n                        $replacement = '&lt;img style=\"display:none;\" class=\"colorbox-none\" $1&gt;';\r\n                        $replacedImgTag = preg_replace($pattern, $replacement, $imgTag);\r\n                        $content = str_replace($imgTag, $replacedImgTag, $content);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        return $content;\r\n    }\r\n\r\n    function register(){\r\n        wp_register_sidebar_widget(\r\n            'Sidebar_Image_Widget', \r\n            'Sidebar Image Widget', \r\n            array('SidebarImage_Widget', 'widget'));\r\n    }\r\n}\r\n?&gt;<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>This is the last in the series where we try to get WordPress to show single-post images in the sidebar and hide them from the post content itself. In the previous two posts we saw how to write a simple WordPress plugin and sidebar widget and how to extract and display images attached to a&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[29,30,28,27],"tags":[73,37,72],"class_list":["post-96","post","type-post","status-publish","format-standard","hentry","category-colorbox","category-images","category-jquery","category-wordpress","tag-colorbox","tag-hide-images","tag-wordpress"],"_links":{"self":[{"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/posts\/96","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/comments?post=96"}],"version-history":[{"count":3,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/posts\/96\/revisions"}],"predecessor-version":[{"id":134,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/posts\/96\/revisions\/134"}],"wp:attachment":[{"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/media?parent=96"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/categories?post=96"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/tags?post=96"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}