Hi,
I realise this is possible with the block editor (see my previous ticket here - https://toolset.com/forums/topic/dynamically-assigned-content-template-based-on-custom-field/).
However I have several sites that don't use the block editor and use the older code editor.
Is it possible with these? Is there a hook we can hook into for this we can use if we write some custom code?
Thanks.
Hi,
Thank you for contacting us and I'd be happy to assist.
Yes, you can use the filter 'wpv_filter_force_template' to programmatically change/override the assigned content template:
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_force_template
In your custom function attached to this filter, you can get the custom field's value and change the assigned template's ID if the value/condition is met.
regards,
Waqar
Hm I can't get this to work it changes it but creates an infinite loop see the attached screenshot.
Code I am using:
```
// Add a custom filter function
add_filter( 'wpv_filter_force_template', 'my_custom_template_filter', 10, 3 );
function my_custom_template_filter( $template_selected, $id, $kind ) {
// Check if the field value is "1"
$expire_but_live = get_post_meta( $id, 'wpcf-expire-but-live', true );
if ( $expire_but_live === '1' ) {
// Set the content template ID to "84774"
$template_selected = 84774;
}
return $template_selected;
}
```
I've tested the code that you've shared and it works on my test website, without any error like this.
Can you please make sure that your involved templates are not nesting other templates or using the 'wpv-post-body' shortcode, at multiple levels?
In case the issue persists, you're welcome to share temporary admin login details, along with the exact steps to see this error message.
Note: Your next reply will be private and making a complete backup copy is recommended before sharing the access details.
While trying to log in to the admin area, I get the message:
'A verification code has been sent to the email address associated with your account.'
Can you please remove this verification code security, temporarily?
Sorry about that, this has now been sorted for you.
During troubleshooting, I was able to fix the infinite loop of content templates, by including an additional check in the code snippet, for the already assigned template.
add_filter( 'wpv_filter_force_template', 'my_custom_template_filter', 10, 3 );
function my_custom_template_filter( $template_selected, $id, $kind ) {
if ($template_selected == 68667) {
// Check if the field value is "1"
$expire_but_live = get_post_meta( $id, 'wpcf-expire-but-live', true );
if ( $expire_but_live === '1' ) {
// Set the content template ID to "84774"
$template_selected = 84774;
}
}
return $template_selected;
}
The code only executes, if the assigned template ID is the same as the single offer template 'Offer Page Template'.