• Resolved Chris Coyier

    (@chriscoyier)


    At one point, this plugin successfully output customCSS in the JSON API as part of the post it was pulling, but now it comes back as null.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Hardeep Asrani

    (@hardeepasrani)

    Hey @chriscoyier,

    As far as I remember, we had discussed it, and it was added with the help of this code snippet: https://ww.wp.xz.cn/support/topic/custom-css-in-the-rest-api/#post-12968470

    Can you confirm that the snippet still exists on your website?

    Let me know, and I’ll take a deeper look to make sure it still works!

    PS: Also, do you have the Otter Blocks plugin installed on your website?

    Thread Starter Chris Coyier

    (@chriscoyier)

    Ah yes — that custom code, exactly as written, is still live in the functions.php of the active theme.

    Here’s an example of JSON output of a page that has custom CSS on it, where the customCSS is null:

    https://blog.codepen.io/wp-json/wp/v2/landing_page/13826

    > do you have the Otter Blocks plugin

    Nope.

    Plugin Author Hardeep Asrani

    (@hardeepasrani)

    Hey @chriscoyier,

    This should do the work:

    add_action( 'rest_api_init', 'add_post_css_rest_field' );
    
    function add_post_css_rest_field() {
        register_rest_field( 'post', 'customCSS', array(
               'get_callback'    => 'get_post_css',
               'schema'          => null,
            )
        );
    }
    
    function get_post_css( $object ) {
        //get the id of the post object array
        $post_id = $object['id'];
        if ( class_exists( '\ThemeIsle\GutenbergBlocks\Blocks_CSS' ) ) {
            $content = get_the_content( $post_id );
            $content = parse_blocks( $content );
            if ( ! is_array( $content ) || empty( $content ) ) {
    	    return null;
            }
            $class = new \ThemeIsle\GutenbergBlocks\Blocks_CSS();
            $css = $class->cycle_through_blocks( $content, 0 ); // 0 here is Post ID, since you aren't using Otter, 0 should be fine, or any post ID for that matter.
            if ( ! empty ( $css ) ) {
                return $css;
            }
        }
    
        return null;
    }

    Sorry, a few months back, we had a major reshuffle for our block plugins and had to change the class names. This should do the work and we don’t think we will be changing the class name ever again.

    Let me know if it helps!

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘customCSS in JSON API missing’ is closed to new replies.