Skip Navigation

[Resuelto] Make More Consistent Relationship Naming Convention

Este hilo está resuelto. Aquí tiene una descripción del problema y la solución.

Problem: I want to get the parent post ID. Post relationships created in the new M2M system use dashes in their slugs, but post relationships migrated from the legacy system use underscores in their slugs. I would like to be able to programmatically determine the relationship slug to get related posts, but the naming convention is inconsistent.

Solution: Use the toolset_get_relationship API to inspect new or legacy migrated relationships, and use the toolset_get_related_posts API to get related posts from either migrated or new relationships.

function be_get_parent_id($atts){
   
    //Get current post object and ID
    global $post;
    $post_id_current = $post->ID;
   
    $a = shortcode_atts( array(
        'postid' => $post_id_current,
        'parent' => '',
    ), $atts );
 
    //get post type
    $post_id_current = $a['postid'];
    $post_type_current = get_post_type($post_id_current);
  
    //The Post relationship slug to check - NOTE THE NEW SYNTAX WITH - HERE
    $relationship_to_query = $a['parent']."-".$post_type_current;
   
    //Set the role the other post type has:
    $role = "parent";
   
//Get related posts with new API, if none, it'll return 0, if any, the ID (hence not 0)
    // try legacy method, fallback to new method
    $related_post = toolset_get_related_post( $post_id_current, array($a['parent'], $post_type_current), $role);
    if (! $related_post ){
        $related_post = toolset_get_related_post( $post_id_current, $relationship_to_query, $role);
    }
    return $related_post;
}
add_shortcode( 'be-get-parent-id', 'be_get_parent_id' );

Relevant Documentation:
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api

This support ticket is created hace 6 años, 6 meses. 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.

Hoy no hay técnicos de soporte disponibles en el foro Juego de herramientas. Siéntase libre de enviar sus tiques y les daremos trámite tan pronto como estemos disponibles en línea. Gracias por su comprensión.

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)

Etiquetado: 

Este tema contiene 9 respuestas, tiene 2 mensajes.

Última actualización por Christian Cox hace 6 años, 6 meses.

Asistido por: Christian Cox.

Autor
Mensajes
#902429

I've noticed that relationships created using the migration tool place an underscore in between post types whereas relationships created using the wizard use a dash. This could cause issues for me since I've created some logic in the site that can guess the relationship by doing [post type 1] + [underscore] + [post type 2]. Now I'm realizing this won't work for those created using the wizard unless I change the default name when stepping through the wizard. Let me know if I've misinterpreted anything. Thanks for the consideration.

- Aaron

#902502

Hi, can you provide a code example showing when you need to determine the post relationship slug? I would like to see if there's a better approach here. The new toolset_get_relationship API might be useful:

Here are two samples showing how to get relationship information in the new API:

$rel = toolset_get_relationship('cpta-cptb'); // m2m relationship slug
$rel = toolset_get_relationship(array('cpta','cptb')); // legacy relationship syntax

https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_get_relationship

#902535

I had created a shortcode that I could use to retrieve the parent post type's ID based on a specific post ID that I enter:

[be-get-parent-id postid="child_post_id_here" parent="parent_post_type_here"]

Would become an issue on the line defining $relationship_to_query.

This isn't a burning issue for me by any means, but thought it'd be worth raising especially since it's still in beta. Let me know what your thoughts are, and I'm certainly open to any better ways I could be going at this. I wrote the code before I realized the migration used an underscore whereas the wizard uses a dash. Thanks.

function be_get_parent_id($atts){
  
  	//Get current post object and ID
    global $post;
    $post_id_current = $post->ID;
  
  	$a = shortcode_atts( array(
	  	'postid' => $post_id_current,
        'parent' => '',
    ), $atts );

	//get post type
	$post_id_current = $a['postid'];
  	$post_type_current = get_post_type($post_id_current);
 
    //The Post relationship slug to check
    $relationship_to_query = $a['parent']."_".$post_type_current;
 
    //Set the role the other post type has:
    $role = "parent";
 
    //Get related posts with new API, if none, it'll return 0, if any, the ID (hence not 0).
    $related_post = toolset_get_related_post( $post_id_current, $relationship_to_query, $role);
 
    return  $related_post;
}
add_shortcode( 'be-get-parent-id', 'be_get_parent_id' );
#902550

I see, thanks. I think this could be accomplished with two separate calls to toolset_get_relationship. First, check to see if the legacy method works. If so, return that result. If not, try the new slug syntax and return that result. Something like this:

//The Post relationship slug to check - NOTE THE NEW SYNTAX WITH - HERE
    $relationship_to_query = $a['parent']."-".$post_type_current;
  
    //Set the role the other post type has:
    $role = "parent";
  
//Get related posts with new API, if none, it'll return 0, if any, the ID (hence not 0)
    // try legacy method
    $related_post = toolset_get_related_post( $post_id_current, array($a['parent'], $post_type_current), $role);
    if (! $related_post ){
        $related_post = toolset_get_related_post( $post_id_current, $relationship_to_query, $role);
    }
    return $related_post;

I assume the "parent" shortcode attribute is the parent post type slug. If not, this will need some adjustment.

I was trying a couple of different approaches and it turns out there is currently a bug in the toolset_get_relationship API. If you try to get a non-existent relationship slug, or if you submit an array of post type slugs that are not actually related, you will trigger a fatal error. So I would avoid trying to use the toolset_get_relationship API to determine whether or not a post relationship actually exists.

#902555
temp.jpg

Thanks. However, won't hard-coding in the dash cause it to not be able to find posts linked through a relationship that was migrated in? For example, the attached screenshot shows some of my legacy relationships that were migrated over using an underscore to separate the two post types (not a dash), so line 2 of your code would skip these (I think?).

#902596

Oh, line 2 doesn't actually perform a query, it just sets the value of the variable $relationship_to_query to be a concatenated string. The query using that variable doesn't actually happen until line 11, and only if the legacy syntax does not produce any results. So I think your legacy relationships will be caught by line 9.

#902602

I thought all posts moving forward (after the migration) would use the new relationships table for storing the relationship details (not the belongs_ meta variable). If that's the case, wouldn't it the legacy syntax only find relationships with the old belongs_ data? If it couldn't find the related post because it was created after the migration, it would then look for a it using the relationship PARENT-CHILD, but it wouldn't find any results because the migration wizard set the relationship slug as PARENT_CHILD. So effectively:

- The code would find related posts created prior to the migration
- The code would find related posts created after the migration provided the relationship was created using the regular wizard
- The code would NOT find related posts created after the migration if the relationship was created using the initial migration wizard

Let me know if I've gotten this wrong. Thanks.

- Aaron

#902621

- The code would NOT find related posts created after the migration if the relationship was created using the initial migration wizard
No, this is not the case. I just ran a test to confirm, and I would like to share the test with you to make sure we are on the same page. My post types are Book and Chapter, and they were both created before updating to the betas. The post relationship (one to many) was also created before updating to the betas. Then I migrated the relationship using the initial migration wizard. After migration, I created a new Book with ID 11 - "Oliver Twist". Then I created a new Chapter in that new Book - "Chap 1", with ID 12. Here is the test code:

add_shortcode( 'rel_test', 'rel_test_func');
function rel_test_func($atts)
{
  // chapter ID = 12, parent post type is book
  $book = toolset_get_related_post( 12, array( 'book', 'chapter' ), 'parent' );
  error_log('book: ' . $book);
  return '';
}

Here is the log:

[23-May-2018 19:59:41 UTC] book: 11

So the parent book was found as expected, even though the relationship was migrated into the new system.

#902784

Hi Christian,

You're right. I just tested the code and it works for me as well. Sorry, I just assumed it wouldn't work when I saw the slugs had underscores instead of dashes, but should have tested it out before jumping to conclusions. Sorry to bug you with this, but anyways I'm happy because you were able to stumble on that bug and now I've got cleaner code. Thanks for the help.

- Aaron

#902829

Okay great, and I just received word from our developers that the Fatal Error problem I mentioned in the toolset_get_relationship API will be fixed in the next release.