gpt4 book ai didi

php - 以编程方式添加带有附件的 Wordpress 帖子

转载 作者:可可西里 更新时间:2023-11-01 12:35:12 30 4
gpt4 key购买 nike

我在 $_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_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/

关于php - 以编程方式添加带有附件的 Wordpress 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3805603/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com