-
I have a content template with dynamic link in the post header. I want to change the post link if a ACF field is filled out. However, the code below gives me a 503 error.
add_filter('post_link', 'maybe_file_link_instead_of_permalink', 1, 2); function maybe_file_link_instead_of_permalink($permalink, $post){ if (function_exists('get_field') && $post instanceof WP_Post) { $file = get_field('fil', $post->ID); if (!empty($file) && isset($file['url'])) { $permalink = esc_url($file['url']); } } return $permalink; }
-
Hi there,
I just tested the code on my site and it does not return an error.
-
And do you have ACF and the field called “fil” like I do?
-
No, I don’t.
Give this new code a try, I added a flag to see if that helps.
add_filter('post_link', 'maybe_file_link_instead_of_permalink', 1, 2); function maybe_file_link_instead_of_permalink($permalink, $post) { // Ensure we're not modifying an already modified permalink (prevent recursion) if (isset($post->filter_applied) && $post->filter_applied) { return $permalink; } $post->filter_applied = true; // Flag to prevent recursion if (function_exists('get_field') && $post instanceof WP_Post) { $file = get_field('fil', $post->ID); if (!empty($file) && isset($file['url'])) { $permalink = esc_url($file['url']); } } return $permalink; }
However, the filter is not from the theme, if it’s conflicting with ACF functions, you might need to check with WP’s support.
or you can use GB’s
generateblocks_dynamic_url_output
filter instead. -
The code with the flagging gives the same error. Weird…
I have changed to the
generateblocks_dynamic_url_output
and added a template_redirect with someone should find the permalink elsewhere.add_filter('generateblocks_dynamic_url_output', 'maybe_file_link_instead_of_permalink', 1, 2); function maybe_file_link_instead_of_permalink($url, $attributes){ if (!empty($url) && !empty($attributes['className']) && 'link-til-indlaeg-eller-fil' === $attributes['className']){ global $post; if (function_exists('get_field') && $post instanceof WP_Post){ $file = get_field('fil', $post->ID); if (!empty($file) && isset($file['url'])) { $url = esc_url($file['url']); } } } return $url; } function redirect_to_acf_file_url() { // Check if it is a singular "Resources" post if (is_singular('post')) { // Get the current post ID $post_id = get_the_ID(); // Get the URL from the ACF file field, assuming the field name is 'fil' $file = get_field('fil', $post_id); // Check if the URL is not empty if (!empty($file) && isset($file['url'])) { // Perform the redirect wp_redirect(esc_url($file['url']), 301); exit; } } } add_action('template_redirect', 'redirect_to_acf_file_url');
-
Does it work well now?
-
Yep, using
generateblocks_dynamic_url_output
works well! -
Glad to hear that 🙂
- You must be logged in to reply to this topic.