【问题标题】:Programmatically adding Wordpress post with attachment以编程方式添加带有附件的 Wordpress 帖子
【发布时间】:2020-07-06 04:53:19
【问题描述】:

我在 $_REQUEST 以及一个图像文件中获得了 post_title、post_content 和其他内容。我想将所有这些作为帖子保存在 wordpress 数据库中。我的页面上有

<?php
require_once("wp-config.php");
$user_ID; //getting it from my function
$post_title = $_REQUEST['post_title'];
$post_content = $_REQUEST['post_content'];
$post_cat_id = $_REQUEST['post_cat_id']; //category ID of the post
$filename = $_FILES['image']['name'];

//I got this all in a array

$postarr = array(
 'post_status' => 'publish',
 'post_type' => 'post',
 'post_title' => $post_title,
 'post_content' => $post_content,
 'post_author' => $user_ID,
 'post_category' => array($category) 
 );
$post_id = wp_insert_post($postarr);

?>

这会将数据库中的所有内容作为帖子获取,但我不知道如何添加附件及其帖子元数据。

我该怎么做?有谁能够帮我?我真的很困惑,花了几天时间试图解决这个问题。

【问题讨论】:

  • 你应该包含 wp-load.php 而不是配置文件。

标签: php wordpress


【解决方案1】:

要添加附件,请使用 wp_insert_attachment():

https://developer.wordpress.org/reference/functions/wp_insert_attachment/

示例:

<?php
  $wp_filetype = wp_check_filetype(basename($filename), null );
  $attachment = array(
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
     'post_content' => '',
     'post_status' => 'inherit'
  );
  $attach_id = wp_insert_attachment( $attachment, $filename, 37 );
  // you must first include the image.php file
  // for the function wp_generate_attachment_metadata() to work
  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
  wp_update_attachment_metadata( $attach_id,  $attach_data );
?>

要添加元数据,请使用 wp_update_attachment_metadata():

https://developer.wordpress.org/reference/functions/wp_update_attachment_metadata/

【讨论】:

  • 我认为它只是从那个 url 复制粘贴.....你能告诉我如何在其中使用我的变量吗?它会通过请求将图像上传到 wp-content/uploads 吗??
  • $post_content 转到 post_content,$post_id 你从帖子插入中获得,等等...
【解决方案2】:

如果您需要上传附件并将其插入数据库,您应该使用media_handle_upload(),它将为您完成所有这些工作。你所要做的就是给它$_FILES数组中文件的索引和父帖子的ID:

$attachment_id = media_handle_upload( 'image', $post_id );
 
if ( is_wp_error( $attachment_id ) ) {
      // The upload failed.
} else {
      // The upload succeeded!
}

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多