admin管理员组

文章数量:1327661

for my google event tracking, I need to have the Page Title in Wordpress of the current site within a jquery function.

There are many ways to get the title with php, but I´m not really shure, that it is the best way.

Thank you, Cheers Marten

for my google event tracking, I need to have the Page Title in Wordpress of the current site within a jquery function.

There are many ways to get the title with php, but I´m not really shure, that it is the best way.

Thank you, Cheers Marten

Share Improve this question edited Dec 14, 2013 at 9:34 user1735856 asked Dec 14, 2013 at 9:23 user1735856user1735856 2817 silver badges16 bronze badges 1
  • You can easily do this with JavaScript using the code var title = $(document).find("title").text(); – Talha Masood Commented Dec 14, 2013 at 9:34
Add a ment  | 

4 Answers 4

Reset to default 2

Depending on how you generate this page title, you need to pass this through to your JS script.

You can do this with wp_localize_script()

http://codex.wordpress/Function_Reference/wp_localize_script

So after you have enqueued the script you can then pass parameters through.

wp_enqueue_script( 'my-script' );
wp_localize_script( 'my-script', 'script_vars', array('site_title' => 'This is my site title' );

You can then use it in your JS file like this:

alert(script_vars.site_title);

just use:

alert(document.title);

depending on your setting you want to strip out the blog name out of it

First, you'll need to get the title in PHP:

$title = get_the_title();

Include your javascript file:

wp_enqueue_script( 'your-script', '../source/to/your/javascript_file.js' )

Then you need to send the $title variable to your javascript file using wp_localize_script():

wp_localize_script( 'your-script', 'script_vars', array('site_title' => $title );

Now you have access to the site_title in your javascript file by doing so:

var site_title = script_vars.site_title;
console.log(site_title);

Jquery

$(document).find("title").text();

javascript

document.title

or

var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
alert(sPage);

本文标签: Get pagetitle in wordpress with jquery or javascriptStack Overflow