Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress - Adding custom field to the post screen

Tags:

wordpress

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,

like image 904
BigJobbies Avatar asked May 01 '11 19:05

BigJobbies


1 Answers

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.

like image 62
Chris_O Avatar answered Oct 04 '22 23:10

Chris_O