0

I created a meta-box with an input field in the settings sidebar of pages. Now I try to save the value, but it does not work. Maybe the problem is, that I try to do this with pages and not with posts. The documentation only shows it for posts. How does it work with pages instead? I tried a lot but it doesn't work.

This is my code in functions.php:

add_action( 'add_meta_boxes_page', function()
{
    add_meta_box(
        'j-meta-box', 
        __( 'Zusätzliche Seiten-Attribute' ),
        'j_meta_box_cb',
        'page', 
        'side', 
        'low'
    );
} );
 
function j_meta_box_cb( $post )
{
    $value = get_post_meta( $post->ID, 'j-icon', true );
    //$value = get_post_meta( $post[->ID], 'icon', true );
    ?>
   
                <input
                  id="j-meta-box"
                  type="text"
                  value="<?php echo esc_attr( $value ) ?>"
                ></input>
<?php
}
 
add_action( 'save_post_page', function( $post_id ) {
update_post_meta(
$post_id,
'j-icon',
$_POST['j-icon']
);
 
});

If I write the string directly in the code like shown in the code below, the value get saved. But it does not work with the input value:

add_action( 'save_post_page', function( $post_id ) {
update_post_meta(
$post_id,
'j-icon',
'test'
);
 
});

I'm very thankful for your time!

1 Answer 1

0

You have forgot to add name of the input box so kindly modify your code for meta box creation as below

function j_meta_box_cb( $post )
{
    $value = get_post_meta( $post->ID, 'j-icon', true );
    
    ?>
   
  <input id="j-meta-box" type="text" name="j-icon"value="<?php echo esc_attr( $value ) ?>"></input>
<?php
} 

Let me know still if you hv any queries.

1
  • Thank you so much! That fixed it.
    – Jessi
    Commented Jul 17, 2023 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.