Jump to content

Append canonical URL to head


Leftfield
 Share

Recommended Posts

Hey Leftfield, it might help us better answer your question if you can describe in more detail your current template set up. For example, I use a template structure where the head is included into every template utilizing 

<?php include("./inc/header.php"); ?>

This way, I call some global settings in the head, and it is included everywhere. However, some people use the delayed output approach. 

Link to comment
Share on other sites

OK.

I got head.php, footer.php, tags.php etc...

I want in tags.php, which doesn't have <head>...</head> in it, to append some Php magic so I could include the line in the head like this one:

<link rel="canonical" href="http://example.com/tags/" />


Something similar to 

headScripts->append

 

Link to comment
Share on other sites

This is the way I found that works:

1. Create a new folder in your site Modules folder named Injector ( site/modules/Injector ).

2. Copy / paste the following code into a file named Injector.module.php and put it in your module folder.

<?php namespace ProcessWire;
class Injector extends Process {
  
  public static function getModuleinfo() {
    return [	  
      'title' => 'Injector',	  
      'summary' => 'Add content before </head> and before </body>',	  
      'href' => '',	  
      'author' => '',	  
      'version' => '1.0.0',	   
	  'singular' => true, 
	  'autoload' => true, 
    ];
  }
  
	public function init() {
		// add a hook after each page is rendered and modify the output
		$this->addHookAfter('Page::render', $this, 'after_render');		
	}
	
    public function after_render($event) {	
		/** @var Page $page */
		$page = $event->object; 

		// ignore templates
		$ignore = array( 'admin' );
		if( !in_array( $page->template, $ignore ) ){
			$replace =array(
				'<!--[+head.include+]-->'  => ( defined( 'HEAD_INCLUDE' ) ? HEAD_INCLUDE : '' ),
				'<!--[+body.include+]-->'  => ( defined( 'BODY_INCLUDE' ) ? BODY_INCLUDE : '' )
				);
		
			$event->return = str_replace( array_keys( $replace ), array_values( $replace ),$event->return );
			
	    }
	}
}

4. In your admin, refresh Modules and then install Injector.

5. In your template before the </head> tag, add <!--[+head.include+]-->, also optional add the <!--[+body.include+]--> before the </body> tag.

6. In your script(s) define HEAD_INCLUDE and BODY_INCLUDE ( optional ), ex:
 

$head_include ='<link rel="canonical" href="http://example.com/tags/" />';

define( 'HEAD_INCLUDE', $head_include );

Do the same thing for BODY_INCLUDE if needed.

Hope this helps.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...