2

I'm trying to build a Joomla article to display a photo the user selects. I'm using the Regular Labs Sourcerer plugin to place the required PHP code into my article.

I want to set various tags within the head of the document using PHP. So far I've been able to set the keywords and the description meta tags using the following code:

$document = JFactory::getDocument();
$document->setDescription("Your meta description");
$document->setMetaData('keywords', "keyword1,keyword2");

However, I can't set the title tag using the following similar code:

$document = JFactory::getDocument();  
$document->setTitle("Your Title");

In this case Joomla displays the Browser Page Title from the article's menu item, and ignores the title I'm trying to set. Leaving the Browser Page Title blank doesn't help- a default value based on the menu item title is used.

I only require to set the title tag for one article on my site, so I'd prefer to use the PHP / Sourcerer method if possible, rather than edit template files.

Is it possible to set the title tag using PHP and Sourcerer, and if so, how is it done?

  • This is a similar question to How do I set the Page Title from within ChronoForms? – Neil Robertson Jun 8 '16 at 0:30
  • 1
    At a guess, I think your code isn't working because it's being fired before Joomla's core setTitle(), therefore gets overridden. Could be wrong, but the only conclusion I could come to. In which case you'll need to use a plugin for this or go along with @NeilRobertson's answer using Javascript – Lodder Jun 8 '16 at 9:49
  • I agree with @Lodder's comment. I checked using getTitle(), and the title tag is definitely being set by my code. So the Joomla core is definitely overwriting it. I tried moving the Sourcerer plugin to the very end of the plugin order, but this didn't help. It looks as if it's a choice between @NeilRobertson's javascript solution, or editing core Joomla files. – user8521 Jun 9 '16 at 19:55
  • Out of interest, does anyone know which core Joomla files are responsible for setting the title tag? – user8521 Jun 11 '16 at 14:20
1

I'm not sure why but the only way I can get this to work is to use JavaScript like this or similar:

{source}
  <script type="text/javascript">
    window.onload = function() {
      document.title = 'Your title here'; 
    }
  </script>
{/source}

Apparently Google does crawl content injected by JavaScript.

There is probably a better way to do this and I'd love to see some alternative answers to this question.

  • 1
    Just simplified the code in the answer. Feel free to revert if you want – Lodder Jun 8 '16 at 9:51
  • Thanks, I need all the help I can get with JavaScript! :) – Neil Robertson Jun 8 '16 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy