Search code examples
phpdrupaldrupal-7

Drupal 7: How do I retrieve a node's Content Type from within a component's prepocess function?


I've got a component that requires me to get the content type of the node the component appears on. I saw there exists a function to get that for me:

node_type_get_name($node)

However, when I use this function within the components pre-process hook, eg:

 my_component_preprocess_my_component_theme(&$variables, $node) {
   dpm(node_type_get_name($node));
 }

I get nothing.

If I dpm($node); I get the title of the component, not the node.

Would anyone know how I can retrieve the node's content-type?


Solution

  • You can load current node like this:

    <?php
    $node = menu_get_object();
    if ( !empty($node) ) {
      print "Have node";
    }
    ?>
    

    So, you'll have full node loaded and can check it's type ($node->type) and anything else you need.

    https://www.drupal.org/forum/support/post-installation/2010-07-28/how-to-get-node-object-or-nid-for-the-current-page

    And if you don't have the node it means, of course, current page is not a node (maybe a view or some custom page...).