【问题标题】:WordPress Cron to update html file once a dayWordPress Cron 每天更新一次 html 文件
【发布时间】:2015-04-17 23:37:09
【问题描述】:

所以我刚刚意识到 WordPress Cron API 和它非常适合我试图解决的任务。我需要 WordPress Cron 来更新我的 Multisite 上的 html 文件。
--------
目标: 我想要实现的是在我的站点网络中,我需要主站点使用主题 A 的子主题,所有子站点都使用主题 B 的子主题。然后,所有子站点必须在顶部实现主站点的标题网站的内容,包括其样式、链接等。
--------
我一直在阅读 WordPress Cron 的工作原理,但我不知道如何处理我试图解决的这个任务。我想我需要创建一个 mu-plugin 并将我的 Cron 作业连接到 Wordpress,或多或少像这样:

register_activation_hook( __FILE__, 'plugin_job' );
    function plugin_job(){
     //Use wp_next_scheduled to check if the event is already scheduled
     $timestamp = wp_next_scheduled( 'plugin_create_job' );

     //If $timestamp == false schedule
     if( $timestamp == false ){
           //Schedule the event for right now, then to repeat daily using the hook
           wp_schedule_event( time(), 'daily', 'plugin_create_job' );
     }
}

//Hook our function
add_action( 'plugin_create_job', 'create_job' );
function create_job(){
     //Generate html file from Mainsites header.php
}

我绝对可以使用一些指导和意见 :-)

【问题讨论】:

    标签: php wordpress plugins cron


    【解决方案1】:

    我会说这种方法使问题过于复杂,但如果您想通过 wp_cron 作业来完成,您正在寻找的方法是 file_get_contentsfile_put_contents

    因此,您需要使用 file_get_contents 将头文件转换为字符串,将该字符串保存为变量,然后使用 file_put_contents 将该字符串写入服务器某处的 html 文件。

    function create_job(){
        //Generate html file from Mainsites header.php
        $header_contents = file_get_contents( get_template_directory_uri() . '/header.php' );
    
        //If the header contains any information write to file
        if( $header_contents ) {
            file_put_contents( 'path/to/html/file.html', $header_contents );
        }
    }
    

    另外两点... wp_cron 非常糟糕,如果可能的话应该是replaced with a real server CRON job

    另外,不要忘记在插件停用时破坏 cron 计划...

    function myplugin_deactivation() {
        wp_clear_scheduled_hook( 'plugin_create_job' );
    }
    
    register_deactivation_hook( __FILE__, 'myplugin_deactivation' );
    

    或者只是删除所有子主题的 header.php 文件,然后所有对 get_header 的调用都会从父主题中检索header.php 文件。

    解决此问题的另一种方法是在父主题的函数文件中创建一个函数,该函数仅输出主题 A 的主题标题的内容...

    function mysite_get_custom_header() {
        return file_get_contents( get_theme_root_uri() . '/child-theme-A/header.php' );
    }
    

    然后将子主题B中get_header()的所有实例替换为...

    echo mysite_get_custom_header();
    

    希望有帮助

    问候

    【讨论】:

    • 嘿@danbahrami - 非常感谢您的意见!你能详细说明为什么它过于复杂吗?我认为这是一种减少服务器请求和流量的方法?我很想听听您认为哪种方法是正确的!
    • @MacLuc 不客气。你能更好地解释一下情况吗?您的多站点网络的子站点是否与您的主站点提供相同的主题并因此使用相同的 header.php 文件?
    • 我现在在我的帖子中更多地扩展这种情况。谢谢。
    • 现在在目标部分。谢谢。
    • @MacLuc 为我的原始答案添加了更多解决方案。您并没有真正通过使用 wp_cron 来保存任何请求,调用 html 文件的成本基本上与调用 php 文件的成本一样高,并且无论您以何种方式加载所有外部资源都必须这样做所以我给出的最后几个方法更简单,一天中第一次点击你的网站的可怜的草皮不必加载两次标题。
    猜你喜欢
    • 1970-01-01
    • 2013-03-31
    • 2021-12-09
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多