Skip to content

Instantly share code, notes, and snippets.

@damianwajer
Last active April 17, 2018 10:46
Show Gist options
  • Save damianwajer/f6d2728aeacb33ad7c73 to your computer and use it in GitHub Desktop.
Save damianwajer/f6d2728aeacb33ad7c73 to your computer and use it in GitHub Desktop.
[WordPress] Conditional Meta Box / Custom fields depending on page template in WP Admin
jQuery( document ).ready( function ( $ ) {
var $pageTemplate = $( "#page_template" ),
$metaBoxID = $( "#meta_box_id" );
$pageTemplate.on( "change", function () {
if ( $( this ).val() == "templates/page-custom.php" ) {
$metaBoxID.show();
} else {
$metaBoxID.hide();
}
}).change();
});
<?php
/**
* Run code in WP Admin depending on page template
*/
if ( isset( $_GET['post'] ) ) {
$post_id = intval( $_GET['post'] );
} elseif (isset( $_POST['post_ID'] ) ) {
$post_id = intval( $_POST['post_ID'] );
} else {
$post_id = 0;
}
if ( get_post_meta( $post_id, '_wp_page_template', true ) == 'templates/page-custom.php' ) {
// This code will run only on pages with page-custom.php template
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment