Skip Navigation

[Resolved] Copy post taxonomy value to another taxonomy on cred save

This support ticket is created 6 years, 3 months 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.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+00:00)

This topic contains 16 replies, has 2 voices.

Last updated by jonB-5 6 years, 3 months ago.

Assisted by: Nigel.

Author
Posts
#1089294

I have a CPT named Voyages
Each Voyage has two taxonomies set in the CRED form, titled 'Embarkation Country' and 'Disembarkation Country'
For all other CPTs on my site I have a taxonomy titled 'Countries'

What I'd like to do, on CRED Save Data, is get the values a user has selected for Embarkation Country and Disembarkation Country and copy them both into the Countries taxonomy for the post.

Can you advise on how I can achieve this?

I have been looking at the following:
https://toolset.com/forums/topic/cred_save_data-to-select-a-category-in-a-form/#post-129756
https://codex.wordpress.org/Function_Reference/wp_get_post_terms
https://codex.wordpress.org/Function_Reference/wp_set_post_terms

I suspect it may be a problem that even though the Taxonomy Titles all match across these three taxonomies, their IDs don't.

#1089492

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Jon

You are right, I think, in that your problem is that the country terms of your embarkation and disembarkation taxonomies won't match each other or the target country taxonomy.

So you need to work with taxonomy slugs.

But the documentation you linked to for wp_set_post_terms says "If you want to enter terms of a hierarchical taxonomy like categories, then use IDs."

A basic requirement for this to be possible is that, although the term IDs will be different, their slugs must be the same.

So, when the form is submitted you get the post term of the embarkation taxonomy, which returns an array of term objects that includes the slug.

Use that slug with the function get_term_by to get the ID of the country taxonomy term that has the same slug.

(https://codex.wordpress.org/Function_Reference/get_term_by)

Then use that term ID to update the post with that country term.

That's handles the embarkation country, repeat for the disembarkation country.

That's what's involved, do you want to try that and if you get stuck let me know.

#1090191

I have built the following, though it does not seem to be working..
Can you see any glaring issues in the code below?

// Manage Voyage Country Taxonomies
add_action('cred_save_data', 'cred_save_voyage_countries', 10, 2);
function cred_save_voyage_countries($post_id, $form_data) {

   $forms = [ 90, 110 ];

   if ( in_array( $form_data['id'], $forms ) )
        {

	$embarkationcountry = get_the_terms( $post_id, 'embarkation-country' );
	$disembarkationcountry = get_the_terms( $post_id, 'disembarkation-country' );

	if ( !empty( $embarkationcountry ) ){

		$emb_term_list = wp_get_post_terms($post_id, 'embarkation-country', array("fields" => "all"));
		$emb_term_slug = $emb_term_list[0]->slug;

		$country_slug_emb = get_term_by('slug', $emb_term_slug, 'countries');
		$country_id_emb = $country_slug_emb->term_id;
        	wp_set_post_terms($post_id, $country_id_emb, 'countries');

	}
	if ( !empty( $disembarkationcountry ) ){

		$dis_term_list = wp_get_post_terms($post_id, 'disembarkation-country', array("fields" => "all"));
		$dis_term_slug = $dis_term_list[0]->slug;

		$country_slug_dis = get_term_by('slug', $country_slug_dis, 'countries');
		$country_id_dis = $country_slug_dis->term_id;
        	wp_set_post_terms($post_id, $country_id_dis, 'countries');

	}
    }
}

I also tries the two methods in the following code, but with no success...

$embarkationcountry = get_the_terms( $post_id, 'embarkation-country' );
	$disembarkationcountry = get_the_terms( $post_id, 'disembarkation-country' );
	$countries = 'countries';

	if ( !empty( $embarkationcountry ) ){
    	     // get the first term
    		$ecountry = array_shift( $embarkationcountry );
    		$ecountryslug = $ecountry->slug;
		$countrysluge = get_term_by('slug', $ecountryslug, 'countries');
		$ecountryid = $countrysluge->term_id;
        	wp_set_post_terms($post_id, $ecountryid, $countries);
	}
	if ( !empty( $disembarkationcountry ) ){

		$dcountrydetails = wp_get_post_terms($post_id, $disembarkationcountry, array("fields" => "all"));
		$dcountryslug = $dcountrydetails->slug;

		$countryslugd = get_term_by('slug', $dcountryslug, 'countries');
		$dcountryid = $countryslugd->term_id;
        	wp_set_post_terms($post_id, $dcountryid, $countries);
	}
#1090207

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

The thing that pops out is that you are using get_the_terms to get the taxonomy terms attached to the post and then using wp_get_post_terms to effectively do the same thing (they are very similar).

Without reproducing your set up I can't test this, but whenever I'm writing some code such as this I liberally add error_log messages throughout the code so I can see whether a function returns what is expected. A typical problem may be that you are expecting a function to return an object, but it returns an array of objects.

So, make sure your debug log is on.

If you haven't already edit your wp-config.php file and change the line with WP_DEBUG like so:

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

That will create a file debug.log in your /wp-content/ directory which you can examine in any text editor.

Then update your code with error log messages, something like this:

// Manage Voyage Country Taxonomies
add_action('cred_save_data', 'cred_save_voyage_countries', 10, 2);
function cred_save_voyage_countries($post_id, $form_data) {
 
   $forms = [ 90, 110 ];
 
   if ( in_array( $form_data['id'], $forms ) )
        {
 
        error_log("starting...");

        $embarkationcountry = get_the_terms( $post_id, 'embarkation-country' );
        $disembarkationcountry = get_the_terms( $post_id, 'disembarkation-country' );

        error_log(print_r($embarkationcountry, true)); //should be array of term objects
        error_log(print_r($disembarkationcountry, true)); //should be array of term objects
     
        if ( !empty( $embarkationcountry ) ){
     
            $emb_term_list = wp_get_post_terms($post_id, 'embarkation-country', array("fields" => "all"));
            $emb_term_slug = $emb_term_list[0]->slug;
     
            $country_slug_emb = get_term_by('slug', $emb_term_slug, 'countries');
            $country_id_emb = $country_slug_emb->term_id;

            error_log(print_r($emb_term_list, true));
            error_log(print_r($emb_term_slug, true));
            error_log(print_r($country_slug_emb, true));
            error_log(print_r($country_id_emb, true));

            wp_set_post_terms($post_id, $country_id_emb, 'countries');
     
        }
        if ( !empty( $disembarkationcountry ) ){
     
            $dis_term_list = wp_get_post_terms($post_id, 'disembarkation-country', array("fields" => "all"));
            $dis_term_slug = $dis_term_list[0]->slug;
     
            $country_slug_dis = get_term_by('slug', $country_slug_dis, 'countries');
            $country_id_dis = $country_slug_dis->term_id;
                wp_set_post_terms($post_id, $country_id_dis, 'countries');
     
        }
    }
}

Note how I'm using print_r inside the error_log messages for variables, because anything that isn't simple text (e.g. an array) will be formatted more helpfully.

You should be able to see from the messages in debug.log whether at each step what is being returned and used is what is expected.

(This is a crude alternative to running a fully-fledged PHP IDE for debugging.)

Try that and if you are still stuck let me know.

#1090231

Good call on the debug log, that got me past another error I'd made here.

Ok, so with a few adjustments I've managed to get the embarkation and disembarkation taxonomies to save to the countries taxonomy successfully, though I'm finding that even though the cred form appears to create the voyage (it is visible in wp-admin), the frontend content for the voyage simply shows a 500 Internal Server Error and I can't see anything in the error log or debug log to correspond with it.

Here's the latest code...

// Manage Voyage Country Taxonomies
add_action('cred_save_data', 'cred_save_voyage_countries', 10, 2);
function cred_save_voyage_countries($post_id, $form_data) {
  
   $forms = [ 90, 110 ];
  
   if ( in_array( $form_data['id'], $forms ) )
        {
  
        error_log("starting...");
 
        $embarkationcountry = wp_get_post_terms($post_id, 'embarkation-country');
        $disembarkationcountry = wp_get_post_terms($post_id, 'disembarkation-country');
 
        error_log(print_r($embarkationcountry, true)); //should be array of term objects
        error_log(print_r($disembarkationcountry, true)); //should be array of term objects
      
        if ( !empty( $embarkationcountry ) ){
      
            $emb_term_list = wp_get_post_terms($post_id, 'embarkation-country', array("fields" => "all"));
            $emb_term_slug = $emb_term_list[0]->slug;
      
            $country_slug_emb = get_term_by('slug', $emb_term_slug, 'countries');
            $country_id_emb = $country_slug_emb->term_id;
 
            error_log(print_r($emb_term_list, true));
            error_log(print_r($emb_term_slug, true));
            error_log(print_r($country_slug_emb, true));
            error_log(print_r($country_id_emb, true));
      
        }
        if ( !empty( $disembarkationcountry ) ){
      
            $dis_term_list = wp_get_post_terms($post_id, 'disembarkation-country', array("fields" => "all"));
            $dis_term_slug = $dis_term_list[0]->slug;
      
            $country_slug_dis = get_term_by('slug', $dis_term_slug, 'countries');
            $country_id_dis = $country_slug_dis->term_id; 

	    error_log(print_r($dis_term_list, true));
            error_log(print_r($dis_term_slug, true));
            error_log(print_r($country_slug_dis, true));
            error_log(print_r($country_id_dis, true));             
      
        }

	error_log(print_r($country_id_emb, true));
	error_log(print_r($country_id_dis, true));

	$termsarray = array( $country_id_emb, $country_id_dis );

	error_log(print_r($termsarray, true));

	wp_set_post_terms($post_id, $termsarray, 'countries');

    }
}

And what I'm seeing in the error log...

[23-Aug-2018 13:14:07 UTC] starting...
[23-Aug-2018 13:14:07 UTC] Array
(
    [0] => WP_Term Object
        (
            [term_id] => 243
            [name] => Bangladesh
            [slug] => bangladesh
            [term_group] => 0
            [term_taxonomy_id] => 243
            [taxonomy] => embarkation-country
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
        )

)

[23-Aug-2018 13:14:07 UTC] Array
(
    [0] => WP_Term Object
        (
            [term_id] => 863
            [name] => Nauru
            [slug] => nauru
            [term_group] => 0
            [term_taxonomy_id] => 863
            [taxonomy] => disembarkation-country
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
        )

)

[23-Aug-2018 13:14:07 UTC] Array
(
    [0] => WP_Term Object
        (
            [term_id] => 243
            [name] => Bangladesh
            [slug] => bangladesh
            [term_group] => 0
            [term_taxonomy_id] => 243
            [taxonomy] => embarkation-country
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
        )

)

[23-Aug-2018 13:14:07 UTC] bangladesh
[23-Aug-2018 13:14:07 UTC] WP_Term Object
(
    [term_id] => 959
    [name] => Bangladesh
    [slug] => bangladesh
    [term_group] => 0
    [term_taxonomy_id] => 959
    [taxonomy] => countries
    [description] => 
    [parent] => 0
    [count] => 0
    [filter] => raw
)

[23-Aug-2018 13:14:07 UTC] 959
[23-Aug-2018 13:14:07 UTC] Array
(
    [0] => WP_Term Object
        (
            [term_id] => 863
            [name] => Nauru
            [slug] => nauru
            [term_group] => 0
            [term_taxonomy_id] => 863
            [taxonomy] => disembarkation-country
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
        )

)

[23-Aug-2018 13:14:07 UTC] nauru
[23-Aug-2018 13:14:07 UTC] WP_Term Object
(
    [term_id] => 1083
    [name] => Nauru
    [slug] => nauru
    [term_group] => 0
    [term_taxonomy_id] => 1083
    [taxonomy] => countries
    [description] => 
    [parent] => 0
    [count] => 0
    [filter] => raw
)

[23-Aug-2018 13:14:07 UTC] 1083
[23-Aug-2018 13:14:07 UTC] 959
[23-Aug-2018 13:14:07 UTC] 1083
[23-Aug-2018 13:14:07 UTC] Array
(
    [0] => 959
    [1] => 1083
)
#1090234

In addition to the above, I have tried using cred_submit_complete instead of cred_save_data but I still the the 500 error.

#1090241

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

What is the 500 error and when exactly do you see it?

A 500 error means a fatal PHP error, and so that should be reported in the error log.

#1090252

Hi Nigel,

The issue appears on the front end for a Voyage published through CRED but also happens if a Voyage is published via wp-admin.

My host is reporting that the pages become visible when running on php 7. I had avoided updating from 5.6 incase of backward compatibility issues in any of my custom code though I wonder if updating is now my only option.

Is it possible some of the php above is not compatible in version 5.6?

#1091190

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Jon

If you are having the problems when viewing Voyage posts on the front end then I don't see how this code comes into play.

The code runs only when you submit a Voyage post using a CRED form, it isn't run when you view a post.

And if it also happens when viewing posts that were added in the backend then this code isn't run at all.

The PHP errors should give you a clue about what's causing them. What are the actual errors?

#1091254

Hi Nigel,

You're right, testing without this code gives the same issue, so the code isn't the problem.

See this link for error: hidden link

I have accessed the server logs, the error log and the debug log and cannot see any records that coincide with this issue.

I think the issue may have something to do with the following...

<div class="form-group">
		<label>Which Vessel/s is this Voyage Available on?</label>
			<div class="checkbox-scroll-area">
          	  <p>Scroll for more...</p>
              [cred_generic_field field='voyage-vessel' type='checkboxes' class='' urlparam='']
				{
				"required":0,
				"validate_format":0,
				"default":[],
				"options":[ [wpv-view name="dynamically-generated-list-of-vessels"] ]
			  }
			  [/cred_generic_field]
    	    </div>
  	</div>

If no value is entered in this field, the 500 error appears.
If a value is selected, no error appears.

I have removed all php items that made this field required but the issue persists.

All other php associated with this field is below...

// New Voyage Form - Save Vessel Data
add_action('cred_save_data', 'save_voyage_vessels_data_action',10,2);
function save_voyage_vessels_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==90) {
        	$vals= isset( $_POST["voyage-vessel"] ) ? $_POST["voyage-vessel"] : array();
        	foreach($vals as $val) {
          	add_post_meta($post_id, 'wpcf-voyage-vessel', $val, false);
        }      
    }
}


// Edit Voyage Form - Update Vessel Data
add_action('cred_save_data', 'update_voyage_vessels_data_action',10,2);
function update_voyage_vessels_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==110) {

        	delete_post_meta($post_id,"wpcf-voyage-vessel");
        	$vals= isset( $_POST["voyage-vessel"] ) ? $_POST["voyage-vessel"] : array();
         
        	foreach($vals as $val) {
          		add_post_meta($post_id, 'wpcf-voyage-vessel', $val, false);
		
          }      
     }
}
#1091274

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hmm. That code all still relates to the CRED form, and you say the issue occurs whether creating posts with the form or in the backend, so it shouldn't be relevant.

The lack of anything in the logs for that 500 error is most peculiar.

I can't really see from a distance what the problem might be.

Do you want to provide me with a copy of your site and I can install it locally and take a closer look to see if I can identify what's happening?

hidden link

I'll mark your next reply as private.

#1092844

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Jon

Thanks for that, but duplicator was unable to extract the archives because of unspecified problem.

Can I get site credentials from you and I'll take a copy myself. I might use an alternative plugin.

#1092908

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Jon

I just noticed that all of your Toolset plugins are out of date.

I can't debug issues on older versions of the plugins, they need to be current.

Can you please update your Toolset plugins to the current versions and let me know that you have done that.

I recommend you make a current backup first.

Also, update Types first, which should fix the wrong plugin update version you currently see for Views.

Once you've done that, re-test the issue to confirm you still get the 500 error.

If so, I'll take a copy of the site then to test locally.

#1092911

Hi Nigel,

I'll begin updating then let you know.

Before I do, can you confirm the latest versions of your plugins are compatible with Toolset Starter and Toolset Starter Child Themes?

I ask because I notice you have discontinued these themes.

#1092915

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

They should be. It is correct that the themes are discontinued, but if we get reports that something breaks with them when updating Toolset plugins we will fix it.

But do take a backup first (which you should do as a matter of course in any case).