Created
January 12, 2016 17:39
-
-
Save jwietelmann/2ea2423a66bb8ba711ac to your computer and use it in GitHub Desktop.
A hacky way to consume WP-API content and provide it to Rails views.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'faraday' | |
class WordpressController < ApplicationController | |
@@wp_client = Faraday.new(url: "http://#{ENV['WP_DOMAIN']}") do |builder| | |
builder.adapter Faraday.default_adapter | |
builder.headers = {'Content-Type' => 'application/json'} | |
builder.request :url_encoded | |
end | |
def show | |
res = @@wp_client.get('/wp-json/wp/v2/posts', 'filter[name]' => params[:path]) | |
raise ActiveRecord::RecordNotFound if res.status == 404 | |
raise 'Wordpress server did not respond with success' unless res.status == 200 | |
@wp = JSON.parse!(res.body).first | |
raise ActiveRecord::RecordNotFound unless @wp | |
# Replace all links that look like, for example... | |
# http://example.wpengine.com/foo | |
# But not, for example... | |
# http://example.wpengine.com/wp-content | |
# http://example.wpengine.com/wp-admin | |
# etc. | |
# With... | |
# /wp/foo | |
# | |
# WARNING: This is a hack. It just happens to work in this case. | |
# A more comprehensive solution would be aware of which HTML attributes of | |
# which tags it was rewriting. | |
@wp['content']['rendered'].gsub! /(https?:)?\/\/#{Regexp.quote(ENV['WP_DOMAIN'])}(?!\/wp-)/, '/wp' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment