- This topic has 5 replies, 3 voices, and was last updated 3 years, 7 months ago by Tom.
-
AuthorPosts
-
August 31, 2020 at 5:49 am #1424951Dominik
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
ManuelAugust 31, 2020 at 8:38 am #1425300LeoStaffCustomer SupportHi 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.
August 31, 2020 at 9:43 am #1425400DominikThanks 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 );
August 31, 2020 at 10:14 am #1425454TomLead DeveloperLead DeveloperHi 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 ) ) { }
September 1, 2020 at 12:25 am #1426079DominikHi 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 );
September 1, 2020 at 9:17 am #1426717TomLead DeveloperLead DeveloperIn that case, the code you had was correct: https://stackoverflow.com/a/7118928/2391422
However, the
!== false
part is important when usingstrpos
. 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.
-
AuthorPosts
- You must be logged in to reply to this topic.