ACF Block in multisite switch_to_blog not working properly #2833
-
I have an ACF Block that admins can add to their page to get and display news from the News site on our network. I switch to the news get, get the 3 most recent posts, and return them to the twig file. In the twig file I'm just looping over them to display them. The title displays, but the post.link or post.meta does not display. If I don't switch_to_blog and just pull the 3 recent blog posts from the site I'm on it works perfectly fine. block/news.php function herdpress_moments_block( $block, $content = '', $is_preview = false ) {
$context = Timber::context(); // phpcs:ignore
$context['block'] = $block;
$context['fields'] = get_fields();
$context['is_preview'] = $is_preview;
switch_to_blog( get_id_from_blogname( 'news' ) );
$context['posts'] = Timber::get_posts(
array(
'posts_per_page' => 3,
)
);
restore_current_blog();
Timber::render( 'blocks/news.twig', $context );
} blocks/news.twig {% for post in posts %}
<a href="{{ post.link }}">{{ post.title }}</a>
<div>{{ post.meta('media_contact') }}</div>
{% endfor %} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Can you try to put the |
Beta Was this translation helpful? Give feedback.
-
This is expected behavior. If you use The reason you need to prepare your data in advance is that certain methods in Timber will call WordPress functions that rely on the current blog. Timber doesn’t fill out all data in The solution looks like this: block/news.php function herdpress_moments_block( $block, $content = '', $is_preview = false ) {
$context = Timber::context(); // phpcs:ignore
$context['block'] = $block;
$context['fields'] = get_fields();
$context['is_preview'] = $is_preview;
$context['posts'] = [];
switch_to_blog( get_id_from_blogname( 'news' ) );
$posts = Timber::get_posts( [
'posts_per_page' => 3,
] );
// Let’s prepare all data we’re gonna need in the Twig view here.
$context['posts'][] = [
'link' => $post->link(),
'title' => $post->title(),
'media_contact' => $post->meta('media_contact'),
];
restore_current_blog();
Timber::render( 'blocks/news.twig', $context );
} blocks/news.twig {% for post in posts %}
<a href="{{ post.link }}">{{ post.title }}</a>
<div>{{ post.media_contact }}</div>
{% endfor %} As of Timber 2.0, you could also use Post serialization for this. |
Beta Was this translation helpful? Give feedback.
-
Thank you! |
Beta Was this translation helpful? Give feedback.
This is expected behavior. If you use
switch_to_blog()
, you need to prepare your data in a context variable.The reason you need to prepare your data in advance is that certain methods in Timber will call WordPress functions that rely on the current blog. Timber doesn’t fill out all data in
{{ post }}
for performance reasons. For example,{{ post.link }}
will callget_permalink()
internally, and this will always try to get the data from the current blog.The solution looks like this:
block/news.php