Search code examples
phphtmlincludemeta

Content from div as meta description


I'm trying to get a content from a p element as a meta description. I tried to adapt what I found here but no luck. Show content from DIV in a META-tag What i have is a bunch of .php files with included header and footer like so.

<?php
 $title="Page title";
 include_once("/includes/header.php");
?>
<div class="container">
<p>This content i want in meta description and it's different in each php file.</p>
</div>
<?php
 include_once("/includes/bottom.php");
?>

What i want to achive is to have different meta descripiton for each .php page i have without editing hundred files (as i already did with the title...) but based on the content inside that paragraph using a script i can add to my header.php.

I tried to make that as clear as i could. Thank You in advance for all Your help. EDIT Where i want that description is in header.php

<meta name="description" content="This is where i want that description" />

Solution

  • You don't even need PHP. With Javascript, you can retrieve the value of the paragraph tag, and then change the meta tag to have this value. Something like this:

    <script>
    
    var myText = document.getElementsByTagName('p')[0].innerHTML
    
    document.getElementsByTagName('meta')[0].setAttribute("content", myText);
    
    </script>