Get pagetitle in wordpress with jquery or javascript

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.

Read More

Thank you, Cheers Marten

Related posts

Leave a Reply

4 comments

  1. 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.org/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);
    
  2. 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);
    
  3. Jquery

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

    javascript

    document.title
    

    or

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