1

I have some posts with video tag that contains autoplay (they should autoplay when you access the post page).

I am using the the_content to show these videos on index page.

The problem is that when you access the home page, all the videos start playing.

I have used the following function to remove it:

function replace_ap($text){
    $replace = array(
        'autoplay=""' => ''
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
 
add_filter('the_content', 'replace_ap');

but now the "autoplay" attribute is removed from the post pages also.

How can I remove it only from the index ?

My thought was to create a function that gets the content and add the filter to this function, then call it from index.php instead of "the_content", but I don't know how or if it's possible

Thank you!

2
  • i guess you could put conditional tags inside your filter as well: is_home(), is_front_page(), is_single()..? – honk31 Jun 30 '20 at 13:05
  • 1
    @honk31 Yes, indeed. Thank you! – Carje Jun 30 '20 at 13:54
1

Few possibilities here:

  1. In index.php you find the_content() and replace it with:

    $content = get_the_content( $more_link_text, $strip_teaser );
    $content = apply_filters( 'the_content', $content );
    $content = str_replace( ']]>', ']]>', $content );
    
    $replace = array(
      'autoplay=""' => ''
    );
    
    $text = str_replace(array_keys($replace), $replace, $text);
    echo $text;
    
  2. Did you try putting that bit of code in index.php? Maybe you have it in functions.php so it will always run but putting it index.php might cause it to only apply there

  3. As @honk31 says you could test for which page you're on inside the function. This might be good if you want this behaviour to apply on other pages later. E.g.

    function replace_ap($text){
      if (is_home()) {
        $replace = array(
            'autoplay=""' => ''
        );
        $text = str_replace(array_keys($replace), $replace, $text);
        return $text;
      } else {
        return $text;
      }
    }
    
    add_filter('the_content', 'replace_ap');
    
1
  • I have tested both ways and it's working as it should. Indeed, @honk31 variant is better for future use. Thank you! – Carje Jun 30 '20 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.