検索
ホームページバックエンド開発PHPチュートリアルこの Cron JOB コードでどのように役立つでしょうか?

How Can Help You in This Cron JOB Code?

postype TVShows,Seasons,episodes を使用してウェブサイト用にこの Cron ジョブを作成しました。シーズンを正しく取得し、生成して公開されましたが、既存のシーズンのタイムコールが発生したときエピソードが生成され公開されませんか?この問題を解決するために手伝ってくれませんか?

`// ステップ 1: テスト用にカスタムの 1 分間隔を登録します
add_filter('cron_schedules', 'custom_one_minute_cron_schedule');
functioncustom_one_minut_cron_schedule($schedules) {
$schedules['毎分'] = array(
'間隔' => 60, // 60 秒
'表示' => __('毎分')
);
$schedule を返す;
}

// ステップ 2: Cron ジョブを毎分実行するようにスケジュールする (テスト目的)
if (!wp_next_scheduled('auto_generate_new_seasons')) {
wp_schedule_event(time(), 'every_ minutes', 'auto_generate_new_seasons');
}

// ステップ 3: 新しいシーズンとエピソードを生成するコールバック関数を定義する
add_action('auto_generate_new_seasons', 'generate_new_seasons');
関数generate_new_seasons() {
グローバル $wpdb;

// Query to get all TMDb IDs of existing TV shows from post meta
$tmdb_ids = $wpdb->get_col("SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = 'ids'");

foreach ($tmdb_ids as $tmdb_id) {
    // Check if the TV show exists in the 'tvshows' custom post type
    $tv_show_posts = get_posts(array(
        'post_type' => 'tvshows',
        'meta_key'  => 'ids',
        'meta_value'=> $tmdb_id,
        'posts_per_page' => 1,  // Only need one result
    ));

    // If TV show does not exist, skip to the next TMDb ID
    if (empty($tv_show_posts)) {
        continue;
    }

    // If the TV show is found, process it
    foreach ($tv_show_posts as $post) {
        // First, check if the 'clgnrt' meta is already set to avoid duplicate generation
        $clgnrt = get_post_meta($post->ID, 'clgnrt', true);
        if (!$clgnrt) {
            // Set the 'clgnrt' meta to '1' for the TV show to avoid regenerating it
            update_post_meta($post->ID, 'clgnrt', '1');
        }
    }

    // Now check for and import new seasons for each TMDb ID
    $existing_seasons = $wpdb->get_col($wpdb->prepare(
        "SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id IN (
            SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'ids' AND meta_value = %s
        ) AND meta_key = 'temporada'",
        $tmdb_id
    ));

    $season = 1;
    while ($season) {
        // Skip seasons that already exist (duplicate check)
        if (in_array($season, $existing_seasons)) {
            $season++;
            continue;
        }

        // Fetch season data from TMDb API
        $response = wp_remote_get("https://api.themoviedb.org/3/tv/$tmdb_id/season/$season", array(
            'body' => array(
                'api_key' => 'YOUR_TMDB_API_KEY',
                'language' => 'en-US',
                'append_to_response' => 'images'
            )
        ));

        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200) {
            break;
        }

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

        // If no season data is found, break the loop
        if (!isset($json_tmdb['season_number'])) {
            break;
        }

        // Create a new season post
        $post_data = array(
            'post_status'  => 'publish',
            'post_title'   => $json_tmdb['name'] . ': Season ' . $json_tmdb['season_number'], // Season Title: "Show Name: Season 1"
            'post_content' => $json_tmdb['overview'],
            'post_type'    => 'seasons',
        );

        $post_id = wp_insert_post($post_data);

        if (!is_wp_error($post_id)) {
            // Add meta data for the new season
            add_post_meta($post_id, 'ids', $tmdb_id);
            add_post_meta($post_id, 'temporada', $json_tmdb['season_number']);
            add_post_meta($post_id, 'air_date', $json_tmdb['air_date']);
            add_post_meta($post_id, 'dt_poster', $json_tmdb['poster_path']);

            // Update the 'clgnrt' meta for seasons to avoid regeneration
            update_post_meta($post_id, 'clgnrt', '1');

            // Generate episodes for the new season
            generate_episodes($tmdb_id, $season, $post_id);
        }

        $season++;
    }
}

}

// ステップ 4: シーズンのエピソードを生成する
functiongenerate_episodes($tmdb_id, $season_number, $season_post_id) {
グローバル $wpdb;

// Check if the episodes for this season already exist
$existing_episodes = $wpdb->get_col($wpdb->prepare(
    "SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id IN (
        SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'temporada' AND meta_value = %s
    ) AND meta_key = 'episodio' ",
    $season_number
));

$episode_number = 1;
while ($episode_number) {
    // Skip episodes that already exist (duplicate check)
    if (in_array($episode_number, $existing_episodes)) {
        $episode_number++;
        continue;
    }

    // Fetch episode data from TMDb API
    $response = wp_remote_get("https://api.themoviedb.org/3/tv/$tmdb_id/season/$season_number/episode/$episode_number", array(
        'body' => array(
            'api_key' => 'YOUR_TMDB_API_KEY',
            'language' => 'en-US',
            'append_to_response' => 'images'
        )
    ));

    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200) {
        break;
    }

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

    // If no episode data is found, break the loop
    if (!isset($json_tmdb['episode_number'])) {
        break;
    }

    // Create a new episode post
    $post_data = array(
        'post_status'  => 'publish',
        'post_title'   => $json_tmdb['name'] . ' ' . $season_number . 'x' . $episode_number, // Episode Title: "Show Name: 1x1"
        'post_content' => $json_tmdb['overview'],
        'post_type'    => 'episodes',
    );

    $episode_post_id = wp_insert_post($post_data);

    if (!is_wp_error($episode_post_id)) {
        // Add meta data for the new episode
        add_post_meta($episode_post_id, 'ids', $tmdb_id);
        add_post_meta($episode_post_id, 'temporada', $season_number);
        add_post_meta($episode_post_id, 'episodio', $json_tmdb['episode_number']);
        add_post_meta($episode_post_id, 'air_date', $json_tmdb['air_date']);
        add_post_meta($episode_post_id, 'dt_poster', $json_tmdb['still_path']);

        // Update the 'clgnrt' meta for episodes to avoid regeneration
        update_post_meta($episode_post_id, 'clgnrt', '1');
    }

    $episode_number++;
}

}

// ステップ 5: テスト後の cron ジョブ スケジュールをクリーンアップしてリセットします
add_action('init', function() {
if (define('WP_DEBUG') && WP_DEBUG) {
// 既存の cron スケジュールを削除してリセットします
$timestamp = wp_next_scheduled('auto_generate_new_seasons');
if ($timestamp) {
wp_unschedule_event($timestamp, 'auto_generate_new_seasons');
}
}

// Re-schedule the cron job to run hourly instead of every minute for production
if (!wp_next_scheduled('auto_generate_new_seasons')) {
    wp_schedule_event(time(), 'hourly', 'auto_generate_new_seasons');
}

});
`

以上がこの Cron JOB コードでどのように役立つでしょうか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
トラフィックの高いウェブサイトのPHPパフォーマンスチューニングトラフィックの高いウェブサイトのPHPパフォーマンスチューニングMay 14, 2025 am 12:13 AM

thesecrettokeepingaphp-poweredwebsterunningsmootlyunderheavyloadinvolvesseveralkeystrategies:1)emform opcodecoduceSciptionexecutiontime、2)aatabasequerycachingwithiThing withiThistolessendavasoload、

PHPでの依存関係注射:初心者向けのコード例PHPでの依存関係注射:初心者向けのコード例May 14, 2025 am 12:08 AM

コードをより明確かつ維持しやすくするため、依存関係が関心(DI)に注意する必要があります。 1)DIは、クラスを切り離すことにより、よりモジュール化されます。2)テストとコードの柔軟性の利便性を向上させ、3)DIコンテナを使用して複雑な依存関係を管理しますが、パフォーマンスの影響と円形の依存関係に注意してください。

PHPパフォーマンス:アプリケーションを最適化することは可能ですか?PHPパフォーマンス:アプリケーションを最適化することは可能ですか?May 14, 2025 am 12:04 AM

はい、最適化されたAphPossibleandessention.1)CachingingusapCutoredatedAtabaseload.2)最適化、効率的なQueries、およびConnectionPooling.3)EnhcodeCodewithBultinctions、Avoididingglobalbariables、およびUsingopcodeching

PHPパフォーマンスの最適化:究極のガイドPHPパフォーマンスの最適化:究極のガイドMay 14, 2025 am 12:02 AM

keyStrategIestsoSificlyvoostphpappliceperformanceare:1)useopcodecachinglikeToreexecutiontime、2)最適化abaseの相互作用とプロペラインデックス、3)3)構成

PHP依存性噴射コンテナ:クイックスタートPHP依存性噴射コンテナ:クイックスタートMay 13, 2025 am 12:11 AM

aphpDependencyInjectionContaineriSATOULTAINATINAGECLASSDEPTINCIES、強化測定性、テスト可能性、および維持可能性。

PHPの依存噴射対サービスロケーターPHPの依存噴射対サービスロケーターMay 13, 2025 am 12:10 AM

SELECT DEPENTENCINGINOFCENT(DI)大規模なアプリケーションの場合、ServicElocatorは小さなプロジェクトまたはプロトタイプに適しています。 1)DIは、コンストラクターインジェクションを通じてコードのテスト可能性とモジュール性を改善します。 2)ServiceLocatorは、センター登録を通じてサービスを取得します。これは便利ですが、コードカップリングの増加につながる可能性があります。

PHPパフォーマンス最適化戦略。PHPパフォーマンス最適化戦略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedforspeedandEfficiencyby:1)enabingopcacheinphp.ini、2)PreparedStatementswithpordatabasequeriesを使用して、3)LoopswithArray_filterandarray_mapfordataprocessing、4)の構成ngincasaSearverseproxy、5)

PHPメールの検証:電子メールが正しく送信されるようにしますPHPメールの検証:電子メールが正しく送信されるようにしますMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。