When adding custom post meta boxes, I understand that whatever name
attribute input
you put would be passed through the form into the server.
Hence, If I have
<input type="text" name="my_custom_field" id="my_custom_field" />
using
get_post_meta($post->ID, 'my_custom_field', true);
I am able to retrieve the value of that input
is possible.
Regarding this, I did some googling on how to target custom page templates and this was what I found.
global $post;
function func_name {
if ( 'foobar.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
do something...
}
}
add_action( 'add_meta_boxes_page', 'func_name' );
Where does _wp_page_template
come from?
I did a inspect on the WP backend edit page on the Page Attributes meta box but no fields have that key name on it. What boggles me is how _wp_page_template
also appears in the database wp_postmeta table.
Can anyone help me explain this?
Thanks in advance.
The HTML attribute
name
is what is sent to the server. There is some PHP code reading it and storing it with a specific key in the database.The HTML name and the database key donât have to be the same string. The PHP code can use a completely different name or split one value into multiple database values.
The template attribute handler does that: It takes the name
page_template
from page attributes metabox and stores it as_wp_page_template
in the database. The leading underscore protects that field from showing up in the custom fields metabox.See this part in
wp_insert_post()
:Saving data from a form is not automatic as you seem to think…
Yes, the form data will be passed to the server as either
POST
orGET
data but nothing happens to that data if it is not intentionally processed by the script. That often means saving to the database but not necessarily. You can email the data instead, as part of a contact form for example.The
name
attribute the form uses does not have to match the key saved to the database. The code that processes the form can save it it under any key the programmer wants.The particular piece of data you are talking about is processed by the
wp_insert_post
function inwp-includes/post.php
.