Php wordpress从图像上传创建帖子

Php wordpress从图像上传创建帖子,php,wordpress,Php,Wordpress,我有一些代码可以通过将图像上传到媒体库来创建帖子,这很好: add_action('add_attachment', 'create_post'); function create_post( $attach_ID ) { $attachment = get_post( $attach_ID ); $my_post_data = array( 'post_title' => $attachment->post_title, 'pos

我有一些代码可以通过将图像上传到媒体库来创建帖子,这很好:

add_action('add_attachment', 'create_post');
function create_post( $attach_ID ) {

$attachment = get_post( $attach_ID );

$my_post_data = array(
            'post_title' => $attachment->post_title,
            'post_type' => 'post',
            'post_category' => array('0'),
            'post_status' => 'publish'
);
$post_id = wp_insert_post( $my_post_data );

// attach media to post
wp_update_post( array(
    'ID' => $attach_ID,
    'post_parent' => $post_id,
) );

set_post_thumbnail( $post_id, $attach_ID );

return $attach_ID;
}
问题是,如果我手动创建帖子,我不希望它通过图片上传创建新帖子。换句话说,我希望代码仅在直接将图像上载到媒体库时创建新帖子,而不是在手动将图像添加到新帖子时创建新帖子


非常感谢您的帮助

也许有更好的方法,但您可以使用全局变量$pagenow

global $pagenow;
if($pagenow == 'upload.php'){
    //your code here
}

我从Wizpert的开发者那里得到了一些帮助。他使用下面的代码使它工作

add_action('add_attachment', 'create_post');

function create_post( $attach_ID ) {

$attachment = get_post( $attach_ID );

if(!$attachment->post_parent)
{
    $my_post_data = array(
    'post_title' => $attachment->post_title,
    'post_type' => 'post',
    'post_category' => array('0'),
    'post_status' => 'publish'
    );

    $post_id = wp_insert_post( $my_post_data );

    // attach media to post
    wp_update_post( array(
    'ID' => $attach_ID,
    'post_parent' => $post_id,
    ) );

    set_post_thumbnail( $post_id, $attach_ID );

    return $attach_ID;
}
}

你好,谢谢你的回复。我确实试过了,但运气不好。我在functions.php页面中这样做有关系吗?不,没有关系,我认为你的目标不太容易实现。。。默认情况下,Wordpress为您上载的每个媒体创建一个新的附件帖子类型。您的脚本将复制附件实体。如果我正确理解你的问题,你应该修改Wordpress的逻辑。