Skip to content

Instantly share code, notes, and snippets.

@kosmiq
Created April 16, 2015 20:39
Show Gist options
  • Save kosmiq/33ccc6a38fe5644de299 to your computer and use it in GitHub Desktop.
Save kosmiq/33ccc6a38fe5644de299 to your computer and use it in GitHub Desktop.
WordPress: Display custom Meta box on specific page template only
/*awesome tip from http://www.paulund.co.uk/display-post-meta-box-specific-page-templates*/
add_action('add_meta_boxes', 'add_product_meta');
function add_product_meta()
{
global $post;
if(!empty($post))
{
$pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);
if($pageTemplate == 'page-templates/product-page.php' )
{
add_meta_box(
'product_meta', // $id
'Product Information', // $title
'display_product_information', // $callback
'page', // $page
'normal', // $context
'high'); // $priority
}
}
}
function display_product_information()
{
// Add the HTML for the post meta
}
Copy link

ghost commented Jul 18, 2018

Hello Kosmiq,
Great job!
I just can not save these fields.

I'm trying to use something like:

function save_meta_page( $post_id ) {
$pageTemplate = get_post_meta($post_id, '_wp_page_template', true);

                if($pageTemplate == 'templates/mytemplate.php' ){
    if( isset($_POST['my_meta_value']) ) {
	update_post_meta( $post_id, 'my_meta_value', sanitize_text_field( $_POST['my_meta_value'] ) );
 }
 }

}
add_action('save_post', 'save_meta_page', 9999, 1);

How do I save these fields to the specific template?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment