Okay
  Public Ticket #3531302
Event Creation inside Server
Closed

Comments

  •  2
    m16021 started the conversation

    Hello,


    I am currently bringing event information from another platform onto my wordpress server and want to add these into my events calendar. 

    I have been trying to do that using a curl statement into wp-json/stec/v5/Events but run into a 401 error where that endpoint does not allow posts?

    Is there a hook I could use instead if I format the event information into one compatible with STEC?

  •  894
    Zhivko replied

    You need to authorize before trying to insert an event via the api.

    In your request add Authorization header. 

    Example:

        curl_setopt_array(
            $curl,
            array(
                CURLOPT_URL            => $url,
                CURLOPT_POSTFIELDS     => json_encode($post_data),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER     => array(
                    "Content-Type: application/json",
                    "Authorization: $auth" // <--- This is the important line
                ),
                CURLOPT_POST           => true
            )
        );
    

    $auth example:

    $username     = 'admin'; 
    $app_password = 'GOBU V20P avUe Qnzi vPV7 TwIg'; // @see https://youtu.be/e_thybKPKHc?si=8ZUNpV6a8Cu5Ke3Q&t=349
    $auth         = 'Basic ' . base64_encode($username . ':' . $app_password);
    

    where $username is your actual login name

    For $app_password you need to go to Dashboard -> Users -> Your profile and scroll down to:

    8359407615.png

    You should use this password and not the one you login with.


    Stachethemes Developer

  •  2
    m16021 replied

    Hi Zhivko,

    Appreciate the quick response.

    My code is below:

    //set auth token for posting
    $username     = 'admin';
    $app_password = '**** **** **** **** **** **** ****'; 

                    /**
                     * Create new event
                             */
                    $new_event = array(
                            "title" => [
                                    "raw" => "My New Event"
                            ],
                            "excerpt" => [
                                    "raw" => "Event short description"
                            ],
                            "content" => [
                                    "raw" => "Event full description"
                            ],
                            "stec_cal" => 6, // the calendar id number
                            "meta" => array(
                                    'start_date' => '2023-07-11T12:30',
                                    'end_date'   => '2023-07-11T12:30',
                                    'all_day'    => true
                            )
                            );
                    // Merge defaults with new event
                    $new_event = array_replace_recursive($defaults, $new_event);

                    // Send new event to the api
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, "https://test.surreyunion.org/wp-json/stec/v5/events");
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($new_event));
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Accept: application/json','Authorization: $auth'));
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $response = curl_exec($ch);
                    // ... do something with the response
                    echo $response;
                    curl_close($ch);

    $defaults is just an initiation array for stec event.

    I am still getting a 401 error. Do you see anything wrong with this?



  •  894
    Zhivko replied
    //set auth token for posting
    $username     = 'admin';
    $app_password = '**** **** **** **** **** **** ****';
    $auth         = 'Basic ' . base64_encode($username . ':' . $app_password);
    /**
     * Create new event
     */
    $new_event = array(
        "title" => [
            "raw" => "My New Event"
        ],
        "excerpt" => [
            "raw" => "Event short description"
        ],
        "content" => [
            "raw" => "Event full description"
        ],
        "stec_cal" => 6, // the calendar id number
        "meta" => array(
            'start_date' => '2023-07-11T12:30',
            'end_date'   => '2023-07-11T12:30',
            'all_day'    => true
        )
    );
    // Merge defaults with new event
    $new_event = array_replace_recursive($defaults, $new_event);
    // Send new event to the api
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://test.surreyunion.org/wp-json/stec/v5/events");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($new_event));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Accept: application/json',
        'Authorization: ' . $auth
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    // ... do something with the response
    echo $response;
    curl_close($ch);

    $auth was missing value and it wasn't correctly added in the header. It was added as a string and not as variable.


    Stachethemes Developer

  •  2
    m16021 replied

    This is amazing thank you Zhivko! 

    I only have one last question, how do I use this Rest API call to set the featured image of the post? Do I need to add a hook in for that?



  •  894
    Zhivko replied

    I'd suggest you to create e helper function that will handle image uploads.

    Here's example. 

    Assuming this is the event post data:

    $post_data = array(
        "title" => [
            "raw" => "My New Event"
        ],
        "excerpt" => [
            "raw" => "Event short description"
        ],
        "content" => [
            "raw" => "Event full description"
        ],
        "stec_cal" => [603], // the calendar id number
        "status" => "publish",
        "meta" => array(
            'start_date' => '2023-12-31T12:30',
            'end_date'   => '2023-12-31T13:30',
            'all_day'    => true,
            'timezone'   => 'stec_cal_default' // default to calendar timezone
        ),
        
        "fn_upload_image" => array(
            "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
        )
    );
    
    7464281389.png

    This array "fn_upload_image" here will hold your images that you want to attach to the event. 

    It should contain array with image sources.

    ---

    And here's the custom hook that will handle the upload and attaching the image to the event "images" meta data:

    /**
     * Handler for 
     * 
     * $post_data = array(
     *     ...
     *     fn_upload_image = array( 'http://image1.jpg', 'http://image2.jpg' ... )
     *    ...
     * )
     */
    add_action('rest_insert_stec_event', function ($post, $request, $creating) {
        $fn_upload_image = $request->get_param('fn_upload_image');
        $uploaded_images = array();
        if (!is_array($fn_upload_image) || empty($fn_upload_image)) {
            return;
        }
        if (!function_exists('wp_crop_image')) {
            include_once(ABSPATH . 'wp-admin/includes/image.php');
        }
        foreach ($fn_upload_image as $image_src) {
            // upload image to media library
            $upload   = wp_upload_bits(basename($image_src), null, file_get_contents($image_src));
            $basename = basename($image_src);
            $mimetype = wp_check_filetype($basename);
            if ($upload['error']) {
                continue;
            }
            $attachment = array(
                'post_title'     => sanitize_file_name($basename),
                'post_content'   => '',
                'post_status'    => 'inherit',
                'post_mime_type' => $mimetype['type']
            );
            $attach_id = wp_insert_attachment($attachment, $upload['file']);
            // Generate attachment metadata and update the attachment
            $attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);
            wp_update_attachment_metadata($attach_id, $attach_data);
            $uploaded_images[] = $attach_id;
        }
        foreach ($uploaded_images as $order => $image_id) {
            $sizes = array('full', 'thumbnail', 'medium', 'large');
            $data = array(
                'id'            => $image_id,
                'sizes'         => array(),
                'dimensions'    => array(),
                'order'         => $order
            );
            foreach ($sizes as $size) {
                $image = wp_get_attachment_image_src($image_id, $size);
                if (!$image) {
                    return false;
                }
                $data['sizes'][$size] = $image[0];
                $data['dimensions'][$size] = array(
                    'width'  => $image[1],
                    'height' => $image[2],
                    'ar'     => $image[1] / $image[2]
                );
            }
            update_post_meta($post->ID, 'images', $data);
        }
    }, 10, 3);

    ---

    Basically what this hook does is it downloads the image, uploads it to the wordpress library and inserts the necessary meta to the event "images" meta.

    The image data structure that is stored in event "images" meta is like following:

    Array
    (
        [id] => 5469
        [sizes] => Array
            (
                [full] => http://localhost:8888/wp-content/uploads/2023/11/googlelogo_color_272x92dp-19.png
                [thumbnail] => http://localhost:8888/wp-content/uploads/2023/11/googlelogo_color_272x92dp-19-150x150.png
                [medium] => http://localhost:8888/wp-content/uploads/2023/11/googlelogo_color_272x92dp-19-300x101.png
                [large] => http://localhost:8888/wp-content/uploads/2023/11/googlelogo_color_272x92dp-19.png
            )
        [dimensions] => Array
            (
                [full] => Array
                    (
                        [width] => 544
                        [height] => 184
                        [ar] => 2.9565217391304
                    )
                [thumbnail] => Array
                    (
                        [width] => 150
                        [height] => 150
                        [ar] => 1
                    )
                [medium] => Array
                    (
                        [width] => 300
                        [height] => 101
                        [ar] => 2.970297029703
                    )
                [large] => Array
                    (
                        [width] => 544
                        [height] => 184
                        [ar] => 2.9565217391304
                    )
            )
        [order] => 0
    )



    Stachethemes Developer

  •  2
    m16021 replied

    Will this work without a large array of sizes? Say if I am only uploading through the API a "full" size image and so only upload to the meta data a full size image?

    So this will add the image into the media carousel for the event? I presume I can then set the post featured image to equal that first image in the meta data?

  •  894
    Zhivko replied

    You just need to specify the full size url. The other sizes are handled by WordPress during the upload process. The uploaded image will be used as an image for the media carousel yes.

    You could also assign the image as a featured image.


    Stachethemes Developer

  •  2
    m16021 replied

    Hi Zhivko,

    The code below seems to be uploading the images correctly to the wordpress database, but the events are not making it into stec rest api to become an event? 

    Anything obvious I should check?

  •  894
    Zhivko replied

    Try to var dump the events ids to see if they are being saved:

    add_action('init', function () {
        $events = get_posts(
            array(
                'fields'        => 'ids',
                'post_type'      => 'stec_event',
                'posts_per_page' => -1,
                'post_status'    => 'any'
            )
        );
        var_dump($events);
        exit;
    });
    

    If the events are there it is possible they are missing some meta data.

    Check if they have read_permission and edit_permission meta values, if their post_status is "publish".


    Stachethemes Developer

  •  2
    m16021 replied

    Hi Zhivko,

    The posts work fine until I add in the custom hook below to add the image in. Then the events dont make it through to the REST API so not sure if its missing meta info unless it is linked to the images that we are adding in? 

    The images are making it onto the server just then not attaching to a posted image so i think the problem is in the custom hook. 

    Can I add the below hook function into that custom hook in order to get the var_dump?


    Cheers!


  •  894
    Zhivko replied

    Do you see any errors in the error_log file? Make sure WP_DEBUG and WP_DEBUG_LOG are set to true in your wp-config.php file.


    Stachethemes Developer

  •  2
    m16021 replied

    Hello Zhivko,

    Sorry for the delayed response.

    There is no errors in the debug.log and all of the debug tools are on. 

    I have noticed that it is creating events within the rest api that are picked up in the counter on the stec dashboard but not in the events management page. So currently the dashboard is reading 300 events when there should be none. Is there an easy way to delete all of that data? I presume they are not pulling through because their json set up is incorrect because of this image processing?

  •  894
    Zhivko replied

    Try turning off all settings in Calendar Dashboard -> Settings -> Language and see if the events show up.

    ---

    This php code will delete all events it finds.

    $ids = get_posts(array(
        'fields'     => 'ids',
        'posts_per_page'   => -1,
        'post_type'  => 'stec_event'
    ));
    if (is_array($ids)) {
        foreach ($ids as $id) {
            wp_delete_post($id, true);
        }
    }


    Stachethemes Developer

  •  2
    m16021 replied

    The language bit didnt work but the php code has got be back to zero thank you.

    So there are no errors in the log, I have got the image being passed to wordpress uploading to the media library but it is not attaching itself to the post either in the media carousel or as the featured image on the post itself. Any suggestions?

  •  2
    m16021 replied

    Managed to solve my post thumbnail problem but the images are still not loading into the carousel. 


    Looks like the data array for the image is fine but it appears that my image is too small for wordpress to make it in a "large size" would that be a specific problem? Does the plugin rely on all 4 standard wordpress sizes being available?

  •  2
    m16021 replied

    So it when i use get_post_meta($postid) after the function I can see that the meta data is in there for the post. 

    But it is not within the rest_api which I believe to be the problem. Should it be that we do the image uploading before we upload the post? Then use the rest_insert_stec_events in order to upload the post thumbnail using the media post id?