以编程方式将帖子元添加到附件

时间:2017-10-17 作者:Game Unity

我有一个为自定义帖子类型创建元键的函数。这对他们来说效果很好,但现在我想对attachment 岗位类型。

通常,它应与挂钩一起工作:add_action(\'add attachment\', \'bZive_generate_AlphanumericID\', 10, 3);

因为它与(这很有效!)几乎相同:
add_action(\'wp_insert_post\', \'bZive_generate_AlphanumericID\', 10, 3);

但由于某种原因,没有生成任何密钥(我在Posteta表中检查了我的db-也在正确的博客中…)

Here the full code

function bZive_generate_AlphanumericID( $post_id ) {

    $postTypes = array(\'profile\', \'article\', \'attachment\');
    $postType = get_post_type( $post_id );

    if (in_array( $postType, $postTypes ) and empty( get_post_meta( $post_id, \'alphanumeric_id\', true ) ) ) {


        $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ\'$§%&!";

        $charactersLength = strlen($characters);
        $randomString = \'\';
        for ($i = 0; $i < 13; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }


         /**
         * Now check here if the string is in the database
         */
        $args = array(
        \'post_type\'     =>  array(
                $postTypes 
            ),
        \'meta_query\'    =>  array(
            array(
                \'meta_key\'  =>  \'alphanumeric_id\'
            )
        )
        );
        $posts = new WP_Query( $args );


        $meta_values = \'\';
        if( $posts->have_posts() ) {
          while( $posts->have_posts() ) {
            $posts->the_post();

            $meta_values[] = get_post_meta( get_the_ID(), \'alphanumeric_id\', true );
          }
        } 
        wp_reset_postdata();


        if (in_array( $randomString, $meta_values )) {
            // "Match found"
            return generate_AlphanumericID;

        }  else {
            // "Match not found"
            add_post_meta($post_id, \'alphanumeric_id\', $randomString);
            return $randomString;

        }

    }

}
add_action(\'wp_insert_post\', \'bZive_generate_AlphanumericID\', 10, 3);
add_action(\'add attachment\', \'bZive_generate_AlphanumericID\', 10, 3);

1 个回复
最合适的回答,由SO网友:Jacob Peattie 整理而成

缺少下划线:

add_action(\'add attachment\', \'bZive_generate_AlphanumericID\', 10, 3);

需要:

add_action(\'add_attachment\', \'bZive_generate_AlphanumericID\', 10, 1);

我还将接受的参数数量更改为1, 因为add_attachment 只有1,并且您的回调函数仍然只使用1。

结束

相关推荐

how to edit attachments?

在将例如文件附加到帖子时,如何在事后编辑/删除它们?在帖子编辑器中找不到任何内容。谢谢