1. It is not supported or inteded to create a JSON output with Views.
2. Views is a Data RENDER engine and not a Data PROVIDER engine
3. The best approach is to create a Custom ShortCode where you create the JSON output on your own.
4. Despite all this it is possible to create JSON with Views, but on your own responsibility and knowing the side-effects:
- Every Custom Filter, pagination, and whatsoever nice feature of Views is maiinly based on a HTML DIV that wraps the View Loop.
- This Wrapper is exactly what makes it impossible to create JSON with Views
- This Wrapper can be removed by this function:
https://toolset.com/forums/topic/views-not-working-after-installing-v1-11/#post-345294
- But then many things will NOT work in Views, and this we can not change.
- Another problem is, if the view where to reurn NO results (maybe nothing matches your query and "no results found" is triggered", your above Custom Function will BREAK because it applies only to the HTML COMMENTS "<!-- wpv-loop-start -->" and "<!-- wpv-loop-end -->"
- So that means, to apply the same filter to the "no results found" you need to add 2 more HTML comments to your View loop, wrapping the "no results found" section in the Loop.
- Then you would apply the same Custom Function as above, but changing the addressing HTML Comment to your Custom Comment.
Example:
add_filter( 'wpv_filter_wpv_view_shortcode_output', 'prefix_clean_view_output', 5, 2 );
function prefix_clean_view_output( $out, $id ) {
if ( $id == '375' ) {
$start = strpos( $out, '<!-- wpv--noloop-start -->' );
if (
$start !== false
&& strrpos( $out, '<!-- wpv-noloop-end -->', $start ) !== false
) {
$start = $start + strlen( '<!-- wpv-noloop-start -->' );
$out = substr( $out , $start );
$end = strrpos( $out, '<!-- wpv-noloop-end -->' );
$out = substr( $out, 0, $end );
}
}
return $out;
}
And then modify the LOOP in the View:
[wpv-layout-start]
[wpv-items-found]
<!-- wpv-loop-start -->
<wpv-loop>
</wpv-loop>
<!-- wpv-loop-end -->
[/wpv-items-found]
[wpv-no-items-found]
<!-- wpv-noloop-start -->
[/wpv-no-items-found]
<!-- wpv-noloop-end -->
[wpv-layout-end]
As you see now I male sure also the "no results" section would output a "clean" result.
As for Conditional inside the Loop in JSON case, this should not be a cause of issues, as long that Conditional also works on a native View.
Does it?
I see you use Custom ShortCodes in there.
So - even if I can not debug such a customized View output, I can suggest to frist try this in a "native" view - if it works, it should also work in a modifed View, but unfortunately as said, I can not go in depth debuggin here, as we basically do not support this modifcation of Views.