5

利用代码实现WordPress后台添加自定义批量操作文章功能

 2 years ago
source link: https://www.huhexian.com/21731.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

利用代码实现WordPress后台添加自定义批量操作文章功能

2022-01-0613:39:39评论

默认 WordPress 后台文章批量操作中,只有编辑和移动到回收站,可以按文本方法添加自定义批量操作选项,例如添加批量将文章改为草稿和自动为选中的文章添加自定义字段和值。将下面代码添加到当前主题函数模板 functions.php 中,最终效果:

利用代码实现WordPress后台添加自定义批量操作文章功能第一步:在批量操作下拉列表中添加选项。
  1. // 在批量操作下拉列表中添加选项
  2. add_filter( 'bulk_actions-edit-post', 'zm_my_bulk_actions' );
  3. function zm_my_bulk_actions( $bulk_array ) {
  4. $bulk_array['zm_make_draft'] = '状态改为草稿';
  5. $bulk_array['zm_set_price'] = '添加自定义字段 ';
  6. return $bulk_array;

默认是为文章添加自定义批量操作,页面、评论、媒体等,可以将代码中的:bulk_actions-edit-post 改为:

  1. 为页面添加批量操作,请使用:bulk_actions-edit-page
  2. 自定义文章类型:bulk_actions-edit-{CPT NAME}
  3. 自定义分类法:bulk_actions-edit-{TAXONOMY NAME}
  4. 评论:bulk_actions-edit-comments
  5. 插件:bulk_actions-plugins
  6. 用户:bulk_actions-users
  7. 媒体:bulk_actions-upload

第二步:添加处理动作

  1. // 处理执行
  2. add_filter( 'handle_bulk_actions-edit-post', 'zm_bulk_action_handler', 10, 3 );
  3. function zm_bulk_action_handler( $redirect, $doaction, $object_ids ) {
  4. $redirect = remove_query_arg( array( 'zm_make_draft_done', 'zm_bulk_price_changed' ), $redirect );
  5. // 改为草稿
  6. if ( $doaction == 'zm_make_draft' ) {
  7. foreach ( $object_ids as $post_id ) {
  8. wp_update_post( array(
  9. 'ID' => $post_id,
  10. 'post_status' => 'draft'// 草稿
  11. $redirect = add_query_arg( 'zm_make_draft_done', count( $object_ids ), $redirect );
  12. // 添加自定义字段
  13. if ( $doaction == 'zm_set_price' ) {
  14. foreach ( $object_ids as $post_id ) {
  15. update_post_meta( $post_id, 'product_price', 1000 );// 自定义字段名称:product_price,值:1000
  16. $redirect = add_query_arg( 'zm_bulk_price_changed', count( $object_ids ), $redirect );
  17. return $redirect;

第三步:添加处理后的提示文字

  1. // 添加提示文字
  2. add_action( 'admin_notices', 'zm_bulk_action_notices' );
  3. function zm_bulk_action_notices() {
  4. // 改为草稿
  5. if ( ! empty( $_REQUEST['zm_make_draft_done'] ) ) {
  6. echo '<div id="message" class="updated notice is-dismissible">
  7. <p>文章状态已更新。</p>
  8. </div>';
  9. // 添加自定义字段
  10. if( ! empty( $_REQUEST['zm_bulk_price_changed'] ) ) {
  11. printf( '<div id="message" class="updated notice is-dismissible"><p>' .
  12. _n( '有 %s 文章添加了价格自定义字段。',
  13. '有 %s 文章添加了价格自定义字段。',
  14. intval( $_REQUEST['zm_bulk_price_changed'] )
  15. ) . '</p></div>', intval( $_REQUEST['zm_bulk_price_changed'] ) );

上面代码只起个抛砖引玉的作用,具体怎么使用,发挥你的想像力吧。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK