This title may get confused someone not familiar with coding in WordPress for a moment!
I am leaving some code here for my own reference as I think I will need to have this handy for a number of times or even share it with others that may need it as I continue to work on creating a Web Application using WordPress and Pods and a number of other cool plugins.
This I found from a very good post from SaltnPixels called Playing With Pods.
That said, here is the first peace of code that I will need to adapt on my own logic for traversing the different tables associated with relationship fields in Pods.
Basically the
field()
function will return an array of pod items from the relating post type. You can then go through these pod items and do what you want with them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//getting one pod item $pod = pods('animals', get_the_ID() ); //make sure it exists if( $pod->exists() ){ //get the related zoo's field and store it in a var $related = $pod->field('related_zoos'); //check if the field is empty. If not lets show some of the zoos! if ( ! empty( $related ) ) { foreach ( $related as $rel ) { //$rel is an array of one pod item echo get_the_title( $rel['ID'] ); } } } |
Here I am getting the zoos that are connected to this animal. Then I am going through each of them and echoing out each zoo’s name. I find the most important piece of info is the related ID’s. With those you can do everything.
Getting Related ID’s Easier
I don’t usually need all the stuff that comes with the related posts. An array of ID’s is usually simpler to work with for me. Here is a little trick to get the related ID’s as opposed to all of the stuff.
Above I have changed the field function to
field('related_zoos.ID')
which gets the ID’s only. Now when I make a for each loop, I’m looping through simply ID’s and nothing else. Pretty nifty. You can fine tune the field function to get a list of anything in those posts!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//getting one pod item same as before $pod = pods('animals', get_the_ID() ); //make sure it exists if( $pod->exists() ){ //get related ID's $related = $pod->field('related_zoos.ID'); //check if the field is empty. If not lets show some of the zoos! //NOTE: foreach loop only needed if the relationship field is multi-select if ( ! empty( $related ) ) { foreach ( $related as $id ) { echo get_the_title($id); } } } |
In fact the
field()
function can take a string that traverses through the tables and gets anything! I can dofield('related_zoos.zoo_location')
to get a list of zoo locations from each zoo related to this animal!