Hide flag field from certain nodes in view I'm new to Drupal, so I may be missing some "obvious" things

I've installed the flag module, so users can flag their content to make it appear on top of other views. The thing is, when I display the list of content to the user (including both published and unpublished nodes), flag shouldn't be available if the node is unpublished

I tried to alter the view using the hook hook_views_pre_render, but I don't seem to have access to the flag content for removing (I guess my hook is being called after the flag hook, but I'm not certain about that). I tried this:

function mymodule_views_pre_render{
  switch ($view-&gt;name) {
    case 'usernodes':
      foreach ($view-&gt;result as &amp;$row) {
        //Custom field with publish states, 3 means it is published
        if ($row-&gt;field_publish_state[0]['raw']['value'] !== '3') {
          //Unset the two values related to flags I could find
          unset($row-&gt;flagging_node_entity_id);
          unset($row-&gt;flagging_nodeuidisnotnull);
        }
      }
      break;
  }
}


But the flags are still rendered

What I think could work:


I could use the hook hook_views_post_render, and edit the second parameter ($output) but it feels wrong to actually override the HTML output (it would become a messy code)
I could change it using some Javascript, when the page loads, but it doesn't feel right
Using Views PHP and then inserting a Global PHP field (as noted by code.rider below), but users have access to views and they could make a mess with that field


What would be the best way to hide the flag field for certain rows?
Install the Views PHP module and enable it. This will allow you to
embed php into a view cell.
Add a new nid/node id field to your View. Make sure to check the
“Exclude from display” checkbox.
Add a new Content: Published field to your View. Make sure to check the
“Exclude from display” checkbox.
Rearrange your fields so that your hidden nid field and published
field  at the top of all fields. This is important. It needs to be
“available” as an element to the custom php field we are about to
add, and if it’s after, the custom php field won’t see it.
Add a new Global: PHP field.
add the following code to the Output Code section of the field (in
php):

if ($row->status) {
  print flag_create_link("the_machine_name_of_your_flag", $row->nid);
}

 Use  delimiters to enclose PHP code. 
Click the apply button


use flag field in Sort criteria for sorting content mean flagged content on top
this is a tested solution.
hope this solve your problem.