Skip Navigation

[Resolved] How to check if there are related posts

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

Problem:
How can we check if there is a related post to a currently displayed post?

Solution:
In simple cases you can use HTML conditional:
https://toolset.com/forums/topic/how-to-test-for-related-posts-to-post-of-current-view/#post-1522445

Or you can use the Custom Code here if it's more a complex scenario

https://toolset.com/forums/topic/conditional-check-if-there-are-related-posts/

This support ticket is created 4 years, 9 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.

Sun Mon Tue Wed Thu Fri Sat
- - 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00
- - - - - - -

Supporter timezone: Asia/Ho_Chi_Minh (GMT+07:00)

This topic contains 13 replies, has 2 voices.

Last updated by ericE-4 4 years, 9 months ago.

Assisted by: Beda.

Author
Posts
#1521975

I am using a view to loop through all posts that are "Lodge" custom post types.

I also have "Deal" post types that have a many-to-one relationship to lodges. the slug of the relationship is "lodge-deal".

In the loop of the view, I need to test for and output content only for Lodges that have at least one Deal post related to it.

I found the solution here (https://toolset.com/forums/topic/conditional-check-if-there-are-related-posts/) and have added the shortcode supplied (I renamed it "count_related") as follows:

add_shortcode( 'count_related', function( $atts = [] ){
   
    // provide defaults
    $atts = shortcode_atts( 
        array(
            'relationship'      =>   '',
        ), 
        $atts
    );
   
    global $post;
    $count = 0;
   
    $relationship = toolset_get_relationship( $atts['relationship'] );
   
    if ( $relationship ) {
   
        $parent = $relationship['roles']['parent']['types'][0];
        $child = $relationship['roles']['child']['types'][0];
        $type = $post->post_type;
   
        $origin = ( $parent == $type ) ? 'parent' : 'child';
   
        // Get connected posts
        $connections = toolset_get_related_posts( $post->ID, $atts['relationship'], array(
            'query_by_role' => $origin,
            'role_to_return' => 'other',
            'need_found_rows' => true )
        );
        $count = $connections['found_rows'];
   
    }
   
    return $count;
});

Then I added a conditional statement to my view as follows:

[wpv-conditional if="( '[count_related relationship="lodge-deal"]' gt '0' )"]
<div class="deal-badge"><i class="fas fa-tag"></i></div>
[/wpv-conditional]

However it only ever calculates '0'.

Is there a better way to accomplish this?

#1522445

You could always use HTML conditions to check if a post has related posts, even in a Many To Many Connection:

[wpv-conditional if="( '[wpv-post-title item='@relationship-slug.parent']' ne '' )"]
          has parents
[/wpv-conditional]
          
[wpv-conditional if="( '[wpv-post-title item='@relationship-slug.parent']' eq '' )"]
          has no parents
[/wpv-conditional]

In your code it seems the $relationship does not exist, that why it stays 0.
Can you ensure you registered the custom shortcode in Toolset > Settings > Front End Content > 3rd party shortcode arguments?
Also, can you try to use it like this:

[wpv-conditional if="( '[count_related relationship='lodge-deal']' gt '0' )"]

If then this still does not work, I will need to take a look directly, but I suspect this should solve the problems.

#1522819
Screenshot 2020-02-22 11.33.23.png

I confirmed the shortcode is registered (see attached image). I also tried the code you provided. Still doesn't work.

I didn't understand your bit about using HTML conditions...lodges and deal are related but not in a parent-child way, as far as I know. If they are, which is the parent and which is the child?

#1526583

That's determined in your Relationship settings when you create it, you can set aliases for parent and child.
However, I admit its not the smartest move, as you have no control over what happens if MORE than one post is there.

Let's debug your custom code then.
https://toolset.com/forums/topic/how-to-test-for-related-posts-to-post-of-current-view/#post-1521975

Please add a few lines of this to your code error_log(print_r($checked_data, true));

Insert this anywhere in the code you think there could be an issue and important data is getting asked by the program.
So, I'd start with global $post;

Just below that line - you insert error_log(print_r($post;, true));
We are telling the program to log to the error log of your system the variable $post.
You need to activate wp debug and error logging for this https://codex.wordpress.org/WP_DEBUG

Then load the page where that ShortCode is used on, or view, or CT. Important is that in some way or another this shortcode is executed on the place you later want it to work.

Then check your debug log file in the sytem and see what is output for $post
It should be a lot of data, including ID, postname etc
Or, it could be just empty. Then, it means you have no data in the $post global.

Similarly, you can proceed on each line of the code if the previous line is OK.
So let's assume you receive indeed the post object in the global $post as expected, you could check $relationship = toolset_get_relationship( $atts['relationship'] ); by adding just below that line the debug statement:
error_log(print_r($relationship, true));

Again, if everything is as expected move to the next line, etc.
You will find at some point either unexpected or empty data.

My tip is on the global $post
You might have more success by populating a posts object with $post = get_post();, if global post is an issue.

Please let me know if you can proceed with this, I am happy to give more advice on how to debug this together!

#1527417
Screenshot 2020-02-25 11.30.47.png

The debug output didn't show any output of the $post variable...is it possible the shortcode is not even being called? Attached is the a screenshot of my shortcode when I ran it with WP_DEBUG on.

The only thing in out output was a series of notices (one set for every loop I think):

Notice: Trying to access array offset on value of type null in /www/fishlodgescom_983/public/wp-content/plugins/wp-views/vendor/toolset/common-es/php/Rest/Route/ShortcodeRender/WithMeta.php on line 74

Notice: Trying to access array offset on value of type null in /www/fishlodgescom_983/public/wp-content/plugins/wp-views/vendor/toolset/common-es/php/Rest/Route/ShortcodeRender/WithMeta.php on line 78

Notice: Trying to access array offset on value of type null in /www/fishlodgescom_983/public/wp-content/plugins/wp-views/vendor/toolset/common-es/php/Rest/Route/ShortcodeRender/WithMeta.php on line 79

Notice: Trying to access array offset on value of type null in /www/fishlodgescom_983/public/wp-content/plugins/wp-views/vendor/toolset/common-es/php/Rest/Route/ShortcodeRender/WithMeta.php on line 81

#1528129

What does the simple shortcode in any page show?
Just insert [count_related], and check what it does.

I tried the code as you provided it in the begin, and it does not throw such notice.
It returns the post object, as expected.

When I create a relationship my-relationship and use the shortcode like [count_related relationship="page-post"] and i have 2 posts connected, the shortcode returns 2.
This is working in a single post, as well as in a View querying the related post type.

It even works if used in a conditional and registered as a shortcode in the settings:
[wpv-conditional if="( '[count_related relationship='page-post']' eq '2' )"]YES[/wpv-conditional]

Something is indeed not set up properly on the site.
Where do you include your code?

#1528139

The shortcode [count_related] just gives me "0" when I insert it on a page. Even when I use it on a page that has related posts, it gives "0"

Those notices could be from something else, I didn't mean to imply that they a result of this shortcode.

I include all custom PHP code in a plugin "My Custom Functions" (https://wordpress.org/plugins/my-custom-functions/). All other shortcodes seem to work fine, even when used in a conditional.

#1528193

Yes, well, the [count_related] always shows 0.
You will need to specify the relationship, as shown in my previous reply

As mentioned it works flawlessly on my install.
Please try this:

- delete the custom code and every occurrence of it from your site, no matter if in files, plugins or else
- delete also the registered or all related registered ShorCodes and functions in Toolset > Settings > Front end content
- take your code from here https://toolset.com/forums/topic/how-to-test-for-related-posts-to-post-of-current-view/#post-1521975 and put it to your theme's functions.php file, at the bottom of it (make sure there are no closing PHP tags)
- register the shortcode count_related in the adequate settings of Toolset
- create an M2M relationship and connect some posts to another post.
- Insert [count_related relationship='exact-slug-of-relationship'] to a post that is related

If this does not work there is an issue that is blocking the code.
You have 2 options:
- you see [count_related relationship='exact-slug-of-relationship'] or anything not executed. That means the shortcode function is not loaded and hence the shortcode can't work
- you see something that the custom code function can produce (like a 0, or else). That means the function is working and outputs results as by the program in that shortcode, and if you see 0 it means your code reaches 0, because there are missing details to build another result that 0.
This also means any line of code alike debug lines must work if planted into that function. It can't just skip the code if it is triggered.

The error_log(print_r($var, true)); will show what is the issue.
I suspect the plugin you use to deploy the code may fire too late or else at the wrong moment, for this to work.

#1529117

Sorry, I completely forgot that this shortcode requires an attribute to work. I was in a rush so I took your instruction "Just insert [count_related], and check what it does." verbatim.

I changed the shortcode on my test page to [count_related relationship="lodge-deal"]. and when I view the page (which as 2 related posts, I indeed get a "2" as the output.

So...the shortcode works.

Next, I tried inserting the following conditional statements on the same page:
[wpv-conditional if="( '[count_related relationship='lodge-deal']' gt '0' )"]There are more than 0 deals.[/wpv-conditional]
[wpv-conditional if="( '[count_related relationship='lodge-deal']' eq '0' )"]There are no deals.[/wpv-conditional]

Both produced nothing.

So, the shortcode works, but not in a conditional.

#1530141

The shortcode works in a conditional, please find my test results here https://toolset.com/forums/topic/how-to-test-for-related-posts-to-post-of-current-view/#post-1528129

Something is not right with the registration of the shortcode, maybe.
Try to delete it in the Toolset > Settings > Front end content > Third-party shortcodes, and add again.

Then also try to output the shortcode exactly as used in the HTML condition as standalone in the same place, just before your condition, to then see in the front end if you really get the output expected. Inspect the HTML to see that it is a raw value, if it is not, it will break.
It should be raw but one never knows, there might be spaces or other tags added.

Also, I suggest passing debug="true" to the HTML condition to see what it does under the hood.
See more on this here https://toolset.com/documentation/user-guides/views/conditional-html-output-in-views/#syntax

Then I also suggest checking, if another HTML condition works, maybe with the post title as the source, or else.

If all this does not help, can you add login details so I can see it live?
I'll need all necessary links and steps to the issue, and view or Content Template.

#1530289
Bildschirmfoto 2020-02-27 um 16.45.32.png

You've again the apostrophes issue.
Please use this:

[wpv-conditional if="( '[count_related relationship='lodge-deal']' gt '0' )"]
<div class="deal-badge"><i class="fas fa-tag"></i></div>
[/wpv-conditional]

You have some other syntax issues in the view.

<div class="mix [wpv-view name='build-mix-classes']" data-type="[types field='type' option="wpcf-fields-radio-option-1c5437b763c2f393b9e290c8c19ddd17-1"]3[/types][types field='type' option="wpcf-fields-radio-option-f261a7a323d08ff2a906a1e82b17eced-1"]1[/types]" data-price="[wpv-post-body view_template='lowest-per-day-price-raw']" data-rating="[wpv-post-body view_template='build-data-rating-for-mix']" data-coord="[types field='map-coordinates'][/types]" data-id="[wpv-post-slug]">

This should be

 <div class="mix [wpv-view name='build-mix-classes']" data-type="[types field='type' option='wpcf-fields-radio-option-1c5437b763c2f393b9e290c8c19ddd17-1']3[/types][types field='type' option="wpcf-fields-radio-option-f261a7a323d08ff2a906a1e82b17eced-1"]1[/types]" data-price="[wpv-post-body view_template='lowest-per-day-price-raw']" data-rating="[wpv-post-body view_template='build-data-rating-for-mix']" data-coord="[types field='map-coordinates'][/types]" data-id="[wpv-post-slug]">

I also tried to insert only the below on the view loop but nothing changes in the front end.
Only the right area goes grey, that's all.

YES
[wpv-conditional if="( '[count_related relationship='lodge-deal']' gt '0' )"]
              YES!
              [/wpv-conditional]

Hence we can't test this view, as it is clearly broken in the output or altered in a way that is not native, because if this would be native output we would see at least a string YES.

Can we duplicate this View, insert it in a page that is only designed with Toolset, then remove all from that loop and only test the questionable code?
I can't do this myself it seems, on every page, I have an overlay, that hinders me from editing.

Generally, I would suggest not to debug such issues in a view that has many potential other interferences.
I suggest instead making sure this works on "clean" (minimal and new) Views, inserted in a page that has no other interference.
If then it works we know it's a conflict with other software.

#1530965
Screenshot 2020-02-27 12.03.58.png

OK I created a new view "Conditional Problem test", also using Lodges as the content. The loop editor code of the view is as follows:

[wpv-layout-start]
	[wpv-items-found]
	<div class="container">
	<!-- wpv-loop-start -->
      	<wpv-loop>
          Testing [wpv-post-title]: I think there are [count_related relationship='lodge-deal'] related posts (deals). Let's see:
              [wpv-conditional if="( '[count_related relationship='lodge-deal']' gt '0' )"]
				Lodge [wpv-post-title] has [count_related relationship='lodge-deal'] deals.
			  [/wpv-conditional]
          <hr style="background-color: #999; margin: 10px;">
      	</wpv-loop>
    <!-- wpv-loop-end -->
    </div>
    [/wpv-items-found]
	[wpv-no-items-found]
		<strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>
	[/wpv-no-items-found]
[wpv-layout-end]

I've placed this view on a new page (hidden link), and it's the only thing on the page. The output again shows that the shortcode works fine, but does not calculate when in a conditional. See attached image.

#1531573
Bildschirmfoto 2020-02-28 um 14.08.26.png

I can't control any of the lodge posts or other screens, I am locked with a overlay, as previously shared.

I see however on the front end some outputs are 4, others 0, so the conditional should work.
I simplified the output to see the returned shortcode value:

0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 2 2

So, we have some values above 0
But now analyse the loop in HTML (see screenshot)
Something is adding spaces to the output.
Meaning, your conditional likely fails because of that un-clean output.
Even outputting just one post, produces that space.
This is likely due to a "class="elementor-widget-container optml-bg-lazyloaded"", which I am not entirely sure how this is added as I removed all HTML from the view.

As mentioned this needs to be tested in a clean page with only that View, it seems, however, the view was added with an Elementor widget?
This should be avoided, to test.

And finally, what we really need, is that ShortCode registered in the Toolset > Settings > Front End Content > Third-party shortcode arguments
It's not registered there, it is registered as function, which is wrong, you do not use the function here but the shortcode.

Can you delete it there, and add it to the ShortCodes section?
I think, after this, it should work. Note, I stripped the current view to a minimal output, as it is a testing view.
I suggest to then test this on the other view, and if not working, we must try to add element by element into the display until we find where the issue begins.

#1531617

>And finally, what we really need, is that ShortCode registered in the Toolset > Settings > Front End Content > Third-party shortcode arguments
It's not registered there, it is registered as function, which is wrong, you do not use the function here but the shortcode.

Seems like this was the problem all along. Too bad we didn't start there. I intuitively put the registered the custom shortcode in the "Functions inside conditional evaluations" section, since it was a "conditional evaluation" that I needed it to work in. Perhaps some feedback for your UX designers.

It works now...thanks!