douyan1972 2015-02-26 19:50
浏览 30
已采纳

附件上传时自动分类

Lets say the media library has the following category [news, events, photo, page, post]

Your wordpress also has the above 5 set as post-type. What I want is when

1- Events -> Add New
2- File is uploaded while adding a new events post-type
3- File Finished uploading, wordpress should automatically attach events category for that attachment file.

I have code to update the category to a set value after upload, but could not find the currently editing post-type when running this function.

adds category 3 to the uploaded file

 function add_category_automatically($post_ID) {
            wp_set_object_terms($post_ID, array(3) or 'cat_slug_goes_here', 'category', true);
    }
    add_action('add_attachment', 'add_category_automatically');

gets currently editing post-type via ID (this displays correctly)

add_action( 'admin_init', 'do_something_152677' );
function do_something_152677() {
    // Global object containing current admin page
    global $pagenow;
    // If current page is post.php and post isset than query for its post type
    if ('post.php' === $pagenow && isset($_GET['post'])) {
        global $new_current_post_type;
        $new_current_post_type = get_post_type( $_GET['post'] );
    }
}

When pulling this value into cat_slug_goes_here the category does not get updated because the value doesn't match.

  • 写回答

1条回答 默认 最新

  • douxin5953 2015-02-26 22:05
    关注

    If the image is uploaded when creating the event using the "Add Media" function of the editor, then it should be associated with the original post by the time the action hook runs.

    You can then:

    function add_category_automatically($post_ID) {
        $attach = get_post($post_ID);
        if ($attach->post_parent) {
            $cats = get_the_category()($attach->post_parent);
            foreach ($cats as $cat) {
                wp_set_object_terms($post_ID, $cat->slug, 'category', true);
            }
        }
    }
    add_action('add_attachment', 'add_category_automatically');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度