CakePHP Canonical Tag with html helper
Asked Answered
J

5

9

How can I create this using the html helper? (with inline=false so i can specify it on a per-view basis)

<link rel="canonical" href="http://www.example.com/product.php?item=swedish-fish" />

Can't seem to find anything on this, apart from a patch that doesn't work.

Jeremiah answered 15/3, 2011 at 9:54 Comment(0)
L
9

Found this in CakePHP bugtracking site : http://cakephp.lighthouseapp.com/projects/42648/tickets/1063-support-for-custom-meta-tag-elements-in-htmlhelper

Apparently you can use

echo $this->Html->meta('canonical', 'http:://example.com', array('rel'=>'canonical', 'type'=>null, 'title'=>null));
//outputs <link href="http:://example.com" rel="canonical" />
Lexine answered 15/3, 2011 at 10:4 Comment(0)
J
8

It seems my friend just told me that I told him how to do this a few months back, problem solved...

<?php echo $this->Html->meta('canonical', 
    'http://www.example.com/product.php?item=swedish-fish', 
    array('rel'=>'canonical', 'type'=>null, 'title'=>null, 'inline' => false)
);?>
Jeremiah answered 15/3, 2011 at 10:3 Comment(0)
K
3

If you're looking for something that automatically outputs the current url into a canonical tag, you can use the $this->Html->url(null, true); or $this->here; within the Cakephp html helper.

<?php echo $this->Html->meta('canonical', $this->Html->url(null, true), array('rel'=>'canonical', 'type'=>null, 'title'=>null)); ?>

Or

<?php echo $this->Html->meta('canonical', $this->here, array('rel'=>'canonical', 'type'=>null, 'title'=>null)); ?>

WARNING: I have heard of some cases where $this->here has issues on local dev environments.

Kamilahkamillah answered 8/12, 2014 at 23:53 Comment(0)
S
1

In CakePHP 2:

echo $this->Html->meta('canonical', 'http://example.com', array('rel' => 'canonical', 'type' => null, 'title' => null, 'inline' => false));

In CakePHP 3:

echo $this->Html->meta('canonical', 'http://example.com', array('rel' => 'canonical', 'type' => null, 'title' => null, 'block' => true));

Note that the main difference between versions is that CakePHP 2 uses 'inline' => false whereas CakePHP 3 uses 'block' => true to place these within the document <head> tags.

Significant answered 28/7, 2017 at 0:40 Comment(0)
C
0

In CakePHP 4:

In your view (es: Articles/view.php) add this:

<?php $this->Html->meta(
  'canonical',
  Router::url(['controller' => 'Articles', 'action' => 'view', $article->slug], true),
  [
    'block' => true
  ]
);
?>

Then you print it in your layout/default.ctp with this instruction

<?= $this->fetch('meta') ?>
Calysta answered 28/12, 2020 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.