问题与WordPress的帖子PHP,如何显示图像?

cld4siwp  于 2023-05-05  发布在  PHP
关注(0)|答案(1)|浏览(109)

我有代码,我应该从API检索数据,并显示在wordpress的帖子。我已经面临的问题,以显示后的图像作为特色图像我不好与php,所以我认为我做了一些错误的代码

function my_function()
{
    $data = file_get_contents("http://datastorageuniversal.com/profiles_data");
    $response = json_decode($data, true);
    $item = $response['data'][0];
    $post_title = $item['name'];

    $address = $item["address"];
    $zip_city = $item["zip_city"];
    $race = $item["race"];
    $sex = $item["sex"];
    $eyes = $item["eyes"];
    $hair = $item["hair"];
    $height = $item["height"];
    $weight = $item["weight"];
    $bildate = $item["bildate"];
    $biltime = $item["biltime"];
    $hair = $item["hair"];
    $Charges = $item["Charges"];
    $image_url = $item['image_url'];
    $name = "ASLYN SMITH";
    $category_id = get_cat_ID('Arrests');
    $name_parts = explode(' ', $name);
    $last_name = array_pop($name_parts);
    $first_name = implode(' ', $name_parts);
    $new_name = $first_name . ', ' . $last_name;
    foreach ($Charges as $charges) {
        $description = $charges['description'];
        $charge_start = $charges['charge_start'];
        $charge_end = $charges['charge_end'];
        $department = $charges['department'];
        $court = $charges['court'];
        $date = $charges['date'];
        $time = $charges['time'];
        $bond = $charges['bond'];
        $image_path = WP_CONTENT_DIR . '/uploads/' . basename($image_url);
        file_put_contents($image_path, file_get_contents($image_url));

        // Create attachment post for the image
        $attachment = array(
            'guid' => $image_path,
            'post_mime_type' => mime_content_type($image_path),
            'post_title' => basename($image_path),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        $attachment_id = wp_insert_attachment($attachment, $image_path);

        // Set the post's featured image

        $post_content = "$image_path<br>Name: $name\nAddress: $address\nZip City: $zip_city\nRace: $race\nSex: $sex\nEyes: $eyes\nHair: $hair\nHeight: $height\nWeight: $weight\nBirth Date: $bildate\nBirth Time: $biltime\nCharges: \nDescription: $description\nCharge start: $charge_start\nCharge end: $charge_end\nDepartment: $department\nCourt: $court\nDate: $date\nTime: $time\nBond: $bond";

        // Check if post already exists for current data
        $existing_post_id = get_posts(array(
            'meta_key' => 'data_hash',
            'meta_value' => md5(json_encode($item)),
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => 1,
            'fields' => 'ids'
        ));

        if (!empty($existing_post_id)) {
            // Post already exists, update post content
            $new_post_id = $existing_post_id[0];
            $new_post = array(
                'ID' => $new_post_id,
                'post_title' => $post_title,
                'post_content' => $post_content,
                'post_status' => 'publish',
                'post_author' => 1, // replace with your desired author ID
                'post_type' => 'post', // replace with your desired post type
                'post_category' => implode(',', array($category_id))
            );

            wp_update_post($new_post);
            set_post_thumbnail($new_post_id, $attachment_id);
        } else {
            // Post does not exist, create new post
            $new_post = array(
                'post_title' => $post_title,
                'post_content' => $post_content,
                'post_status' => 'publish',
                'post_author' => 1, // replace with your desired author ID
                'post_type' => 'post', // replace with your desired post type
                'post_category' => array($category_id)
            );
            $new_post_id = wp_insert_post($new_post);

            // Save data hash as custom field to check for duplicates
            update_post_meta($new_post_id, 'data_hash', md5(json_encode($item)));
        }
    }
}
add_action('init', 'my_function');

我试图在$post_conent上显示它们为img src=,但在这种情况下,我在控制台上得到404错误,

lymgl2op

lymgl2op1#

这里首先你必须做wp_insert_post和你需要传递给附件的ID作为标签到该帖子。
也有几个条件,而上传到WP媒体。你必须检查实际的文件不应该上传重复。所以你可以存储附件的外部url,然后用meta_query重新检查。

试试下面的代码

if (!filter_var($url, FILTER_VALIDATE_URL) ||  empty($post_id)) {
    return;
}

// Add Featured Image to Post
$image_url         = preg_replace('/\?.*/', '', $url); // removing query string from url & Define the image URL here
$image_name       = basename($image_url);
$upload_dir       = wp_upload_dir(); // Set upload folder
$image_data       = file_get_contents($url); // Get image data
$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name); // Generate unique name
$filename         = basename($unique_file_name); // Create image file name

// Check folder permission and define file location
if (wp_mkdir_p($upload_dir['path'])) {
    $file = $upload_dir['path'] . '/' . $filename;
} else {
    $file = $upload_dir['basedir'] . '/' . $filename;
}

// Create the image  file on the server
file_put_contents($file, $image_data);

// Check image file type
$wp_filetype = wp_check_filetype($filename, null);

// Set attachment data
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => sanitize_file_name($filename),
    'post_content'   => '',
    'post_status'    => 'inherit'
);

// Create the attachment
$attach_id = wp_insert_attachment($attachment, $file, $post_id);
update_post_meta($attach_id, 'feed_external_url', $url, true);

// And finally assign featured image to post
set_post_thumbnail($post_id, $attach_id);

// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');

// Define attachment metadata
$attach_data = wp_generate_attachment_metadata($attach_id, $file);

// Assign metadata to attachment
wp_update_attachment_metadata($attach_id, $attach_data);

相关问题