Question

I created a shortcode for creating dynamic pages with the help of API data. If someone changes the page title I also want changes.

Now I have a dynamic page title in a shortcode function, but I need to run that variable in the 2nd function too.

1st Function Code:

$mainiid = $_GET['stattype'];
$title_new = $_GET['titype'];
$z123 = $title_new;

2nd Function code:

function custom_titles($z123) {

      global $wp;
      $current_slug = $wp->request;

      if ($current_slug == 'demo') {
        return $z123 . 'Foobar';
        print_r($z123);
      }
    }
    add_filter('wpseo_title', 'custom_titles', 10, 1);

I'm using Yoast plugin and my dynamic title was stored in var $z123 in the first function.

Was it helpful?

Solution

Filters take variables from the function where they are defined. So, the Yoast plugin defines the wpseo_title filter inside on of its functions and passes a variable with it. You cannot insert your own variable.

However, since you are still in the same page build, you can still access the $_GET variables inside your own filter. So the trick would be to isolate the snippet from your first function in a third function, which you call from the second function as well. So, you don't pass the variable, but construct it twice, making sure in this way that the same value is available both times. Like this:

function function1() {
  // your code ...
  $z123 = function3();
  // your code ...
}

function function2( $title ) {
  // your code ...
  $z123 = function3 ();
  // your code ...
}
add_filter( 'wpseo_title', 'function2', 10, 1 );

function function3() {
  $mainiid = $_GET['stattype'];
  $title_new = $_GET['titype'];
  $z123 = $title_new;
  return $z123;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top