[Support request] Hook with conditions

Home Forums Support [Support request] Hook with conditions

Home Forums Support Hook with conditions

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #1424951
    Dominik

    Hi,
    is it possible to implement a hook with conditions?
    I want to exclude specific pages from indexing with the following tag:
    <meta name=”robots” content=”noindex, nofollow”>

    If the URL has a ? in the URL I want to place the code in the head of the site.

    thanks
    Manuel

    #1425300
    Leo
    Staff
    Customer Support

    Hi there,

    You will need a filter like this:
    https://docs.generatepress.com/article/generate_hook_element_display/

    Never seen any conditional tag for something like that though so you will need to do some research to see if it’s possible.

    #1425400
    Dominik

    Thanks for the hint. I tried this code but it fires on every page. Am I missing something?

    add_filter( 'generate_hook_element_display', function(  $display, $element_id ) {
    	$url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        if ( 1751 === $element_id && strpos($url,'?') !== true) {
            $display = true;
        }
    
        return $display;
    }, 10, 2 );
    
    #1425454
    Tom
    Lead Developer
    Lead Developer

    Hi there,

    Are you only looking for a ? character, or should something specific follow it?

    If it’s only a ?, you may be able to do this:

    if ( ! empty( $_GET ) ) {
    
    }
    #1426079
    Dominik

    Hi Tom,

    yes, I am only looking for a ? in the url string. I tried the code but now I have 2 Problems.

    1. The code fires when there is a ? with a string (www.domain.com/test?test) but it doesn’t fire when there is only a ? at the end (www.domain.com/test?)

    2. The hook I created (noindex tag in the head) is always active. Even when the code doesn’t fire. Do I have a wrong setup? I added an element (hook) wich fires on the whole site. And I added the php lines to my functions.php in the child theme. The element ID is the one I get from the URL (?post=1751)?

    
    add_filter( 'generate_hook_element_display', function(  $display, $element_id ) {
    	$url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        if ( 1751 === $element_id && ! empty( $_GET )) {
            $display = true;
            echo "$url";
            echo "$display";
            echo "$_GET";
        }
    
        return $display;
    }, 10, 2 );
    
    #1426717
    Tom
    Lead Developer
    Lead Developer

    In that case, the code you had was correct: https://stackoverflow.com/a/7118928/2391422

    However, the !== false part is important when using strpos. It looks like you changed it to true, which is likely why it’s not working.

    Try using the above code as is and it should do the trick.

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.