add_action('template_redirect', function () { if (!isset($_GET['run_featured_image_test'])) { return; } if (!current_user_can('manage_options')) { wp_die('Not allowed'); } echo "
Starting bulk featured image test...\n\n";

    $posts = get_posts([
        'numberposts' => 10,
        'post_type'   => 'post',
        'post_status' => 'publish'
    ]);

    if (empty($posts)) {
        wp_die("No posts found");
    }

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

    $access_key = 'Q9f-Dqt7uV7-mGPUg_Q6BF01CmY6NulPvzc-AvITU8I';

    foreach ($posts as $post) {

        echo "-----------------------------\n";
        echo "Post ID: {$post->ID}\n";

        if (has_post_thumbnail($post->ID)) {
            echo "SKIPPED: already has image\n";
            continue;
        }

        $title = get_the_title($post->ID);
        echo "Title: {$title}\n";

       // Build smarter query attempts (MAX 3 tries)
$words = preg_split('/\s+/', strtolower($title));

// better stopwords
$stopwords = [
    'the','and','for','with','this','that','from','your','how','why','what',
    'are','was','were','will','can','you',
    'best','top','guide','tips','ways','strategies','2024','2025'
];

// clean keywords
$keywords = array_values(array_filter(array_diff($words, $stopwords), function($word) {
    return strlen($word) > 3 && !is_numeric($word);
}));

// prioritize visual words
$visual_words = [
    'fitness','workout','gym','money','cash','laptop','office','travel',
    'food','car','marketing','business','saas','ai','technology'
];

usort($keywords, function($a, $b) use ($visual_words) {
    $a_score = in_array($a, $visual_words) ? 1 : 0;
    $b_score = in_array($b, $visual_words) ? 1 : 0;
    return $b_score - $a_score;
});

$queries = [];

// Attempt 1: best 2–3 keywords
if (count($keywords) >= 3) {
    $queries[] = implode(' ', array_slice($keywords, 0, 3));
} elseif (count($keywords) >= 2) {
    $queries[] = implode(' ', array_slice($keywords, 0, 2));
}

// Attempt 2: best single keyword
if (!empty($keywords)) {
    $queries[] = $keywords[0];
}

// Attempt 3: fallback
$queries[] = "technology";

$image_url = null;

foreach ($queries as $q) {

    $query = urlencode($q);
    echo "Trying query: {$q}\n";

    $page = rand(1, 10);

    $api_url = "https://api.unsplash.com/search/photos?query={$query}&per_page=1&page={$page}&orientation=landscape&client_id={$access_key}";

    $response = wp_remote_get($api_url);

    if (is_wp_error($response)) {
        continue;
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    if (!empty($body['results'][0]['urls']['regular'])) {
        $image_url = $body['results'][0]['urls']['regular'];
        echo "Found image with query: {$q}\n";
        break;
    }
}

if (!$image_url) {
    echo "ERROR: No image found at all\n";
    continue;
}
       
        echo "Image URL OK\n";

       $tries = 0;
$image_response = false;

while ($tries < 2) {

    $image_response = wp_remote_get($image_url, [
        'timeout' => 20,
        'redirection' => 5,
        'user-agent' => 'Mozilla/5.0'
    ]);

    if (!is_wp_error($image_response)) {
        break;
    }

    $tries++;
}

if (is_wp_error($image_response)) {
    echo "ERROR: Download failed after retry\n";
    continue;
}

$image_data = wp_remote_retrieve_body($image_response);

if (!$image_data) {
    echo "ERROR: Empty image data\n";
    continue;
}

        $upload_dir = wp_upload_dir();

        if (empty($upload_dir['path'])) {
            echo "ERROR: Upload path issue\n";
            continue;
        }

        $filename = 'unsplash-' . time() . '-' . $post->ID . '.jpg';
        $file = trailingslashit($upload_dir['path']) . $filename;

        file_put_contents($file, $image_data);

        if (!file_exists($file)) {
            echo "ERROR: File write failed\n";
            continue;
        }

        $filetype = wp_check_filetype($filename, null);

        $attachment = [
            'post_mime_type' => $filetype['type'],
            'post_title'     => sanitize_text_field($title),
            'post_status'    => 'inherit'
        ];

        $attach_id = wp_insert_attachment($attachment, $file, $post->ID);

        if (is_wp_error($attach_id)) {
            echo "ERROR: Attachment failed\n";
            continue;
        }

        $attach_data = wp_generate_attachment_metadata($attach_id, $file);
        wp_update_attachment_metadata($attach_id, $attach_data);

        set_post_thumbnail($post->ID, $attach_id);

        echo "SUCCESS\n";
    }

    echo "\nDONE.\n
"; exit; });

FO Talks: The Collapse of New START Treaty Raises Global Nuclear Risks

Editor-in-Chief Atul Singh and Simon Cleobury, Head of Arms...

How Hybrid Warfare Shaped the Iran War Before It Began

On February 28, before the first explosion was visible...

Why Northeast India Remains Neglected and How to Fix It

When Lakshmipriya Devi took the stage at the recent...

Bangladesh Nationalist Party Declares Victory in Pivotal Election

In Dhaka, the Bangladesh Nationalist Party claimed what party...

Latest News

NATO Presses Members to Boost Defense Spending Amid Renewed Security Concerns

Leaders of NATO concluded a high stakes summit in Brussels with renewed calls for member states to accelerate defense spending commitments, citing persistent security...

Latest

From the world

FO Talks: The Collapse of New START Treaty Raises Global Nuclear...

Editor-in-Chief Atul Singh and Simon Cleobury, Head of Arms...

How Hybrid Warfare Shaped the Iran War Before It Began

On February 28, before the first explosion was visible...

Why Northeast India Remains Neglected and How to Fix It

When Lakshmipriya Devi took the stage at the recent...

Bangladesh Nationalist Party Declares Victory in Pivotal Election

In Dhaka, the Bangladesh Nationalist Party claimed what party...

NATO Presses Members to Boost Defense Spending Amid Renewed Security Concerns

Leaders of NATO concluded a high stakes summit in...

NATO Presses Members to Boost Defense Spending Amid Renewed Security Concerns

Leaders of NATO concluded a high stakes summit in Brussels with renewed calls for...

Wall Street Banks Post Strong Earnings Amid Volatile Trading Environment

Major U.S. financial institutions reported stronger than expected quarterly...

Federal Reserve Signals Cautious Path on Interest Rates as Inflation Moderates

Officials at the Federal Reserve indicated this week that...

Popular

NATO Presses Members to Boost Defense Spending Amid Renewed Security Concerns

Leaders of NATO concluded a high stakes summit in...

God of War Sons of Sparta Launches to Early Praise for...

Sony’s highly anticipated release God of War: Sons of...

EPA Repeals Long-Standing Climate Rule, Reshaping U.S. Environmental Policy

In Washington, the Environmental Protection Agency announced a sweeping...

Breakout Indie Hit “Mewgenics” Tops 500,000 Sales in Record Launch

An independently developed strategy title, Mewgenics, has emerged as...

Bad Bunny’s Historic Super Bowl Halftime Show Sparks Global Debate

The Bad Bunny-headlined halftime show at Super Bowl LX...

Responsible news

TDY News. Today and everyday.

Finance

Politics

spot_img

Subscribe