Print shortcode in custom action hook not where the shortcode is entered

I think I’d use a meta box:

// create the meta box
function dht_box() {
    add_meta_box(
        'dht_box', // id, used as the html id att
        __( 'Do Header Thing' ), // meta box title
        'dht_cb', // callback function, spits out the content
        'post' // post type or page. This adds to posts only
    );
}
function dht_cb($post) {
  $meta = get_post_meta($post->ID,'do_header_thing',true);
  echo '<input type="checkbox" name="do_header_thing" ',checked($meta),' />';
}
add_action( 'add_meta_boxes', 'dht_box' );

// save the data
add_action(
  'save_post',
  function ($post_id) {
    if (isset($_POST['do_header_thing'])) {
      add_post_meta($post_id,'do_header_thing',true);
    } else {
      delete_post_meta($post_id,'do_header_thing',true);
    }
  }
);

Then, in your template file or on an appropriate hook use:

if (is_single()) {
  $obj = get_queried_object();
  $dht = get_post_meta($obj->ID,'do_header_thing',true);
  if (!empty($dht)) { 
    echo 'Yay';
  }
}

Very crude code but that should give you the idea.

Leave a Comment