php - 在 "created by"框中为每个产品和优惠券等添加 "post_submitbox_misc_actions"

标签 php wordpress woocommerce user-data author

我能够编写一个运行良好的代码!我只是想知道这段代码是否具有良好的质量或者我是否可以做得更好。

我们希望在管理后端的每个产品编辑页面和优惠券等上显示“创建者”。为此,我编写了下面的代码。基础知识来自 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>';     
        }      
    }   
}

关于php - 在 "created by"框中为每个产品和优惠券等添加 "post_submitbox_misc_actions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65656912/

相关文章:

javascript - AngularJs $http 在页面加载时发布

php - 比较多维数组中的两个 DATETIME 字段并返回值或索引

javascript - 动态背景颜色变化

html - 社交媒体粘性垂直对齐

css - 在移动设备上实现 2 列 - Woocommerce

php - Woocommerce - 禁用变体选择时的图像更改

php - 用于递归结果的 Laravel 查询构建器?例如。 id, parent_id

php - 在服务器子文件夹中移动 Laravel 5 应用程序

php - 为什么 nav 在 Wordpress 的内部静态页面上不起作用

php - 在 Woocommerce 中购买某个产品类别的产品时重定向