(english is not my language so I'm sorry if I don't explain really good)
My custom plugin get an URL from custom metabox and add it into the header.php
My problem is that I can't get $post_id
in my wp_head
function to insert the URL in the header (all works fine before this).
Add my code from my custom plugin:
add_action( 'add_meta_boxes', 'extra_metabox' );
function extra_metabox () {
add_meta_box( 'extra-metabox', 'Extra Meta Box', 'extra_create_mb', array('page','post'), 'normal', 'core' );
}
function extra_create_mb( $post ){
wp_nonce_field( 'wpe_extra_nonce_save', 'wpe_extra_nonce' );
$meta_alternate = get_post_meta( $post->ID, 'extra_meta_alternate', true );
$html=
'<table width="100%">
<tr>
<td style="width: 20%" valign="top"><label for="extra_meta_alternate">'.__('Alternate', 'extra_custom_alternate_redirect').'</label></td>
<td>
<input type="url" id="extra_meta_alternate" name="extra_meta_alternate" pattern="https://.*" value="' . esc_attr( $meta_alternate ) . '" style="width: 100%;">
</td>
</tr>
</table>';
function extra_save_mb( $post_id ) {
$nonce_name = isset( $_POST['wpe_extra_nonce'] ) ? $_POST['wpe_extra_nonce'] : '';
$nonce_action = 'wpe_extra_nonce_save';
if ( ! isset( $nonce_name ) ) {
return;
}
if ( ! wp_verify_nonce( $nonce_name, $nonce_action ) ) {
return;
}
if ( wp_is_post_revision( $post_id ) ) {
return;
}
update_post_meta( $post_id, 'extra_meta_alternate', sanitize_text_field($_POST['extra_meta_alternate'] ) );
}
add_action( 'save_post', 'extra_save_mb' );
function extra_head(){
//global $post;
$meta_alternate = get_post_meta( $post->ID, 'extra_meta_alternate', true );
//$meta_alternate = get_post_meta( $post_id, 'extra_meta_alternate', true );
//$meta_alternate = get_post_meta( get_the_ID(), 'extra_meta_alternate', true );
if ( is_page() || is_single() ){
echo '<link rel="alternate" media="only screen and (max-width:400px)" href="'.$meta_alternate.'" />';
}
}
add_action ('wp_head', 'extra_head');
But in <head></head>
only print:
<link rel="alternate" media="only screen and (max-width: 400px)" href="">
Also I try to add global $post
inside extra_head()
or get_the_ID()
but didn't work.
I'm relatively new with this, so thanks for the help.