文章目录
php

wordpress通过代码发布文章的核心代码

行云流水
2023-08-06 / 0 评论 / 224 阅读 / 正在检测是否收录...

前言

上篇文章分享了woocommerce通过代码添加商品的核心代码,稍微变通一下。woocommerce是wordpress下一款优秀的开源电商主题。那么其他主题可以使用吗?稍微修改了一下,用来自动发布wordpress文章。

核心代码

通过api接口接收文章数据,通过函数创建文章
if (($_SERVER['REQUEST_METHOD'] === 'POST') && preg_match("/pimport/i", $_SERVER['REQUEST_URI'])) {
    // 获取 POST 请求的原始数据
    $postData = file_get_contents('php://input');

    // 解码 JSON 数据为关联数组
    $jsonData = json_decode($postData, true);

    //打印日志
    //error_log(__METHOD__ . PHP_EOL .print_r($jsonData, true));

    // 使用 isset() 函数检查是否存在特定的表单字段
    if (isset($jsonData['unique_id']) && isset($jsonData['mall_info'])) {
        $unique_id = $jsonData['unique_id'];
        $mall_info = $jsonData['mall_info'];

        // 进一步处理接收到的数据
    // 虚拟商品名称
    if (array_key_exists('name', $mall_info)) {
        $name = $mall_info['name'];
    } else {
        exit('fail');
    }

    // 正文
    if (array_key_exists('content', $mall_info)) {
        $content = $mall_info['content'];
    } else {
        $content = '';
    }

    // 正文图片
    if (array_key_exists('imgs', $mall_info)) {
        $descimgs = $mall_info['imgs'];

        //下载图片并获取id列表
        $image_ids=download_and_import_imgs($mall_info['imgs']);
    }

    if (count($image_ids)>0) {
        foreach ($image_ids as $image_id) {
            // 获取新上传图片的 URL
            $new_image_url = wp_get_attachment_url($image_id);

            // 将新图片的 HTML 标记添加到描述中
            $new_image_html = '<img src="' . $new_image_url . '" alt="Product Image">';
            $content .= $new_image_html;
        }
    }

    // 关键词
        if (array_key_exists('keywords', $mall_info)) {
                $keywords = $mall_info['keywords'];
        } else {
                $keywords = '';
        }

    // 描述
    if (array_key_exists('desc', $mall_info)) {
                $desc = $mall_info['desc'];
        } else {
                $desc = '';
        }


    // 文章分类
    $table_name = $wpdb->prefix . 'batch_upload_job';
    $query = $wpdb->prepare("SELECT category FROM $table_name WHERE unique_id = %s", $unique_id);
    $category = $wpdb->get_var($query);
    $category_ids = array($category,);

    $post = array(
            'post_title'    => $name,         // 设置文章标题
            'post_content'  => $content,         // 设置文章内容
            'post_status'   => 'pending',         // 设置文章状态为发布
            'post_author'   => 5,             // 设置文章作者ID
            'post_category' => $category_ids,     // 设置文章分类(可选)
        'meta_input' => array(
            'post_titie' => $name,
                'keywords' => $keywords,
                'description' => $desc
            )
    );

    // 创建
    $post_id = wp_insert_post($post);

    exit('success');
    } else {
    #失败
    exit('fail');
    }
}

上一篇:
woocommerce通过代码添加商品之核心代码

评论 (0)

取消
只有登录/注册用户才可评论