上载过程中仅针对帖子类型将WP附件名称更改为POSSID

时间:2016-01-09 作者:I Am Stack

我知道有很多解决方案,如何在上传文件到postid时重命名附件。我得到了真正有效的正确解决方案是:https://wordpress.stackexchange.com/a/30767/86517 (I\'m new and I can\'t comments there. So I ask this question.)

The code is:

add_action(\'add_attachment\', \'rename_attacment\');
function rename_attacment($post_ID){

    $post = get_post($post_ID);
    $file = get_attached_file($post_ID);
    $path = pathinfo($file);
        //dirname   = File Path
        //basename  = Filename.Extension
        //extension = Extension
        //filename  = Filename

    $newfilename = "NEW FILE NAME HERE";
    $newfile = $path[\'dirname\']."/".$newfilename.".".$path[\'extension\'];

    rename($file, $newfile);    
    update_attached_file( $post_ID, $newfile );

}
但问题是,我只想更改3种自定义帖子类型。目前我的网站有6个自定义帖子类型。所以只有3个自定义帖子类型需要这个。是否有任何方法允许仅针对那些自定义帖子类型运行此函数?

谢谢

2 个回复
最合适的回答,由SO网友:I Am Stack 整理而成

我真的很抱歉。我在发布这个问题几分钟后解决了我的问题。所以我在这里添加了我的工作代码,以便将来有人需要时提供帮助。

add_action(\'add_attachment\', \'rename_attacment\');

function rename_attacment($post_ID){
 if ( get_post_type( $_REQUEST[\'post_id\'] ) === \'post_type_1\' OR get_post_type( $_REQUEST[\'post_id\'] ) === \'post_type_2\' OR get_post_type( $_REQUEST[\'post_id\'] ) === \'post_type_3\' ){
    $post = get_post($post_ID);
    $file = get_attached_file($post_ID);
    $path = pathinfo($file);
        //dirname   = File Path
        //basename  = Filename.Extension
        //extension = Extension
        //filename  = Filename

    $newfilename = "NEW FILE NAME HERE";
    $newfile = $path[\'dirname\']."/".$newfilename.".".$path[\'extension\'];

    rename($file, $newfile);    
    update_attached_file( $post_ID, $newfile );
 }
}
谢谢大家。

SO网友:Prakash Rao

更简单(&A);开发人员友好的代码

add_action(\'add_attachment\', \'rename_attacment\');
    function rename_attacment($post_ID){

    //get post type
    $post_type = get_post_type($post_ID);

    //if not in allowed post types then return
    $allowed_post_types = array(\'post_1\',\'post_2\',\'post_3\');
    if(!in_array($post_type,$allowed_post_types)){
      return;
    }

        $post = get_post($post_ID);
        $file = get_attached_file($post_ID);
        $path = pathinfo($file);
            //dirname   = File Path
            //basename  = Filename.Extension
            //extension = Extension
            //filename  = Filename

        $newfilename = "NEW FILE NAME HERE";
        $newfile = $path[\'dirname\']."/".$newfilename.".".$path[\'extension\'];

        rename($file, $newfile);    
        update_attached_file( $post_ID, $newfile );

    }

相关推荐

如何在Functions.php中链接style.css

我是WordPress的新手;我刚开始学习WordPress。我想把风格联系起来。函数中的css。php,但我无法解决这里可能存在的问题。谁能给我指出正确的方向吗?指数php<?php get_header(); ?> <?php if ( have_posts() ) { while ( have_posts() ) { the_post();