Solvedacf to rest api Apply same post format as WP JSON if ACF return format is Post Object

I would like to apply the same WP Rest API formatting to my ACF field values if the return format of that field is Post object. Right now, we can't reuse any code we write for a detail page and it's nested ACF related posts, because they are two completely different formats, see:

[
  {
    "id": 2,
    "date": "2017-06-30T11:29:19",
    "date_gmt": "2017-06-30T11:29:19",
    "guid": {
      "rendered": "http:\/\/localhost:8080\/?page_id=2"
    },
    "modified": "2017-06-30T15:47:57",
    "modified_gmt": "2017-06-30T15:47:57",
    "slug": "sample-page",
    "status": "publish",
    "type": "page",
    "link": "http:\/\/localhost:8080\/",
    "title": {
      "rendered": "Sample Page"
    },
    "content": {
      "rendered": "<p>This is an example page. It&#8217;s different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:<\/p>\n<blockquote><p>Hi there! I&#8217;m a bike messenger by day, aspiring actor by night, and this is my website. I live in Los Angeles, have a great dog named Jack, and I like pi&#241;a coladas. (And gettin&#8217; caught in the rain.)<\/p><\/blockquote>\n<p>&#8230;or something like this:<\/p>\n<blockquote><p>The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.<\/p><\/blockquote>\n<p>As a new WordPress user, you should go to <a href=\"http:\/\/localhost:8080\/wp\/wp-admin\/\">your dashboard<\/a> to delete this page and create new pages for your content. Have fun!<\/p>\n",
      "protected": false
    },
    "excerpt": {
      "rendered": "<p>This is an example page. It&#8217;s different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this: Hi there! I&#8217;m a bike messenger [&hellip;]<\/p>\n",
      "protected": false
    },
    "author": 1,
    "featured_media": 0,
    "parent": 0,
    "menu_order": 0,
    "comment_status": "closed",
    "ping_status": "open",
    "template": "",
    "meta": [
      
    ],
    "acf": {
      "related_posts": [
        {
          "ID": 1,
          "post_author": "1",
          "post_date": "2017-06-30 11:29:19",
          "post_date_gmt": "2017-06-30 11:29:19",
          "post_content": "Welcome to WordPress. This is your first post. Edit or delete it, then start writing!",
          "post_title": "Hello world!",
          "post_excerpt": "",
          "post_status": "publish",
          "comment_status": "open",
          "ping_status": "open",
          "post_password": "",
          "post_name": "hello-world",
          "to_ping": "",
          "pinged": "",
          "post_modified": "2017-06-30 11:29:19",
          "post_modified_gmt": "2017-06-30 11:29:19",
          "post_content_filtered": "",
          "post_parent": 0,
          "guid": "http:\/\/localhost:8080\/?p=1",
          "menu_order": 0,
          "post_type": "post",
          "post_mime_type": "",
          "comment_count": "1",
          "filter": "raw"
        }
      ]
    }
  }
]

As you can see, the related_posts key is a post as well, but has a completely different format to the parent post.

I have seen issue #109 but no solution was provided there for this particular issue.

Is this possible using filters right now? If so. how?

20 Answers

βœ”οΈAccepted Answer

Allright, thanks! The ticket on core is picked up and it will be fixed in WP 4.9.5.

For the people who are also looking for this, below is the function I wrote. What it does is converting the post object that any relationship or post object field returns, and converts it to an object that matches the scheme of the API. this means that all of these fields will now return a normal post in the rest api format, also containing all of it's child ACF fields etc.

<?php

	function QikkerAcfPostObjectFix()
	{

		function qikker_fix_acf_post_ojects($value, $original_post_id, $field)
		{

			if ($field[ 'return_format' ] !== 'object') {

				return $value;

			}

			remove_filter('acf/format_value/type=relationship', 'qikker_fix_acf_post_ojects', 20);
			remove_filter('acf/format_value/type=post_object', 'qikker_fix_acf_post_ojects', 20);

			if (is_array($value)) {

				foreach ($value as $post) {

					$formatted[] = convert_post_object_to_rest_response($post, $original_post_id);

				}

			} else {

				$formatted = convert_post_object_to_rest_response($value, $original_post_id);

			}

			add_filter('acf/format_value/type=relationship', 'qikker_fix_acf_post_ojects', 20, 3);
			add_filter('acf/format_value/type=post_object', 'qikker_fix_acf_post_ojects', 20, 3);

			return $formatted;

		}

		function convert_post_object_to_rest_response($post, $original_post_id)
		{

			global $wp_rest_server;
			$post_type = get_post_type_object($post->post_type);

			$request = WP_REST_Request::from_url(rest_url(sprintf('wp/v2/%s/%d', $post_type->rest_base, $post->ID)));
			$request = rest_do_request($request);
			$data = $wp_rest_server->response_to_data($request, isset($_GET[ '_embed' ]));

			// For the line below, see https://core.trac.wordpress.org/ticket/43502#ticket
			$GLOBALS[ 'post' ] = $original_post_id;

			return $data;

		}

		add_filter('acf/format_value/type=relationship', 'qikker_fix_acf_post_ojects', 20, 3);
		add_filter('acf/format_value/type=post_object', 'qikker_fix_acf_post_ojects', 20, 3);

	}

	add_action('rest_api_init', 'QikkerAcfPostObjectFix');

Other Answers:

@airesvsg I ended up doing exactly that, thanks!

Here is the PR if anyone is curious: https://github.com/paramander/wp-headless-theme/pull/1/files

Related Issues:

14
acf to rest api How to get ACF post object field with ACF fields
Hi @travis-zookacreative Thanks for using my plugin bellow I wrote an example most generic V3 V2 Fun...
5
acf to rest api Apply same post format as WP JSON if ACF return format is Post Object
Allright thanks! The ticket on core is picked up and it will be fixed in WP 4.9.5 For the people who...
227
neovim build fails with OSX Mojave
Starting with Mojave the headers are no longer installed under /usr/include/ by default -- look unde...
124
graphql engine relay support
Hi @srghma @toxsick relay makes assumptions about the GraphQL server as outlined here We haven't mad...
122
amplify cli Many-To-Many
You can implement many to many yourself using two 1-M @connections and a joining @model ...
111
zeal Content rendering error in MDN (HTML, JS, CSS) docsets
I find it can fix temporary by remove the CSS.docset\Contents\Resources\Documents\developer.mozilla....
101
type graphql Getting "Schema must contain uniquely named types but contains multiple types named" for a single type
This was a hard one to track down with an annoying fix (Nest specific not the fault of type-graphql)...
98
axios module How to set query params and message body?
No I don't mean the baseURL but the url path As an example let's say I have the following call: Axio...
96
strapi πŸ‘‰ Question: What are the main pain points you have using Strapi? (Episode 3)
Pain point Issue: No TypeScript support Context: I know it has been mentioned as something the team ...
96
fastapi WARNING: Unsupported upgrade request.
This error is not part of the FastAPI codebase When attempting to run this (using UviCorn) it starts...
90
neovim Build failed with Homebrew on both macOS 11.4 and 12.0.1
This should be fixed in Homebrew for now Neovim version (nvim -v) Upgrading neovim HEAD-487286b -> H...
83
amplify cli aws-exports.js is not generated
Even after the third read I find it utterly confusing and I have usability issues too ...
76
web3.js sendSignedTransaction() error: invalid sender
@paulrberg If you want to use the version: 2.0.0 you should add extra parameter chain like this ...
69
web3.js The method personal_unlockAccount does not exist/is not available
@vijayr2410 Well Looks like it's just require to specify following parameters to resolve this issue ...
64
fastapi [QUESTION] How to bridge Pydantic models with SQLAlchemy?
I just finished integrating Pydantic ORM mode into FastAPI it is released as version 0.30.0 πŸŽ‰ The n...
61
web3.js Handle web socket disconnects
You can listen to events from the WebSocketProvider to detect disconnects. Im making an app that mon...
61
strapi New project fails to connect to database
I had the same issue with 3.0.0-alpha.10 I ran strapi new project-name then when it prompts to enter...
59
ponzu no go files in /home/user/go/src/github.com/ponzu-cms/ponzu
try running go get -u github.com/ponzu-cms/ponzu/.. via copy / paste that exact command. ...
56
amplify cli @auth public/private IAM roles and other Providers
ok my bad was actually quite easy just do : and add a auth provider in my case was IAM ...
55
neovim Update tree-sitter to v0.19.0
Workaround for homebrew users: Uninstall tree-sitter@0.19.1 ignoring neovim dependency Extract the f...
52
fastapi [QUESTION] How to send 204 response?
Instead of returning None and instead of injecting the response just return a newly created response...
48
strapi Refresh JWT route
This is quite important for my app So I implement it by extending plugin (for temporary use) Here's ...
47
type graphql Cannot determine GraphQL input type for
For future readers This may have been due to using an @ObjectType() CompanyData as an @InputType() i...
44
amplify cli jest-haste-map: Haste module naming collision: -> namefunction <-
For React Native 0.6x configure the blacklist in metro.config.js instead of rn-cli.config.js as per ...
44
chi chi@v1.5.x mod issues
I do not want to release /v5 and see it on the import path I'm not sure why you are considering /v5 ...
43
Jackett The method or operation is not implemented. (all indexers!)
Working on Synology after manual update Note that this worked for my DS415+ that is using the Mono v...
42
fastapi OpenAPI UI not working properly when using automatic swagger-ui CDN (swagger-ui-3.30.1)
Thanks for reporting it and for all the discussion here everyone! πŸš€ β˜• Indeed it's a bug in Swagger ...
40
web3.js Transferring ERC20 tokens from account using web3 over Ropsten
Single-address allocation of MineFIL Token (MFIL) code which was written and tested using web3 versi...
39
L5 Swagger oauth2 + passport = Bearer <token>
Sharing my solution in case it might help This is I how made it to work with Passport using password...
38
neovim homebrew build fails to start (segfault in libtermkey 0.21)
EDITOR=/usr/bin/vim brew edit libtermkey edit the URL to libtermkey-0.20.tar.gz and the hash to 6c0d...
37
web3.js Error: Can't resolve 'crypto'
Ah yes!! this solution with the patch worked: https://gist.github.com/niespodd/1fa82da6f8c901d1c33d2...
36
web3.js Truffle and Ganache providers, Metamask Provider Engine no longer accepted as valid by web3
For those who might not know me I'm part of the Truffle team and @davidmurdoch and I oversee the dev...
34
core Non anemic doctrine models are not supported
Regarding the general design of API Platform and how it fits with command buses and/or event sourcin...
34
neovim Feature: optional floating window borders
This works for me Not sure why but it does. #6619 Added floating windows but no way to create a bord...
34
axios module How to import module to external file
@lukasborawski I think the following solution is far more elegant So let's say that I'm using axios ...
34
fastapi [QUESTION] Is this the correct way to save an uploaded file ?
@classywhetten FastAPI has almost no custom logic related to UploadFile -- most of it is coming from...
34
fastapi [QUESTION] Storing object instances in the app context
@ebarlas you're 100% right Description In Flask ...
33
amplify cli runtime parameter of nodejs8.10 is no longer supported
@asyschikov where can you find the build settings for amplify CLI that you are refering to ? For tho...
32
graphql engine Support for Mac M1
Hey folks Sorry for the radio silence on the thread from the Hasura team Add Hasura Support for Mac ...
31
api platform normalization context don't work on symfony v5.1.99
Try to run ./bin/console cache:clear API Platform version(s) affected: x.y.z Description when i make...
30
amplify cli Connect a cognito user with an AppSync type
Any updates on this? Having to manually write a Lambda triggered by Cognito events to create an AppS...
30
graphql engine Handling multiple roles on the graphql client (possibly in the same query)
@shahidhk .. my understanding of the current JWT role workflow is: The token is decoded ...
30
fastapi [QUESTION] aiohttp integration best practice
That is one way if you want create a new session for every request You can also use a singleton appr...
28
type graphql Integration with Prisma
Hi @19majkel94! We're still very interested in supporting you with a seamless Prisma integration Giv...
28
amplify cli npm install -g @aws-amplify/cli error
sudo npm install -g --unsafe-perm --verbose @aws-amplify/cli worked for me. npm install -g @aws-ampl...
27
web3.js Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!
I think I found the error When I call a contract function and await the send startWatching is invoke...
27
Jackett yggtorrent - new address
the YGGTorrent website has changed their domain to .ws And you should be able to get the Jackett YGG...
26
amplify cli Amplify push fails with error creating directory
I retried the amplify push command and changed the two paths that default to / to ./ and the command...
26
amplify cli Amplify API push fails
I also had trouble with amplify push In my case APIKeyExpirationEpoch: -1 did not help ...
26
loopback next Feature parity with LoopBack 3.x (and the lack of it)
Some of the big hitters here that are blocking us from migrating from LB3 to LB4 would be: Polymorph...