在“post_submitbox_misc_actions”框中为每个产品和优惠券等添加“创建者”

问题描述

我能够编写一个运行良好的代码!我只是有一些疑问,如果这段代码质量很好,或者我是否可以做得更好。

我们希望在后台的每个产品编辑页面和优惠券等上显示“创建者”。为此,我编写了下面的代码。基础知识来自 How to add a field in edit post page inside Publish box in Wordpress?Add a new column with author name to WooCommerce admin coupon list

此代码完全有效!

但我不确定它是否是干净的代码并且想学习。

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>';     
    }   
}

解决方法

变量 $post_id 未定义,应替换为“$post->ID”。另外 <strong> 替换旧的 <b> html 标签,并且“创建者:”标签应该是可翻译的。

所以在你的代码中:

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>';     
    } 
}

它应该会更好地工作。


附加:要仅定位产品和优惠券,您还应该添加一些条件,例如:

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>';     
        }      
    }   
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...