• Hello!
    We use RPWE to nicely format lists of posts on our company’s support website (WordPress, naturally). It works great.

    I recently started implementing a third-party tool that calls the WP API to search for posts based on a (string) search term. The query looks like this:
    https://mysite.com/wp-json/wp/v2/posts?search=asdf
    And the result is supposed to be a nice json array of posts.

    However…and this is the strange part… Somehow, RPWE is getting in the way and ouputting a chunk of CSS into the result, right at the top. Since the caller is expecting json only, it breaks our integration.

    I’ve tried playing around in the RPWE plugin code–I see the exact line where it inserts that CSS, and I added some “if” logic to only output the CSS if a certain shortcode attribute were present. The results are strange: if I call the API directly, right after loading a WP page with RPWE on it, it still fails (as if RPWE remembers being loaded from the UI).

    Am I missing something obvious? I’m not a WP expert (C# and javascript is my trade), so maybe there’s just some setting I need to know about….?

    Thanks in advance!

Viewing 1 replies (of 1 total)
  • Thread Starter dsanderling

    (@dsanderling)

    I think I have a workaround. I added the following code to functions.php:

     //I found this part on stackexchange
      if (!function_exists('is_rest')) {
        /**
         * Checks if the current request is a WP REST API request.
         * 
         * Case #1: After WP_REST_Request initialisation
         * Case #2: Support "plain" permalink settings
         * Case #3: URL Path begins with wp-json/ (your REST prefix)
         *          Also supports WP installations in subfolders
         * 
         * @returns boolean
         * @author matzeeable
         */
        function is_rest() {
            $prefix = rest_get_url_prefix( );
            if (defined('REST_REQUEST') && REST_REQUEST // (#1)
                || isset($_GET['rest_route']) // (#2)
                    && strpos( trim( $_GET['rest_route'], '\\/' ), $prefix , 0 ) === 0)
                return true;
    
            // (#3)
            $rest_url = wp_parse_url( site_url( $prefix ) );
            $current_url = wp_parse_url( add_query_arg( array( ) ) );
            return strpos( $current_url['path'], $rest_url['path'], 0 ) === 0;
        }
    }

    And I added the && !is_rest() to this if-block, also in functions.php:

    	// Display the default style of the plugin.
    	if ( $args['styles_default'] === true && !is_rest()) {
    		rpwe_custom_styles();
    	}

    I do worry about updates to this plugin breaking my fix, so mayyyybe you could add something like this to the plugin code… 🙂 thank you.

Viewing 1 replies (of 1 total)

The topic ‘rpwe breaks wp-json posts API output’ is closed to new replies.