• I have the following code:

    function send_media_credit_to_editor($html, $attachment_id, $attachment) {
            $post =& get_post($attachment_id);
            $author_id = $post->post_author;
            $user = get_userdata($author_id);
            if ( !empty($user->user_nicename) )
                    $author_nicename = $user->user_nicename;
            $pattern = '/(\"]<img)/i';
            $author_link = '<a href="' . get_author_posts_url($author_id, $author_nicename) . '">$author_nicename</a>';
            $replacement = '<br /><a href=' . $author_link . '${1}';
            $html = preg_replace($pattern, $replacement, $html);
            return $html;
    }
    add_filter('image_send_to_editor', 'send_media_credit_to_editor', 10, 3);

    However, the $html that I return is not used and the caption is not filtered at all. However, if I replace the entire function with:

    function send_media_credit_to_editor($html, $attachment_id, $attachment) {
            $html = 'Hi';
            return $html;
    }

    Then the caption is properly changed to be simply the word “Hi”. Why is my preg_replace not working and how can I get it to work?

    Thanks,
    Scott

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter Scott Bressler

    (@sbressler)

    To clarify and simplify a bit, I’m trying to add something to the end of the caption that is displayed under the picture. So if the shortcode written to the editor were:
    [caption id="attachment_5" align="aligncenter" width="300" caption="This is a caption."]<img src="https://website.com/wp-content/uploads/2010/02/picture.jpg" alt="" title="" width="300" height="53" class="size-medium wp-image-5" />[/caption]
    I want it to become, with the extra bit added to the end of the caption text:
    [caption id="attachment_5" align="aligncenter" width="300" caption="This is a caption. <br /><a href='https://www.link.com'>Link Text</a>"]<img src="https://website.com/wp-content/uploads/2010/02/picture.jpg" alt="" title="" width="300" height="53" class="size-medium wp-image-5" />[/caption]

    I thought that this code should accomplish that:

    function change_caption($html, $attachment_id, $attachment) {
            $pattern = '/("]<img)/';
            $link = '<a href=\'https://www.link.com\''>Link Text</a>';
            $replacement = '<br />' . $link . '${1}';
            $html = preg_replace($pattern, $replacement, $html);
            return $html;
    }
    add_filter('image_send_to_editor', 'change_caption', 10, 3);

    However, the above (much-simplified) filter doesn’t accomplish anything — the caption as it normally would be inserted is indeed inserted into the editor. Thoughts as to why?

    Thanks!

    Thread Starter Scott Bressler

    (@sbressler)

    Seems like I need to filter the caption shortcode instead…

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘preg_replace on image caption’ is closed to new replies.