wordpress 添加post函数
时间 : 2023-12-31 23:26:02 声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

最佳答案

添加Post函数是通过WordPress提供的API来实现的。下面是一个简单的示例代码,演示了如何使用WordPress的REST API来添加一个帖子:

```php

<?php

$endpoint = 'https://your-wordpress-site/wp-json/wp/v2/posts';

$username = 'your-username';

$password = 'your-password';

// 设置请求头

$headers = array(

'Content-Type: application/json',

'Authorization: Basic ' . base64_encode($username . ':' . $password)

);

// 创建帖子的内容

$data = array(

'title' => 'My First Post',

'content' => 'This is the content of my first post.',

'status' => 'publish'

);

// 发送POST请求

$request = wp_remote_post($endpoint, array(

'headers' => $headers,

'body' => json_encode($data)

));

// 检查请求是否成功

$response_code = wp_remote_retrieve_response_code($request);

if ($response_code === 201) {

echo 'Post created successfully';

} else {

echo 'Failed to create post';

}

在上面的代码中,需要替换`https://your-wordpress-site`为你的WordPress网站地址,`your-username`和`your-password`为你的WordPress登录凭证。

这段代码使用了`wp_remote_post`函数发送POST请求,并使用`wp_remote_retrieve_response_code`函数获取请求的响应状态码。如果状态码为201,则表示帖子创建成功。

请注意,这只是一个简单的示例,实际使用中可能需要添加更多的错误处理和验证逻辑。同时,确保你的WordPress网站已经启用了REST API才能使用这种方式。

其他答案

要在WordPress中添加文章(Post),可以使用`wp_insert_post()`函数。以下是一个示例:

```php

// 创建文章数组

$new_post = array(

'post_title' => '新文章标题',

'post_content' => '这里是文章正文内容。',

'post_status' => 'publish',

'post_author' => 1,

'post_category' => array(1, 2) // 文章分类ID

);

// 插入文章

$post_id = wp_insert_post($new_post);

if ($post_id) {

echo '文章创建成功,文章ID为:' . $post_id;

} else {

echo '文章创建失败';

}

在上面的示例中,我们首先创建了一个包含新文章的相关信息的数组`$new_post`。然后,我们使用`wp_insert_post()`函数将该文章插入WordPress数据库。

在示例中,我们设置了文章的标题为"新文章标题",正文内容为"这里是文章正文内容。";文章状态为"publish",表示发布文章;作者ID为1,表示文章的作者是ID为1的用户;文章分类为ID为1和2的分类。

如果文章添加成功,`wp_insert_post()`函数将返回新文章的ID,并输出"文章创建成功,文章ID为:"加上文章ID。否则,将输出"文章创建失败"。

您可以根据需要自定义文章的其他属性,比如设置文章的标签、特色图像等。`wp_insert_post()`函数的参数和用法可以参考WordPress官方文档。