• 300

    ONL

  • 345

    TOIP

  • 521

    TOPV

  • 21

    MEM

  • 11

    YESIP

  • 108

    YESPV


其他 拼.音 域名推介:She.Lu Chao.Ma Hua.Nu Qiu.Bi Hai.Ci Last.City
分类:常用—格子老师知识手册汇编—前路文库

分类:常用

2020年10月14日 23:26更新

分类:常用

漫川 常用 24
WP博客实现上传媒体自动发布文章WP博客实现上传媒体自动发布文章
2天前
代码
评论(3)
前言:好长时间没水文章了,给大家分享一个最近研究出来的上传媒体自动发布文章的方法。适用于做壁纸小程序的伙伴们。很方便的,只需要几行代码就可以了。给大家分享两个方法一个是可以自动设置特色封面的和不自动设置特色图片的

方法一(不带特色图片):
可以通过编写自定义代码来实现在上传媒体文件时自动发布文章的功能。具体的实现方法如下:

打开 WordPress 的主题文件夹,找到 functions.php 文件。
在 functions.php 文件中添加以下代码:
function auto_post_on_upload( $post_id ) {
if ( wp_is_post_revision( $post_id ) ) {
return;
}
$post_title = get_the_title( $post_id );
$post_content = get_post_field( 'post_content', $post_id );
$post_status = 'publish';
$post_type = 'post';
$post_category = array( 'category_name' => '默认分类' ); //设置默认分类
$post_tags = ''; //设置默认标签
$post_author = get_current_user_id();
$post_data = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => $post_status,
'post_type' => $post_type,
'post_category' => $post_category,
'tags_input' => $post_tags,
'post_author' => $post_author,
);
wp_insert_post( $post_data );
}
add_action( 'add_attachment', 'auto_post_on_upload' );
这段代码会在上传媒体文件时自动创建一个新的文章,并将上传的文件作为文章的特色图片。你可以根据自己的需求修改代码中的默认分类、标签等信息。

需要注意的是,自定义代码的实现需要一定的编程技能和经验,如果你不熟悉编程,建议使用插件来实现自动发布文章的功能。

方法二(自动特色图片):
要实现上传媒体文件自动发布文章并设置特色图片,您可以使用 WordPress 的 add_attachment 钩子和 wp_insert_post() 函数。

以下是一个示例代码片段,可以在上传媒体文件时自动发布文章并将上传的图像作为特色图片:

add_action( 'add_attachment', 'auto_publish_post_from_attachment' );
function auto_publish_post_from_attachment( $attachment_id ) {
// 获取上传的图像 ID
$image_id = $attachment_id;
// 获取图像的文件类型
$image_type = get_post_mime_type( $image_id );
// 如果上传的文件不是图像,则不自动发布文章
if ( strpos( $image_type, 'image' ) === false ) {
return;
}
// 获取要将文章发布到的分类 ID
$category_id = 1; // 这里假设文章要发布到 ID 为 1 的分类中
// 获取上传的图像的标题作为文章标题
$post_title = get_the_title( $image_id );
// 获取上传的图像的描述作为文章内容
$post_content = get_post_field( 'post_content', $image_id );
// 设置文章的默认分类、标签等信息
$post_category = array( $category_id );
$post_status = 'publish';
$post_type = 'post';
$post_author = get_current_user_id();
$post_tags = '';
// 创建文章对象
$post = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_category'=> $post_category,
'post_status' => $post_status,
'post_type' => $post_type,
'post_author' => $post_author,
'tags_input' => $post_tags,
);
// 插入文章
$post_id = wp_insert_post( $post );
// 如果文章插入成功,则将上传的图像设置为文章的特色图片
if ( $post_id ) {
set_post_thumbnail( $post_id, $image_id );
}
}
这段代码将在上传媒体文件时触发 add_attachment 钩子,然后获取上传的图像 ID 和文件类型。如果上传的文件不是图像,则不自动发布文章。如果上传的文件是图像,则获取要将文章发布到的分类 ID,以及上传的图像的标题和描述作为文章的标题和内容。然后,设置文章的默认分类、标签等信息,并使并使用 wp_insert_post() 函数插入文章。如果文章插入成功,则将上传的图像设置为文章的特色图片。

https://www.bena.cc/845.html
——《漫川
未知 常用 854
常用1-20套圈数字①、②、③、④、⑤、⑥、⑦、⑧、⑨、⑩、⑪、⑫、⑬、⑭、⑮、⑯、⑰、⑱、⑲、⑳。——《网络

返回首页


吐槽也是一种生活态度。

发表评论

电子邮件地址不会被公开。 必填项已用*标注