日程表函数wordpress插件

hkmswyz6  于 2023-01-16  发布在  WordPress
关注(0)|答案(1)|浏览(117)

我创建一个插件,我需要运行,例如每5分钟(测试,稍后将每12小时)。和文件.xml更新后,功能再次启动,但这是不工作的。它只工作一次,当我激活插件,之后什么都没有:

function send_http_post_request() {
error_log('Cron is running'); // added this line

    // Set up the request body with the SOAP request
    $request_body = '<?xml version="1.0" encoding="utf-8"?>
    <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
      <soap12:Body>
        <GetProducts xmlns="http://URL">
          <username>TEST</username>
          <password>123456789</password>      
          <productGroupCode>Test</productGroupCode>           
    </GetProducts>
  </soap12:Body>
</soap12:Envelope>';

// Send the request
    $response = wp_remote_post( 'https://www....', array(
        'method' => 'POST',
        'headers' => array(
            'Content-Type' => 'application/soap+xml; charset=utf-8',
        ),
        'body' => $request_body,
    ) );

    // Check for error
    if ( is_wp_error( $response ) ) {
        // There was an error making the request
        $error_message = $response->get_error_message();
        echo "Error making request: $error_message";
    } else {
        // The request was successful
        $response_code = wp_remote_retrieve_response_code( $response );
        $response_body = wp_remote_retrieve_body( $response );

        // Check if the response has changed since the previous iteration
        if ( $response_body != $prev_response_body ) {
            // Update the previous response
            $prev_response_body = $response_body;

            // Update the response.xml file
            file_put_contents( ABSPATH . 'folder/test.xml', $response_body );
        }
    }
}
// Run the function when the plugin is activated
register_activation_hook( __FILE__, 'send_http_post_request' );

//schedule the function to run every 5 minutes
if ( ! wp_next_scheduled( 'send_http_post_request' ) ) {
    wp_schedule_event( time(), 'every5minutes', 'send_http_post_request' );
}

//add the action to the scheduled event
add_action( 'send_http_post_request', 'send_http_post_request' );

//deactivation hook to remove scheduled event
register_deactivation_hook( __FILE__, 'remove_scheduled_event' );
function remove_scheduled_event() {
    wp_clear_scheduled_hook( 'send_http_post_request' );
}
?>
qxgroojn

qxgroojn1#

您将事件的时间表定义为“every5minutes”,但是WordPress没有预定义的每5分钟的时间表。相反,您可以使用interval参数来安排事件每300秒(5分钟)运行一次。因此,您应该替换

wp_schedule_event( time(), 'every5minutes', 'send_http_post_request' );

wp_schedule_event( time(), 300, 'send_http_post_request' );

相关问题