Skip to main content
edited tags
Link
fuxia
  • 107.1k
  • 38
  • 255
  • 459
Source Link

Saving custom input from settings sidebar of pages in Wordpress

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!