Skip Navigation

[Resolved] Filter the options in Post Relationship field in wp-admin post editor

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

Problem: I would like to filter the options shown in the Post Relationship field in the post editor screen. Only the current User's posts should be shown here.

Solution: There is not a good way to do this in wp-admin, but you can use generic fields in CRED to accomplish something similar.
- Create a CRED form to add posts and insert a generic select field
- Create a View of posts, filtered by author, where the author is the current User
- In the Loop Output editor, insert this code to replace the default wpv-loop tags:

<wpv-loop>
      [wpv-item index=1]
        {"value":"[wpv-post-id]","label":"[wpv-post-title]"}
      [wpv-item index=other]
      ,{"value":"[wpv-post-id]","label":"[wpv-post-title]"}
</wpv-loop>

- Add the following custom code to your functions.php file:

add_filter( 'wpv_filter_wpv_view_shortcode_output', 'prefix_clean_view_output', 5, 2 );
 
function prefix_clean_view_output( $out, $id ) {
  $ids = array( 12345 );
  if ( in_array( $id, $ids )) {
    $start = strpos( $out, '<!-- wpv-loop-start -->' );
    if (
      $start !== false
      && strrpos( $out, '<!-- wpv-loop-end -->', $start ) !== false
    ) {
      $start = $start + strlen( '<!-- wpv-loop-start -->' );
      $out = substr( $out , $start );
      $end = strrpos( $out, '<!-- wpv-loop-end -->' );
      $out = substr( $out, 0, $end );
    } else {
      $start = strpos( $out, '>' );
      if ( $start !== false) {
        $out = substr( $out, $start + 1 );
        $end = strpos( $out, '<' );
        $out = trim(substr( $out, 0, $end ));
      }
    }
  }
  return $out;
}

add_action('cred_save_data', 'cred_belongs_impresa_action',10,2);
function cred_belongs_impresa_action($post_id, $form_data)
{
    $forms = array( 67890, 98765 );
    // if a specific form
    if (in_array($form_data['id'], $forms))
    {
        if (isset($_POST['selectcompany']))
        {
            update_post_meta( $post_id, '_wpcf_belongs_impresa_id', $_POST['selectcompany'] );
        }
    }
}

- Change 12345 to match the ID of the View
- Change 67890, 98765 to be a comma-separated list of CRED form IDs (your edit and add CRED forms)
- Place the View of posts inside the options of the generic select field:

[cred_generic_field field='your-field-slug' type='select' class='' urlparam='']
{
"required":0,
"validate_format":0,
"default":[],
"options":[ [wpv-view name="your-parent-post-view-slug"] ]
}
[/cred_generic_field]
This support ticket is created 6 years ago. There's a good chance that you are reading advice that it now obsolete.

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
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 31 replies, has 2 voices.

Last updated by Silvia 5 years, 11 months ago.

Assisted by: Christian Cox.

Author
Posts
#675509

I hope to be able to explain the problem exhaustively.
I am developing a website for an Institute that deals with job opportunity matchmaking between companies and schools. Matches can be searched both “privately” (by employees of the institute that provides such service) and publicly (i.e. a school searches for companies in a certain km radius to send its students to, or a Company wants to see if there is a School nearby that allows students to have job experiences in its activity or production field).

Since it is a paid service certain details regarding companies and schools need to be undisclosed to public, most importantly COMPANY NAME and SCHOOL NAME (otherwise companies and schools would be able to perform the search themselves and wouldn’t be needing my client anymore) but need to be accessible to the employees that have access to the backend of the website.

To achieve this, I created four different post types :
1. Companies
2. Company opportunities (which is a child of Companies)
3. Schools
4. Schools Opportunities (which is a child of Schools)

Let’s take the Companies cpt, for example.
Ideally the Post Title should be containing the Company name, because it’s the most logic choice… But I can’t do that because even tho I decide to never use the “Post Title” or “Post Title with a link” fields, whenever I use a LINK to the post, the name of the company would be disclosed to public on the bottom left of the browser that’s displaying the link, because of the permalink structure. Same problem with Schools. I’d rather not change permalink structure, because of SEO positioning problems.

So I found a small php script that allows me to dynamically create the post title concatenating “company n” with the post-id so that the post title is “company n 33” for instance. In the cpt fields I inserted a text field that stores the actual Company name. Same with Job Opportunities (if post title is empty then concatenate "opt" + "post id") in this case because employees do not want to come up everytime with an original name for each job opportunity. Using the post Id I am sure to avoid having duplicates.

This solution takes care of keeping the Company/School name hidden to the public.

The problem is though, when I have to insert Job Opportunities related to a certain company, the relation field necessary to bind that opportunity to the right company that's shown at the bottom of the opportunity page contains the COMPANY cpt post title… and unfortunately, to employees that have to connect the job opportunity with the right company, the title “Company n. 33” doesn’t say much. They’d have to jump back and forth to see what company name is related to Company post title and that’s just not practical at all.

My question: is there a way to display both “Post Title” and another field in the relationship field so that users can actually see “Company n. 33 - Acme Inc” or even better “Acme Inc - Company n. 33”? Can you provide me with the code? This needs to be done for both Companies and Schools.

If not, do you have a practical alternative suggestion that would help me solve this problem? Thank you!!!

#675573

Hi, I assume you're talking about the post relationship select field in a CRED form, correct? If so, then the standard post relationship field will not work here, because there is no easy way to filter the option label. Instead, you can replace those with CRED generic fields. It's possible to use a View to generate the options of that generic field dynamically, so you can put whatever text you want in the label of each option by inserting the proper shortcodes in the loop output. This ticket talks about the general approach for setting up generic fields with options generated by a View:
https://toolset.com/forums/topic/how-use-a-shortcode-instead-of-options-for-cred-forms

In your case, you will create two generic fields - one for the parent Company and another for the parent School. In the Loop Output of the View that generates options, you will insert shortcodes in the "label" attribute, which can include a shortcode to display the custom field value. In the "value" attribute, you will keep the wpv-post-id shortcode in place.

Once you have the generic select fields set up in your CRED form, I can help you use the CRED API to capture the selections made by your Users and converting those into post relationships. Let me know if you are able to get that far or if you get stuck and I can take a look.

#675731
toolsetimage.jpg

Hello Christian, no I was talking about the field on the backend, I have enclosed an image, if this can help... As regarding the solution you're suggesting, I will be looking into it tomorrow, because it's late here now and this needs particular attention. Regardless of this answer of mine, where I am showing you the image about what I was talking about, can we leave this ticket open so if I decide to go with the option you suggested I can use this ticket to ask for your help? Thank you!

#675734

Okay I see, there's not a good way to filter these post relationships options in wp-admin. You could set up a CRED form on the front-end of the site using the method I described earlier, and allow your employees to make parent / child associations there instead of wp-admin. I'll keep this ticket open pending an update from you.

#690931

Chris,
I came up with an alternative solution to my problem, but since this is a quite complex project I don't want to be the one to make such crucial decisions, I want the CLIENT to chose which approach they like best. So, in addition to presenting my solution, I would like to go thru with yours, if you are kind enough to guide me step by step in the process.
Thanks a lot!

#693783

Okay sure. Let's begin with these steps:
1. Create a new CRED form that edits the child post type. Use the Auto-generate button to set up the form.
2. Follow these instructions to insert an Edit Post link on the child post: https://toolset.com/documentation/user-guides/displaying-cred-editing-forms/
3. Once you have the edit form showing up on the front-end, edit the CRED form and remove everything except the required form tags:

[credform class='cred-form cred-keep-original']

	[cred_field field='form_messages' value='' class='alert alert-warning']

	[cred_field field='form_submit' value='Submit' urlparam='' class='btn btn-primary btn-lg' output='bootstrap']

[/credform]

4. Use the Add Generic Field button to insert a generic select field in between the messages shortcode and the submit shortcode. For now, just add some dummy options.

Let me know if you are able to finish these steps or if you get stuck.

#695911

Chris,
I managed to follow almost all the steps you indicated but I think I am missing the big picture here : I don't get why you had me create an EDIT cred form while the problem is when CREATING a brand new child post to assign to a parent (because the parent's name (company name in this case) is not displayed but a random-generated name is placed in the Post Title instead) . I thought this whole process would have had an employee create a new job opportunity via Cred Form and be able to have a Select Field in the form that would allow them to pick the right Company that Job Opportunity is related to, by name, which is classified data to public. Maybe the whole process is not clear to me, I apologize. Maybe I am going ahead of myself and that is exactly what you had in mind.. but in order to learn from this I have to have it clear in my mind. Can you please explain? Thank you so much!

#710464

Since there is not a good way to filter the parent options in wp-admin, I was thinking you could use a CRED form on the front-end of the site to manage these parent / child relationships. When creating new child posts, yes, a New Post CRED form will be the best option, but for existing child posts you would use an Edit Post CRED form to manage those parent/child relationships. I think I was focusing more on the existing child post process, as opposed to the new child post process, sorry for the confusion.

#710778

Okay then, no problem! I need to address both situations, anyway! Right now I only have dummy data that’s been inserted for testing purposes only but not the future I’ll need to have users capable of handling both create and edit situations, and it’ll be necessary for the company name to be always shown to them coz they’re not WordPress savvy. The easier I make it for them, the better! So, let’s start. I managed to follow the steps you told me in your previous post. What do I do now? Thanks for your help!!!

#711762

Okay now that you have the generic field in place from step 4, we will create a View that will be used to define the options for this generic field.
5. Create a new View of the Parent post type (I believe it's Impreza), filtered by Post Author, so that the current User only sees their parent posts.
6. In the Loop Output editor, click the "Skip Wizard" button and replace the wpv-loop tags with this code:

<wpv-loop>
      [wpv-item index=1]
        {"value":"[wpv-post-id]","label":"[wpv-post-title]"}
      [wpv-item index=other]
      ,{"value":"[wpv-post-id]","label":"[wpv-post-title]"}
</wpv-loop>

7. Add the following code to functions.php to strip out the extra formatting and markup:

add_filter( 'wpv_filter_wpv_view_shortcode_output', 'prefix_clean_view_output', 5, 2 );

function prefix_clean_view_output( $out, $id ) {
  $ids = array( 1, 2, 3, 4, 71 );
  if ( in_array( $id, $ids )) {
    $start = strpos( $out, '<!-- wpv-loop-start -->' );
    if (
      $start !== false
      && strrpos( $out, '<!-- wpv-loop-end -->', $start ) !== false
    ) {
      $start = $start + strlen( '<!-- wpv-loop-start -->' );
      $out = substr( $out , $start );
      $end = strrpos( $out, '<!-- wpv-loop-end -->' );
      $out = substr( $out, 0, $end );
    } else {
      $start = strpos( $out, '>' );
      if ( $start !== false) {
        $out = substr( $out, $start + 1 );
        $end = strpos( $out, '<' );
        $out = trim(substr( $out, 0, $end ));
      }
    }
  }
  return $out;
}

8. Place the View on the front-end of your site to test it out. You should see a list of parent posts for the current author, like this:

{"value":1234, "label": "The post title"},{"value":2345, "label": "The post title #2"}

9. Once that works, you can remove the test View and place it inside the generic field's "options" attribute (from step 4).

[cred_generic_field field='your-field-slug' type='select' class='' urlparam='']
{
"required":0,
"validate_format":0,
"default":[],
"options":[ [wpv-view name="your-parent-post-view-slug"] ]
}
[/cred_generic_field]
#713181
detailpage.jpg
CHILD POST EDIT.png

Dear Chris,
I did everything you told me to do but it's not working the way it's supposed to. I am enclosing a couple images for you to see. I have also created an admin user for you, if you want to take a look.
Fyi :

  • "impresa" is the cpt that stores companies
  • "Opportunità Impresa" is the cpt that stores job opportunities offered by companies
  • "Scuole" is the cpt that stores schools
  • "Opportunità Scuole" is the cpt that stores job experiences requested by schools for the students
#717766

Please provide login credentials here and I will take a look. Please also include the URL of the detail page you showed above.

#720020
Screen Shot 2018-04-23 at 2.36.55 PM.png
Screen Shot 2018-04-23 at 2.37.01 PM.png

1. I changed your functions.php file to point to the correct View ID:

function prefix_clean_view_output( $out, $id ) {
  $ids = array( 220 );
  if ( in_array( $id, $ids )) {

2. I unchecked "Non include la pagina attuale nel risultato del query" in the View. This can cause problems in queries so if you don't need it, don't check it.

3. I published a post so I could test: hidden link

4. It seems to work correctly now, so I trashed the post I created.

#720713

I am sorry Chris but nothing is working on my end.
The generic field inserted in CRED edit form was showing the POST TITLE, which is the automatically generated name with the post id, and that's not what I wanted. I need to show the name of the company, which is stored into "ragione-sociale-impresa" field. So I changed the view from:

 {"value":"[wpv-post-id]","label":"[wpv-post-title]"}

to

 {"value":"[wpv-post-id]","label":"[types field='ragione-sociale-impresa'][/types]"}

but now the COMPANY JOB OPPORTUNITIES page is not showing neither the "Settore Impresa" taxonomy nor the "edit" link anymore... probably because it has lost the association with the parent Company post.

It looks like the generic field generated by the view you told me to create is not storing any value in the wpcf_belongs_impresa_id.

I also created the "Aggiungi Opportunità Impresa" cred form, and used the same generic field. I tried to add a new opportunità Impresa but as I suspected, it saves everything but the parent post.
Can you please help? This is the most complex project I have ever developed so far, and its due date is May 14th so I really need this to work!
Thank you

#720885

Okay I'm not sure what type of custom field this is, but you may need to add the output='raw' attribute to this types field shortcode:

{"value":"[wpv-post-id]","label":"[types field='ragione-sociale-impresa' output='raw'][/types]"}

This raw attribute will strip all extra formatting and markup from the field value, which should help. If the select field does not appear, please move the View outside of the generic field so you can observe the results generated by the View. Post those here for me to review.

The raw attribute, among others, is discussed in the types field shortcode documentation here:
https://toolset.com/documentation/customizing-sites-using-php/functions

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.