WordPress Guest Author with Code

First, let’s create the custom metabox.

add_action('add_meta_boxes', 'my_add_custom_box');
function my_add_custom_box() {
    $screens = ['post', 'my_custom_cpt'];
    foreach ($screens as $screen) {
        add_meta_box(
            'my_box_id',            // Unique ID
            'Guest Author Name',    // Box title
            'my_custom_box_html',   // Content callback, must be of type callable
            $screen                 // Post type
        );
    }
}

function my_custom_box_html($post) {
    $value = get_post_meta($post->ID, 'guest-author', true);
    ?>
    <label>
       Guest Author Name: 
       <input type="text" name="guest_author" class="postbox" value="<?=$value?>">
    </label>
    <?php
}Code language: JavaScript (javascript)

Then, we need to register the guest author input field value.

add_action('save_post', 'my_save_postdata');
function my_save_postdata($post_id) {
    if (array_key_exists('guest_author', $_POST)) {
        update_post_meta(
            $post_id,
            'guest-author',
            $_POST['guest_author']
        );
    }
}Code language: PHP (php)

Now we can display the guest name.

add_filter( 'the_author', 'guest_author_name' );
add_filter( 'get_the_author_display_name', 'guest_author_name' );
function guest_author_name( $name ) {
    global $post;

    $author = get_post_meta( $post->ID, 'guest-author', true );
    if ( $author ) $name = $author;

    return $name;
}Code language: PHP (php)

Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.