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.

Warren Sergent
  • 2,542
  • 4
  • 36
  • 42
Chris J Allen
  • 18,970
  • 20
  • 76
  • 114

5 Answers5

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" />
JohnP
  • 49,507
  • 13
  • 108
  • 140
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)
);?>
bancer
  • 7,475
  • 7
  • 39
  • 58
Chris J Allen
  • 18,970
  • 20
  • 76
  • 114
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.

bigmike7801
  • 3,908
  • 9
  • 49
  • 77
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.

Warren Sergent
  • 2,542
  • 4
  • 36
  • 42
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') ?>
massimoi
  • 324
  • 4
  • 11