• Resolved saphod

    (@saphod)


    Hi!

    I want to log the ID of the post that has been visited when in single post view. The plugin where I wanna add this uses the “template_redirect” hook.

    First, I tried the following:

    if(is_single()) {
    	global $post;
    	$post_ID = $post->ID;
    }

    … resulted in a ‘0’ in the relating log table field.

    BTW:
    That field is called “post_ID” and has the structure BIGINT(20) NULL.

    Then, I found something mentioning $wp_query, so I tried:

    global $wp_query;
    if ($wp_query->is_single) {
    	$post_ID = $wp_query->post->ID;
    } else {
    	$post_ID = NULL;
    }

    Result is the same: ‘0’ in the relating log table field.

    Does anyone know what is wrong with the code?
    Help would be appreciated.
    Thanks!

    EDIT:
    As I just found out, the is_single() should already work at template_redirect, see this source. So, it all comes down to the $post or $wp_query class, right?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter saphod

    (@saphod)

    I tried

    global $wp_query;
    
    if (is_single()) {
    	$post_ID = 4321;
    } else {
    	$post_ID = 1234;
    }

    to test it.

    I only got ‘1234’s, even though I am sure I viewed a single post.
    Seems like is_single() does not work.

    I have now put

    global $wp_query, $post, $posts;

    at the very beginning of the function, but doubt that it’s gonna work.

    Any idea? Anyone?

    BTW:
    How can I set a variable to NULL so that MySQL actually shows NULL and not ‘0’? $variable = NULL did not work…

    Thread Starter saphod

    (@saphod)

    I am such an idiot!
    It wasn’t the hook template_redirect
    it was init!
    And as wp() hasn’t been called yet at init:
    no wonder it didn’t work!

    Changing to template_redirect made it work!
    Yippieh! ??

    Thread Starter saphod

    (@saphod)

    OK, ‘template_redirect’ does not give me the same information as ‘init’, e.g. when hooking into ‘init’, I can even see requests for non-posts, like /wp-admin/ and stuff, which I find more interesting.

    But, as I said, there is no way yet to get the post ID, as $wp_query is not yet initialized.

    Does anyone know a way how to get the post ID by the URI???

    My idea is to combine an antispam funtionality in terms of IP blocking (which should hook in as soon as possible) with a statistics module (for which I would need the post ID).

    Does anyone have a hint, maybe?
    Thanks!

    Thread Starter saphod

    (@saphod)

    In the German WordPress Forum, I was advised to use url_to_postid(), a WordPress Function from wp-rewrite.php. Think that is exactly what I need, although I doubt it will already work on init() as wp_query is not yet initialized there… damn…

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Get Post ID While Hooking Into template_redirect’ is closed to new replies.