Wordpress - Adding custom field to the post screen

前端 未结 1 1719
失恋的感觉
失恋的感觉 2021-02-20 10:44

I was wondering if its possible to add a little box, like the \'excerpt\' box to all posts in wordpress so that i can enter a URL.

Cheers,

相关标签:
1条回答
  • 2021-02-20 11:29

    You can use the add_meta_box function. You also need a callback function that outputs the form html on the post screen and a save function.

    Here is a basic example that adds a URL meta box to lower right hand side of the post screen.

    add_action( 'add_meta_boxes', 'c3m_sponsor_meta' );
            function c3m_sponsor_meta() {
                    add_meta_box( 'c3m_meta', 'Sponsor URL Metabox', 'c3m_sponsor_url_meta', 'post', 'side', 'high' );
                    }
    
                function c3m_sponsor_url_meta( $post ) {
                    $c3m_sponsor_url = get_post_meta( $post->ID, '_c3m_sponsor_url', true);
                    echo 'Please enter the sponsors website link below';
                    ?>
                    <input type="text" name="c3m_sponsor_url" value="<?php echo esc_attr( $c3m_sponsor_url ); ?>" />
                    <?php
            }
    
    add_action( 'save_post', 'c3m_save_project_meta' );
            function c3m_save_project_meta( $post_ID ) {
                global $post;
                if( $post->post_type == "post" ) {
                if (isset( $_POST ) ) {
                    update_post_meta( $post_ID, '_c3m_sponsor_url', strip_tags( $_POST['c3m_sponsor_url'] ) );
                }
            }
            }
    

    Edit: Corrected namespace error in code above.

    0 讨论(0)
提交回复
热议问题