Tweaking auto alt tag generation in Wordpress

Discussion in 'PHP' started by popokolok, May 4, 2013.

  1. #1
    Hello,

    I tried many WP plugins to create automatic alt tags site-wide. None of the available plugins seem to work (I Tried SEO Friendly Images, Wordpress SEO Images, WP Image SEO) even with the default theme... Any other plugins anyone can suggest, please?

    Anyway, I found this code that's supposed to go into the functions.php of the theme, but it doesn't seem to work... It's supposed to check for images without an alt tag and fill in the post title - can anyone here please help me with making this code to change ALL alt tags by putting the post title in them and making this code work in the first place..?

    function add_alt_tags($content)
    {
            global $post;
            preg_match_all('/<img (.*?)\/>/', $content, $images);
            if(!is_null($images))
            {
                    foreach($images[1] as $index => $value)
                    {
                            if(!preg_match('/alt=/', $value))
                            {
                                    $new_img = str_replace('<img', '<img alt="'.$post->post_title.'"', $images[0][$index]);
                                    $content = str_replace($images[0][$index], $new_img, $content);
                            }
                    }
            }
            return $content;
    }
    add_filter('the_content', 'add_alt_tags', 99999);
    PHP:
    Thank you very much!
     
    popokolok, May 4, 2013 IP
  2. usr

    usr Greenhorn

    Messages:
    6
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    13
    #2
    A simple way to insert the alt="title" attribute would be this , but you have to introduce the title too, unfortunately:

    function add ($content,$post_title)
    {
    //it splits the string where '<img' is/are
    $array=explode('<img',$content);

    //it rebuilds the string inserting 'alt="..."' $new_content=implode("<img alt=\"$post_title\"",$array);

    return $new_content;
    }

    The new content $new_content will have the alt="title" in place

    $new_content=add($content,$post_title);
    Maybe you can improvise something with this...
     
    usr, May 9, 2013 IP