views:

89

answers:

2

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

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

I'd also like to be able to use this same technique to add the H2 text into the meta description - Can anyone help?

+2  A: 

That sounds like something that jQuery would excel at:

<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 modify the meta data, you would do more of the same. I strongly recommend jQuery - Novice to Ninja as an amazing way to get into great depth 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>
Jonathan
Is there a way to also add the content of the H2 tag into the meta description too?
Stephen Meehan
Just tried this and it works a treat. Thanks! Still need to get the same info into the meta description...
Stephen Meehan
Thank you Jonathan for all your help! :)
Stephen Meehan
+2  A: 

If your h2 text is dynamically made then other parts of your web page can be dynamically created too. 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 technique, you can define the text of other parts of the web page.

scubacoder
This is good because search engines will see the title.
Jonathan
Hi, The H2 tag isn't dynamically created. Is there a way to wrap the H2 tag in some PHP so it spits out a page title and adds the text in the H2 tag into the meta description?
Stephen Meehan
@Stephen Not exactly. How many pages would you need to do this on?
George Marian
Ah, then one of the best ways to do this is via jQuery. I believe Jonathan answered this in his jQuery answer thread. (+1)
scubacoder
@George Marian I need to add this code to about 45 pages, by hand! The jQuery technique suggested by @Jonathan works great. But I also need a way to put the same info from the H2 tag into the meta data description.
Stephen Meehan
@Stephen Ideally, what you'd want is a script to automate that for you and then you'd simply verify each file by hand. Perl would be great for that, though it could also be done in PHP. (To be explicit: I'm talking about a script to process your existing html/php files.) That said, it would not be a trivial piece of code. Now, regarding the JavaScript/jQuery solution, I'd personally stay away from that, especially since this seems like an exercise in SEO. I would do it all on the server side, be it with PHP or static HTML.
George Marian