Skip Navigation

[Resolved] Is there a Post type form field to assign a content template to a Custom Post ?

This thread is resolved. Here is a description of the problem and solution.

Problem:

The customer was working on a Custom Post Type ("Object") that represents artworks on their museum platform. They created specific content templates for different museums to cater to their unique display requirements. However, there was no option in the Custom Post Type Forms for the museum staff to assign the appropriate content template when creating or editing an artwork. The customer wanted to eliminate the need for staff to navigate the wp-admin editing page, which could lead to confusion and errors.

Solution:

We suggested utilizing a generic field in the form to enable the selection of a content template. The customer successfully implemented a dropdown select field, but encountered an issue where the selected option did not display when returning to the form. To resolve this, we provided a custom PHP function that retrieves the current template assigned to the post. The code snippet for the function is as follows:

add_action('cred_save_data', 'my_save_data_action', 10, 2);
function my_save_data_action($post_id, $form_data) {
    // Array of form IDs for which the action should be triggered
    $form_ids = array(21166, 18806);
    // Check if the current form ID is in the list
    if (in_array($form_data['id'], $form_ids)) {
        if (isset($_POST['select-template'])) {
            update_post_meta($post_id, '_views_template', sanitize_text_field($_POST['select-template']));
        }
    }
}

After further testing, we recommended that for museum editors, the solution could be simplified by hardcoding the content template ID to ensure the correct template is always assigned. This change allowed for the expected functionality when creating or editing artworks.

Relevant Documentation:
https://toolset.com/course-lesson/conditional-display-for-form-inputs/
https://toolset.com/documentation/programmer-reference/forms/cred-shortcodes/#cred_generic_field

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 -
- 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 -

Supporter timezone: America/Sao_Paulo (GMT-03:00)

This topic contains 14 replies, has 2 voices.

Last updated by FRANCESCOD7762 3 months ago.

Assisted by: Mateus Getulio.

Author
Posts
#2740136
Assigning_Template_in_Post_Edit_Page.JPG

I have a Custom Post Type "Object" representing works of art on a Museum Platform site (muselink.ch), which contains the Collections of 2 or more different museums.
Each museum has a specifiv way (content & design) to display it's art works : in order to accomodate each specificities, I created specific content templates for each museum.
Also, to allow the Museum staff to create/edit the Objects (art works), I created focussed Custom Post type Forms
Now, with one of those forms, when I create or edit an Object (art work) belonging to a specific Museum, I have to assign the correct content template to a given Object :
- so far, I did not find any form field, which would allow to assign a content template to a given Object
- I am able to do such an assignment only on the wp-admin Object Editing page : which is exactly what I don't want the Museum staff to have to deal with (too much data/ choices = opportunities to mess up the plateform...)
-> see attached screen shot

Is there any documentation that you are following?
- I did not find any

Is there a similar example that we can see?
- no

What is the link to your site?
hidden link

#2740291

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

Hi,

Thank you for contacting us and I'd be happy to assist.

To offer a content template selection field in a post form, you'll need to use a generic field, for example:
( ref: https://toolset.com/documentation/programmer-reference/forms/cred-shortcodes/#cred_generic_field )


[cred_generic_field type='radio' field='select-template']
{
"required":1,
"default":[],
"options":[{"value":"123","label":"Template 1"},{"value":"456","label":"Template 2"}]
}
[/cred_generic_field]

Note: In the generic field's options attribute, replace the values and labels, to match your content template IDs and titles.

Next, you'll need a custom function attached to the "cred_save_data" that gets the selected template's ID from the generic field and sets it as the "_views_template" custom field value:
( ref: https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data )


add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
	// if a specific form
	if ($form_data['id']==12345)
	{
		if (isset($_POST['select-template']))
		{
			update_post_meta( $post_id, '_views_template', $_POST['select-template'] );
		}
	}
}

Note: You'll replace '12345' with your actual form's ID.

I hope this helps and please let me know if you need any further assistance around this.

regards,
Mateus

#2740828
Capture d’écran 2024-09-06 161116.png

Hi Mateus,
Thank you for your prompt and detailed response.

The generic field works very well : I opted for drop down select field instead of the radio field.

Nevertheless, there is now a side effect :
- when I return on the same Custom Type Form, the field does not display the chosen content template Name
see attached screen shot
What do I have to add to the custom function, so that the select field displays the chosen option / value of the Custom Type Field ?

Best regards,

Francesco

#2741098

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

Hello Francesco,

Can you please try to replace the shortcode with this new version?

[cred_generic_field type='select' field='select-template' class='custom-select']
{
"required":1,
"default":["[wpv-post-field name='_views_template']"],
"options":[
    {"value":"123","label":"Template 1"},
    {"value":"456","label":"Template 2"}
]
}
[/cred_generic_field]

This aims to load the current template by adding [wpv-post-field name='_views_template']

Thank you, please tell me how it goes.
Mateus

#2741338
Shortcode_with_default_Not_Working.JPG

Hi Mateus,
This is not working (see attached screen shot) :
- the generic field works only with the option to manually enter the options (I already had this issue with the previous shirtcode) :
--- is this a bug ?
- but in the manual case, there is no way to enter a default value

Maybe the custom function has to define the default value ?

Best regards,
Francesco

#2742807

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

Hi Francesco,

I implemented the default field in a test site and it is loading the current post assigned template properly.

To debug it further and suggest the best way to fix it in your site, I'll need to see how this is set up in the admin area.

Can you please share temporary admin login details along with a link to a page where this form can be seen?

Note: Your next reply will be private and please make a complete backup copy, before sharing the access details.

regards,
Mateus

#2743023

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

default-form.jpg

Hello Francesco,

Thank you for providing me with that access.

Regarding the code, you can refactor it to eliminate an if. You can create an array and check if the ID is in there:

add_action('cred_save_data', 'my_save_data_action', 10, 2);
function my_save_data_action($post_id, $form_data)
{
    // Array of form IDs for which the action should be triggered
    $form_ids = array(21166, 18806);

    // Check if the current form ID is in the list
    if (in_array($form_data['id'], $form_ids))
    {
        if (isset($_POST['select-template']))
        {
            update_post_meta($post_id, '_views_template', sanitize_text_field($_POST['select-template']));
        }
    }
}

I didn't want to implement it on the live site, since I don't have FTP access, but feel free to replace the old code with this version.

Regarding the templates, I enabled the expert mode and added the default, please check the screenshot for further reference.

Now I'm able to see the proper template when going back to the edit screen, please check it: hidden link

It might be necessary for you to save the other 'objets' at least once for the template to get retrieved. New objets should not need it.

Can you please test it and confirm it is working now?

Thank you,
Mateus

#2744916

Hi Mateus,
Please leave this ticket still open : I am still testing.
I will post results soon.

Thank you,

Francesco

#2745125

Hi Mateus,
The cod you gave me works well, but it needs to be extended for the following reason :
- there are 2 kinds of connected users :
--- ADMIN : accesses all museums data
--- Museum EDITORS : access only their museums data

Consequently, for instance for the Confrérie des Vignerons Museum Editor, there is no need to give her the choice of Content Templates. On the contrary, she should have only one choice, namely the Modèle pour Objets Confrérie.

Therefore, in the Confrerie Object Creation and Editing forms, I replaces the select generic field with a Single line text field :
- I gave it the slug : input-template
- I then modified the custom php function, You can see it here :
hidden link

Unfortunately, neither of those Confrérie forms is working :
- the Object is created, but the template is not assigned : hidden link
You can see the forms here :
- the Confrérie Creation form : hidden link
- the Confrérie Editing form : hidden link
--- for the Editing form, I added a JS function to make the Single line text field "readonly", so that the museum Editor can not change it:
function enable()
{
let eleman = document.getElementsByClassName("template-select");
eleman[0].setAttribute("readonly", true);
console.log(eleman[0]);
}
enable();

The function works : you can see the forms screens here :
- the Confrérie Creation form : hidden link
- for a test object I created, the Confrérie Editing form : hidden link

It baffles me : thank you for helping me with this.
Best regards,

Francesco

#2745195

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

Hello Francesco,

What if you used the conditional display to hide the content template field from the form based on the current's user role: https://toolset.com/course-lesson/conditional-display-for-form-inputs/

eg.: To only display it to the admin role:

[wpv-conditional if="( '[wpv-current-user info="role"]' eq 'administrator' )"]
 
[cred_generic_field type='select' field='select-template' class='custom-select']
{
...
}
[/cred_generic_field]
 
[/wpv-conditional]

Would it suffice for what you're trying to implement?

#2745547

Hi Mateus,
Thank you for the suggestion to use the conditional display : I had thought of it before, now it is a matter of choice if the Museum Editors need to see it present in the Object Editing Form - even though read only - or not ; I will discuss this with them.

Now, the main issue of my previous message was that the Museum Editor Object Creation Form does not set the content template :
- I was not clear about the fact that MUSEUM EDITORS have the permission to Create Objects
- in that case, their Object Creation Form has to set the value of the content template, which is specifically configured for their Museum
- and they do not need to have any other choice, hence the Generic Single line Textfield
- contrary to the site ADMIN, which has all permissions, meaning that if necessary she needs to be able assign any content template when she creates an Object, hence the Generic Select field

The Admin forms with the Select field (slug : select-template) - Object Creation and Editing - do work fine, and set the correct content templates.
Now, the issue is that the Museum Editors forms with the Textfield (slug : input-template) do not work :
- maybe the edit I made of the php custom function, integrating that input-template field, is not correct ?
- or is it some other mistake I made ?

For the museum Confrérie as an example, please check the following :
- the Confrérie Creation form : hidden link
- and the php custom function : hidden link

You can try creating an new Confrérie Object with it's Creation form page :
hidden link

When submitting it, you should be redirected to the Object content template, but at the moment, it is not working - you get an empy page.
You can also verify that the object has been created on the page listing all Confrérie Objects :
hidden link

I have made a backup of the whole site (files and DB), and will not work on it until I have your response.
By the way, this site is live - not a staging site - but is is not advertised, and still under development.

Thank you for your help.

Francesco

#2747216

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

Hello Francesco,

Sorry for the delay caused due to the weekend and for the confusion in my last reply.

Given that the new forms won't give the option for the users to select from existing templates, the solution is even easier.

You don't need to retrieve the user selection from the form, instead you can edit the code to always save the ID of the desired template, in this case it is 70:

// Array of MUSEUMEDITORS Object Creation and Editing forms IDs for which the action should be triggered
    $form_input_ids = array(16691, 18806);

    // Check if the current form ID is in the list
    if (in_array($form_data['id'], $form_input_ids)) {
        // Check if the current form select field exists in the form
        if (isset($_POST['input-template'])) {
            update_post_meta($post_id, '_views_template', 70);
        }
    }

I already updated it in the site and tested that both forms are assigning 'Modèle pour Objets Confrérie' as expected.

#2748009

Hi Mateus,

Thank you for resolving the issue and simplifying the solution.
We decided to keep displaying the template setting field for the Museum Editors, for clarity sake.

I learned a lot thanky to your efficient help : thank you so much.

I have one more generic question about content templates :
- what is their "Priority attribute", what is it doing really ?

Best regards,

Francesco

#2748201

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

Hi Francesco,

I'm glad to hear that the solution is working well for you, and thank you for your kind words!

Regarding your question, the priority attribute is used when you have multiple content templates that could be conditionally applied to the same content type. In such cases, the "Priority" setting determines which template should be used. The template with the highest priority (the highest number) will be applied first.

When Would You Use It?

For example, suppose you have two content templates:

- Template A is assigned to all "Object" posts in a specific category.
- Template B is assigned to all "Object" posts with a specific tag.

If an "Object" post belongs to both the category and the tag, both templates could be applied. By setting a higher priority for Template B (say, priority 10) and a lower priority for Template A (say, priority 5), WordPress will use Template B whenever a post meets both conditions.

Do You Need to Use the Priority Setting?

Given the current setup you have described, where each museum's editor is assigned a specific content template for their objects, you likely do not need to use the priority attribute. Your structure seems straightforward, with each form designed to assign a specific content template without any overlapping conditions. This makes the priority setting unnecessary in your case.

Please let me know if you have any further questions or if there's anything else I can assist you with!

Best regards,
Mateus

#2749274

Hi Mateus,

Thank you for your comprehensive explanation !
I finally know now what the Template Priority is used for...

I think this ticket is resolved and you can close it.
Thank you for your efficient help : I always learn a lot when I get your instructions.

Best regards,
Francesco