2

I was able to write a code which is working fine! I just had some question if this code has a good quality or if I can do it better.

We want to display "Created by" on every product edit page and coupon etc. in admin backend. For that, I wrote the code below. The basics are from How to add a field in edit post page inside Publish box in Wordpress? and Add a new column with author name to WooCommerce admin coupon list

This code is fully working!

But I'm not sure if it is clean code and want to learn.

add_action( 'post_submitbox_misc_actions', 'created_by' );

function created_by($post)
{
    // Author ID
    $author_id = get_post_field ( 'post_author', $post_id );
    
    // Display name
    $display_name = get_the_author_meta( 'display_name' , $author_id );
    
    if ( ! empty ( $display_name ) ) {
              echo '<div class="misc-pub-section misc-pub-section-last">
     <span id="timestamp"><label><b>Created by: </b></label>' . $display_name .'</span></div>';     
    }   
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Nik7
  • 346
  • 2
  • 16

1 Answers1

2

The variable $post_id is not defined and should be replaced by '$post->ID'. Also <strong> replace old <b> html tag and "Created by:" label should be translatable.

So in your code:

add_action( 'post_submitbox_misc_actions', 'created_by' );

function created_by( $post )
{
    // Get Author ID
    $author_id = get_post_field ( 'post_author', $post->ID );
    
    // Get Author Display name
    $display_name = get_the_author_meta( 'display_name' , $author_id );
    
    if ( ! empty ( $display_name ) ) {
        echo '<div class="misc-pub-section misc-pub-section-last">
           <span id="timestamp"><label><strong>' . __("Created by:", "woocommerce").' </strong></label>' . $display_name .'</span>
       </div>';     
    } 
}

It should better work.


Addition: To target only products and coupons, you should also add some conditions, like:

add_action( 'post_submitbox_misc_actions', 'created_by' );

function created_by( $post )
{
    global $typenow;

    if ( in_array( $typenow, array('product', 'shop_coupon') ) ) 
    {
        // Get Author ID
        $author_id = get_post_field ( 'post_author', $post->ID );
        
        // Get Author Display name
        $display_name = get_the_author_meta( 'display_name' , $author_id );
        
        if ( ! empty ( $display_name ) ) {
            echo '<div class="misc-pub-section misc-pub-section-last">
               <span id="timestamp"><label><strong>' . __("Created by:", "woocommerce").' </strong></label>' . $display_name .'</span>
           </div>';     
        }      
    }   
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399