Friday, April 21, 2023

Create extra fields in page or post or custom post type

Hello.

Today I saw you how to add some extra fields in your post, page or custom post type. 

For example, you have to create social media links like facebook, instagram, twitter for consultant. 

Here I created 4 fields. I used consultant post type, which is my custom post type. You can use page or post also.

You have to put this code:

//new metabox for consultant type
function wporg_add_custom_box() {
    $screens = [ 'consultant', 'wporg_cpt' ];
    foreach ( $screens as $screen ) {
        add_meta_box(
            'wporg_box_id',                 // Unique ID
            'Social Media Links Here',      // Box title
            'wporg_custom_box_html',  // Content callback, must be of type callable
            $screen                            // Post type
        );
    }
}
add_action( 'add_meta_boxes', 'wporg_add_custom_box' );
function wporg_custom_box_html( $post ) {
    $fblink = get_post_meta( $post->ID, 'metakey_facebook', true );
    $instalink = get_post_meta( $post->ID, 'metakey_insta', true );
    $twitterlink = get_post_meta( $post->ID, 'metakey_twitter', true );
    $pinrestlink = get_post_meta( $post->ID, 'metakey_pinrest', true );
    ?>
    <p> <label for="facebooklink">Facebook</label>
    <input type="text" name="facebooklink" id="facebooklink" value="<?php echo $fblink; ?>"></p>
    <p><label for="instalink">Instagram</label>
    <input type="text" name="instalink" id="instalink" value="<?php echo $instalink; ?>"></p>
    <p> <label for="twitterlink">Twitter</label>
    <input type="text" name="twitterlink" id="twitterlink" value="<?php echo $twitterlink; ?>"></p>
    <p><label for="pinrestlink">Pinrest</label>
    <input type="text" name="pinrestlink" id="pinrestlink" value="<?php echo $pinrestlink; ?>"></p>
    <?php
}
function wporg_save_postdata( $post_id ) {
    if ( array_key_exists( 'facebooklink', $_POST ) ) {
        update_post_meta(
            $post_id,
            'metakey_facebook',
            $_POST['facebooklink']
        );
    }
    if ( array_key_exists( 'instalink', $_POST ) ) {
        update_post_meta(
            $post_id,
            'metakey_insta',
            $_POST['instalink']
        );
    }
    if ( array_key_exists( 'twitterlink', $_POST ) ) {
        update_post_meta(
            $post_id,
            'metakey_twitter',
            $_POST['twitterlink']
        );
    }
    if ( array_key_exists( 'pinrestlink', $_POST ) ) {
        update_post_meta(
            $post_id,
            'metakey_pinrest',
            $_POST['pinrestlink']
        );
    }
}
add_action( 'save_post', 'wporg_save_postdata' );
//end consultant code


In this code you have to change "consultant" to "post" or "page" or any of your custom post type slug.

You have to change in this : $screens = [ 'consultant', 'wporg_cpt' ];



No comments:

Post a Comment