Make relationships automatically bidirectional
-
I have a custom post type
work
and I would like each work to have a list of related works. If the page for work A includes a link to work B, then the page for work B should also include a link to work A.I have tried setting up such a relationship as follows:
MB_Relationships_API::register( array( 'id' => 'works_to_works', 'from' => array( 'object_type' => 'post', 'post_type' => 'work', 'meta_box' => array( 'title' => 'Related From', 'context' => 'advanced', 'empty_message' => 'Not related from another work', ), ), 'to' => array( 'object_type' => 'post', 'post_type' => 'work', 'meta_box' => array( 'title' => 'Related To', 'context' => 'advanced', 'empty_message' => 'Not related to another work', ), ), ) );
However this creates 2 metaboxes on the work entry page, in other words I have to manually create the reverse of a given relationship. Consider the following scenario:
- I’m editing work A and want to make work B a related work.
- I add work B using the Related To metabaox.
- I then also have to add work B to the Related From list. If I don’t this extra step, there will be no link to work A when I edit/view work B.
When registering a relationship, it would be really nice if there was a ‘bidirectional’ parameter which, when set to true (and when both ends of the relationship are of the same type?), would mean that only one metabox is displayed for an object A and any related object B added using this metabox would automatically show a link to object A.
I have tried several hacks to try and achieve this behaviour but have not managed to get any of them to work (I’m a WordPress newbie and have not yet quite got my head around the data model / code structure).
If I make the from metabox hidden and use the following 2 queries in the
single_work_php
script…
‘relationship’ => array(
‘id’ => ‘works_to_works’,
‘from’ => get_the_ID(),
)`
…and…
‘relationship’ => array(
‘id’ => ‘works_to_works’,
‘to’ => get_the_ID(),
)`
…this does not address the metabox issue on the work entry page – when editing work B, I cannot edit a link to work A created on work A’s entry page.I tried creating a trigger to automatically create reverse relationships (swapping from and to) but MySQL does not allow a trigger to insert another row in the same table that caused the trigger to fire.
I’ve also considered making the from metabox hidden and trying to add some Javascript that updates it whenever the the to box is changed. Not sure how to go about this though.
Note it would also be nice if:
- With relationships between objects of the same type, the metabox dropdown lists should exclude the currently edited object.
- One could have related objects sorted by title (or some other field).
Any ideas would be most welcome.
- The topic ‘Make relationships automatically bidirectional’ is closed to new replies.