1

I'd like to set a query alter function that checks if the node.status condition is already set in the view's query, and if it's not I'd like to set it to only get published content. The following code doesn't seem to running on my app. Do you have any suggestions to make this work?

function hook_views_query_alter(&$view, &$query) {

    $found = false;

    foreach($query->condition as $condition) {
        if($condition = 'node.status') {
            $found = true;
        }
    }

    if(!$found) {
        $this->query->add_where(
            $this->options['group'],
            db_or()->condition('node.status', 1, '=')
        );
    }

I have > 100 views to implement this change on.

2
  • My question now has a question mark. Feb 3 '17 at 21:23
  • You wants to show only published content in a view right? Or you wants something apart from that.
    – DRUPWAY
    Feb 4 '17 at 6:08
0

Why not just set a filter in the View configuration and set Status as Published?

3
  • I'm working on an application that already has ~ 100 views and all but one view need to show only published content. Feb 3 '17 at 21:25
  • I see from your comment that you have ~100 views and you are looking to do this programmatically so that you don't have to edit each view. I highly recommend against that. You should edit your views. Otherwise the view (as it appears in the Views UI, or in your exported feature) will not match the actual behavior of your site and you will regret it later. That said, if you change just one view to add this filter, and then re-export your feature you may be able look at exactly what changes so that you can edit all your exported views (just test thoroughly to avoid human error)
    – bleen
    Feb 5 '17 at 16:03
  • That's some good insight, just setting a filter to only show published content shouldn't generate too much code, and should be easy enough to copy paste into all applicable files. Thanks bleen. Feb 6 '17 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.