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



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

我们想要显示";由";在管理后台的每个产品编辑页面和优惠券等。为此,我写了下面的代码。基础知识来自如何在Wordpress的"发布"框中的编辑文章页面中添加字段在WooCommerce管理员优惠券列表中添加一个带有作者名称的新列

此代码正在完全工作!

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

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’。另外CCD_ 2替换旧的CCD_;创建者:";标签应该是可翻译的。

所以在你的代码中:

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

最新更新