P +886 90 537 8918 | E hello@bdigital.asia

Insights

WordPress Custom Head Tags

We recently had a client using WordPress for their company website that needed to include custom head tags that were fully customizable on a per-post basis.

There are a number of plugins available that will allow custom head tags and scripts but these are usually for the entire site. In some unique cases you might want to include a specific stylesheet, external script or meta tags for a specific post, and this was the case here.

There are a number of plugins available that will allow custom head tags and scripts but these are usually for the entire site. In some unique cases you might want to include a specific stylesheet, external script or meta tags for a specific post, and this was the case here.

This is an extremely simple single page customization so we are happy to share the plugin for everyone and you can find it on our GitHub over here.

For the developers out there, let's break down how the plugin works:

First we need to add the custom meta box to post (you could also expand this to add the custom meta to other custom post types you might have , i.e. Recipes)

function headtags_register_meta_boxes() {
      add_meta_box( 'headtags', __( 'Additional Head Tags', 'headtags' ), 'headtags_callback', 'post' );
}add_action( 'add_meta_boxes', 'headtags_register_meta_boxes' );function headtags_callback( $post ) {
      echo "<textarea name='headtags' id='headtags' style='width: 100%; height: 250px'>".stripslashes(urldecode(get_post_meta( get_the_ID(), 'headtags', true )))."</textarea>";
}

Next we needed to handle saving the custom meta data.

function header_save_meta_box( $post_id ) {
      if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
      if ( $parent_id = wp_is_post_revision( $post_id ) ) {
            $post_id = $parent_id;
      }
      $fields = [
           'headtags'
      ];
     foreach ( $fields as $field ) {
          if ( array_key_exists( $field, $_POST ) ) {
                update_post_meta( $post_id, $field, urlencode($_POST[$field]) );
          }
      }
}
add_action( 'save_post', 'header_save_meta_box' );

The third and final step is to make our custom tags appear on the frontend

function hook_headtags() {
       /* dont show on front page */
      if(is_front_page()){
             echo '<!--front-->'; /* or you could do nothing */
       } else {
             /* output custom header content */
             echo stripslashes(urldecode(get_post_meta( get_the_ID(), 'headtags', true )));
       }
}
add_action('wp_head', 'hook_headtags');

If you have found this article useful or you want to talk to us about more advanced WordPress customization then please get in touch with us for a free consultation.


Insights

The case for a common web platform for the public sector in Taiwan

 

Read More

A guide to flexible working

 

Read More

The Case Against Shopify

 

Read More