Is it possible to pull the content from the title tag and display it as text on a html webpage? Wordpress

1.7k views Asked by At

I'm in the process of making a site that has a lot of different URL's all sharing the same design. I'm trying to make the titles display on each site because they're all unique, where as everything else is the same for the most part. I tried using this code:

<script type="text/javascript">
<!--
  document.write(document.referrer);
// -->
</script>

On some browsers this would display the URL at the bottom of the webpage, but on others it wouldn't show at all, I tried to grab the data from this and move it to where I would like the content to go but I wasn't able to select it at all.

I'm using wordpress as my CMS and I looked into the editor to see if there was something I could do there and realized its all php - something I've never used before. I searched if there was a way to do this in wordpress but turned up with nothing.

I'm assuming this is where the php code should be

<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">here</a></h1>

I'm assuming I'd need something similar to the php echo in the href where it says 'here'. Just to try I put the script in the anchor tag and not surprisingly the whole site stopped working because of an error. So I'm stuck.

Is there a way in wordpress that I can pull the title tag from the header into the html?

3

There are 3 answers

0
dokgu On BEST ANSWER

Here's a simple script to get the title of the page.

var title = $("title").text();
$("body").html("<h1>" + title + "</h1>");

The first line is getting the text portion of the title tag. The second line just replaces all the contents of your body tag to only contain the title extracted. Modify the second line to fit what you need. The important part you need to know is the first line.

3
Craig On

If you want the current page title use

<?php the_title(); ?>

Or if you want the meta title use

<?php wp_title(); ?>

They're both WordPress PHP functions.

Assuming you want the meta title (from the header) use

<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php wp_title(); ?></a></h1> 

Here's the docs https://developer.wordpress.org/reference/functions/wp_title/

Hope that helps!

1
Craig Mason On

I believe this was answered in this question

To get the path, you can use:

var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL