· 7 months ago · Feb 21, 2025, 08:40 AM
1<?php
2/**
3 * Sync a 'Job' CPT item to Customer.io Collections whenever it is published or updated.
4 *
5 * @package my_wp_fusion_customizations
6 */
7
8/**
9 * Sends Job CPT data to Customer.io Collections on save_post.
10 *
11 * @param int $post_id ID of the post being saved.
12 * @param WP_Post $post The post object.
13 * @param bool $update Whether this is an existing post being updated or not.
14 */
15function my_prefix_sync_job_to_customer_io_collections( $post_id, $post, $update ) {
16
17 // Only run for our 'job' CPT.
18 if ( 'job' !== $post->post_type ) {
19 return;
20 }
21
22 // If this is an autosave or a revision, exit.
23 if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
24 return;
25 }
26
27 // Replace with your real Customer.io API key.
28 $customer_io_api_key = 'YOUR_CUSTOMER_IO_API_KEY';
29
30 // Build the data you want to send to Customer.io.
31 // Expand or modify these fields as needed.
32 $data = array(
33 'id' => (string) $post_id, // Unique identifier in the collection.
34 'title' => sanitize_text_field( $post->post_title ),
35 'link' => esc_url_raw( get_permalink( $post_id ) ),
36 // Add meta fields, e.g.:
37 // 'skills_required' => sanitize_text_field( get_post_meta( $post_id, 'skills_required', true ) ),
38 // etc.
39 );
40
41 // Prepare the remote request arguments.
42 // For the Collections API you may need POST, PUT, or PATCH.
43 $args = array(
44 'method' => 'PUT', // or 'POST', depending on whether you want to upsert or create.
45 'headers' => array(
46 'Authorization' => 'Bearer ' . $customer_io_api_key,
47 'Content-Type' => 'application/json',
48 ),
49 'body' => wp_json_encode( $data ),
50 );
51
52 // Adjust the endpoint with your real Collection ID in Customer.io:
53 $collection_id = 'YOUR_COLLECTION_ID';
54
55 // Typically an upsert endpoint might look like:
56 $endpoint_url = 'https://track.customer.io/api/v1/collections/' . $collection_id . '/items/' . $post_id;
57
58 // Send the request.
59 $response = wp_remote_request( $endpoint_url, $args );
60
61 // Optional: check for errors.
62 if ( is_wp_error( $response ) ) {
63 error_log(
64 sprintf(
65 /* translators: %s is the WP_Error message */
66 esc_html__( 'Customer.io Collection sync error: %s', 'wp-fusion' ),
67 $response->get_error_message()
68 )
69 );
70 } else {
71 error_log(
72 esc_html__( 'Job synced successfully to Customer.io Collections.', 'wp-fusion' )
73 );
74 }
75}
76add_action( 'save_post', 'my_prefix_sync_job_to_customer_io_collections', 10, 3 );
77