Hook for post and page load

I need to run a function when a particular post or page is loaded. Is there any hook that lets me check whether a post is being displayed during page load ?

Related posts

Leave a Reply

3 comments

  1. You can use the wp hook and check the global $wp_query object or any conditional.

    add_action( 'wp', 'wpse69369_special_thingy' );
    function wpse69369_special_thingy()
    {
        if (
            'special_cpt' === get_post_type()
            AND is_singular()
        )
            return print "Yo World!";
    
        return printf(
            '<p>Nothing to see here! Check the object!<br /></p><pre>%s</pre>',
            var_export( $GLOBALS['wp_query'], true )
        );
    }
    

    See: wp in codex.wordpress.org and wp in developer.wordpress.org

  2. I’ve quite often used the following to load in custom meta boxes on pages (rather than custom posts).

        add_action('admin_init','how_we_do_it_meta');
    
        function how_we_do_it_meta() {
    
            if ( $_SERVER['SCRIPT_NAME'] == '/wp-admin/post.php' ) {
    
                $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'];
                $template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
    
                if ($template_file == 'page-how-we-do-it.php') {
    
                    add_meta_box('how_we_do_it_who-meta', 'Who we work with...', 'how_we_do_it_who', 'page', 'normal', 'high');
    
                    add_action('save_post', 'save_how_we_do_it_meta');
    
                }
            }
        }