Archived topic
Hook with conditions
5 replies · Started by Dominik on August 31, 2020
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
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.
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 );
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 ) ) {
}
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 );
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.