如何以编程方式将图像添加到帖子中?

时间:2018-12-30 作者:Matthew Brown aka Lord Matt

我正在把我以前的NucleusCMS博客转换成WordPress。我已经在本地创建了一组表,并开始了转换过程。“我一直都很好,一直到图像”;转换;。我想我可以使用this answer. 在那之后,我有点迷路了。

我想做的是,刚刚以编程方式添加了一个媒体项(图片),然后通过编程方式将该图像添加到一个特定的帖子中,其中包含我刚刚从源代码中提取的维度和alt文本(通过regex)。

第1步。我需要为新添加的媒体获取指针或id或其他信息

我不完全知道我在用WordPress自己做什么,所以我不知道如何处理我刚刚添加的媒体。

第2步。我需要把这张照片作为帖子的一部分

至于我如何以WordPress本机使用的任何格式将其添加到帖子中(大小合适)。。。

这两个步骤我都需要帮助

2 个回复
SO网友:Faham Shaikh

嘿,我使用了类似的代码(我还下载了远程图像并上传到WordPress网站)。请看一下:

$image_url = $value;//This is the sanitized image url.
$image = pathinfo($image_url);//Extracting information into array.
$image_name = $image[\'basename\'];
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$unique_file_name = wp_unique_filename($upload_dir[\'path\'], $image_name);
$filename = basename($unique_file_name);
$postarr = array(
    \'post_title\' => $post_title,
    \'post_content\' => $post_content,
    \'post_type\' => \'post\',//or whatever is your post type slug.
    \'post_status\' => \'publish\',
    \'meta_input\' => array(
        //If you have any meta data, that will go here.
    ),
);
$insert_id = wp_insert_post($postarr, true);
if (!is_wp_error($insert_id)) {
    if ($image != \'\') {
        // Check folder permission and define file location
        if (wp_mkdir_p($upload_dir[\'path\'])) {
            $file = $upload_dir[\'path\'] . \'/\' . $filename;
        } else {
            $file = $upload_dir[\'basedir\'] . \'/\' . $filename;
        }
        // Create the image  file on the server
        file_put_contents($file, $image_data);
        // Check image file type
        $wp_filetype = wp_check_filetype($filename, null);
        // Set attachment data
        $attachment = array(
            \'post_mime_type\' => $wp_filetype[\'type\'],
            \'post_title\' => sanitize_file_name($filename),
            \'post_content\' => \'\',
            \'post_status\' => \'inherit\',
        );
        // Create the attachment
        $attach_id = wp_insert_attachment($attachment, $file, $insert_id);
        // Include image.php
        require_once ABSPATH . \'wp-admin/includes/image.php\';
        // Define attachment metadata
        $attach_data = wp_generate_attachment_metadata($attach_id, $file);
        // Assign metadata to attachment
        wp_update_attachment_metadata($attach_id, $attach_data);
        // And finally assign featured image to post
        $thumbnail = set_post_thumbnail($insert_id, $attach_id);
    }
}

SO网友:Antti Koskinen

基于对相关问题的公认答案,我认为类似的方法可能会奏效。

所以基本上,

获取现有帖子内容get_post_fieldwp_insert_attachment 这将为您提供图像ID,从帖子内容中获取图像大小和altwp_get_attachment_image

  • 用新图像html替换旧图像占位符当所有图像占位符都替换为img标记时,使用将修改后的帖子内容保存到DBwp_update_post
  • 可以选择将任何图像设置为后期缩略图/特色图像set_post_thumbnail.

    $post_id = 1234;
    $images = array(\'filename1.png\', \'filename2.png\', ... \'filename10.png\');
    
    // Get post content
    $post_content = get_post_field( \'post_content\', $post_id );
    
    // Get the path to the upload directory.
    $wp_upload_dir = wp_upload_dir();
    
    foreach($images as $name) {
      $attachment = array(
        \'guid\'=> $wp_upload_dir[\'url\'] . \'/\' . basename( $name ), 
        \'post_mime_type\' => \'image/png\',
        \'post_title\' => \'my description\',
        \'post_content\' => \'my description\',
        \'post_status\' => \'inherit\'
      );
    
      /**
        * STEP 1
        * add images as attachments to WordPress
        */
      $image_id = wp_insert_attachment($attachment, $name, $post_id);
      // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
      require_once( ABSPATH . \'wp-admin/includes/image.php\' );
      // Generate the metadata for the attachment, and update the database record.
      $attach_data = wp_generate_attachment_metadata( $image_id, $name );
      wp_update_attachment_metadata( $image_id, $attach_data );
    
      /**
        * STEP 2
        * Grab image data from $post_content
        */
      // strpos() + substr() maybe?
      $width = 123;
      $height = 123;
      $alt = \'Hello\';
    
      /**
        * STEP 3
        * get html markup for image
        */  
      // Let WP generate the html markup for the image, adjust size as needed (thumbnail,medium,large,full,array(width,height))
      $image_html = wp_get_attachment_image( $image_id, array( $width, $height ), false, array( \'alt\' => $alt ) );
    
      /**
        * STEP 4
        * Replace placeholders in content with img markup
        */
      preg_replace( $pattern, $image_html, $post_content ) // I don\'t understand regex well enough to give an example, so you need to figure it out yourself
    
      /**
        * OPTIONAL
        * set image as featured
        */
      if ( $name === \'example\' ) {
        set_post_thumbnail( $post_id, $image_id );
      }
    
    }
    
    /**
      * STEP 5
      * Update post content
      */
    $post_with_imported_images = array(
      \'ID\'           => $post_id,
      \'post_content\' => $post_content,
    );
    wp_update_post( $post_with_imported_images );
    
    EDIT 这应该是可行的,也许只需稍加调整,至少在经典编辑器中是这样。我对古腾堡不太确定,因为我没怎么研究它。

    相关推荐

    get_posts custom field

    这是一个愚蠢的问题,但我找不到合适的方式问谷歌。所以,如果这是一个重复的问题,很抱歉。我提供了一个带有复选框的自定义字段,用户可以检查是否希望此特定帖子进入主页。因此,在我的主页上,我呼吁所有已激活选中的帖子。我正在为自定义帖子类型CV创建自定义字段:function add_custom_post_meta_box() { add_meta_box( \'custom_post_meta_box\', // $id \'Campos Per