How to create a dynamic page title using PHP

Hi, I was wondering if anyone could help with this PHP problem.

Is it possible to use text in the H2 tag and use it to dynamically populate the page title.

I would also like to be able to use the same technique to add H2 text to the meta description. Can anyone help?

+4
source share
3 answers

This is similar to what jQuery will excel:

<script type='text/javascript' src='jquery-1.4-min.js'></script> <script type="text/javascript"> $(document).ready(function() { document.title = $('h2:first').text(); }); </script> 

To change the metadata, you will do more of the same. I highly recommend jQuery, a beginner to the ninja, as an awesome way to go deeper with jQuery.

 <html> <head> <meta description="" /> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('meta:first').attr('description', $('h2:first').text()); alert($('meta:first').attr('description')); }); </script> </head> <body> <h2>Testing 123</h2> </body> </html> 
+3
source

If your h2 text is dynamically made, other parts of your web page can also be dynamically created. For example, if you have a variable $ a = "My Text"

 <?php $a = "My Text" ?> <html> <head> <title><?php echo $a;?></title> </head> <body> <h2><?php echo $a;?></h2> </body> </html> 

Using this method, you can determine the text of other parts of the web page.

+5
source

For those who are looking for a slightly more dynamic method that does a meta and a title at the same time and uses some casts:

 <script type="text/javascript"> $(document).ready(function() { $title = ''; if($('h1:first').text() != '') { $title = $('h1:first').text(); document.title = document.title + " | " + $title; $('meta:first').attr('content', $title); } else if($('h2:first').text() != ''){ $title = $('h2:first').text(); document.title = document.title + " | " + $title; $('meta:first').attr('content', $title); } else if($('h3:first').text() != ''){ $title = $('h3:first').text(); document.title = document.title + " | " + $title; $('meta:first').attr('content', $title); } else if($('.panel-heading:first').text() != ''){ $title = $('.panel-heading:first').text(); document.title = document.title + " | " + $title; $('meta:first').attr('content', $title); } }); </script> 

This will merge the generated header at the end of your current header. He also sets the description to one value.

You must have a description meta tag as the first meta tag in your title so that it works to set a description meta file. If this is not the case, you can change the $('meta:first') selector to select a description meta tag.

I use bootstrap, so the first title of the panel is my return case: $('.panel-heading:first') , change this to display the corresponding required margin if there are no title tags on the current page.

When all else fails, this script will leave your name value in its current value.

+1
source

All Articles