Hook Do-action with Add_action - php

I am trying to call function, created with add_action using do_action:
In the function.php of the theme:
function bleute_utbi_service_type()
{
return "service";
}
add_action('utbi_service_type', 'bleute_utbi_service_type');
Now, I need to get the value of the function in a plugin file:
// 'x' plugin file:
function get_valor(){
$val = do_action('utbi_service_type');
echo "this is the valor:" . $val";
}
This way of doing is not working, $val return 'null'...why?

Action hooks do not return content, and honestly if you need an action hook to return content there is a pretty good chance that you are doing something wrong.
add_action() takes the identification of a function, in your case
bleute_utbi_service_type(), and puts it into a list of functions to be called
whenever anybody calls do_action().
Either use $params with your do_action and add_action and then set the $value in your add_action callback function or use filters to return contents. To know how return works with filters, u may refer here: Wordpress: How to return value when use add_filter? or https://developer.wordpress.org/reference/functions/add_filter/

If you want to do it with add_action than you have to follow this referenece by passing argument to add_action
Reference
else try using apply filters like this.
add above code in function.php:
function example_callback( $string ) {
return $string;
}
add_filter( 'example_filter', 'example_callback', 10, 1 );
function get_valor(){
$val = apply_filters( 'example_filter', 'filter me' );
echo "this is the valor:". $val;
}
and add below code to wherever you want to print:
get_valor();
hope it works for you :)

Related

why wp_title filter is not working at all?

I know there are other questions like this but didn't find a reliable answer. So:
First activate the thing (simplyfied code):
add_action( 'after_setup_theme', 'theme_setup' );
function theme_setup() {
add_theme_support('title-tag');
}
Second, delete title tag from header.php.
Third, on page templates, before calling get_header(), add something like this:
add_filter('wp_title', 'set_custom_title', 10, 3);
function set_custom_title($title, $sep, $seplocation){
return 'test';
}
Well, this is not working at all, in any template, being a page, an archive, a custom taxonomy or post type archive. No nothing. Wordpress is generating titles by itself.
Why? Am I doing something wrong? Note that this code once upon a time just worked: used in other sites/themes.
Is it maybe an issue of wp5.2.0?
So, thanks to #Vel, the answer is to re-add the title tag (even if in previous wp versions > don't know til what version you had to delete it form head instead).
Current working code for me:
//functions.php
add_action( 'after_setup_theme', 'theme_setup' );
function theme_setup() {
add_theme_support('title-tag');
}
//header.php
<title><?php wp_title('|', true, 'right'); ?> | <?php echo get_bloginfo('name') ?></title>
//page templates
$window_title = // do something
add_filter('wp_title', function($title, $sep, $seplocation) use($window_title){ return $window_title; }, 10, 3);
Try to use follows code -
add_filter('document_title_parts', function($titles){
return array('title' => 'Custom Title');
});
For anyone still having this issue of the wp_title filter not working, I'd suggest adding a higher priority value. The higher priority value will ensure that your filter is executed and not overriden by other filters in your theme or plugins installed. Please see below: (ref: https://developer.wordpress.org/reference/functions/add_filter/)
// the 9999999 priority value will force this filter to be executed closer to the end. A lower number corresponds with earlier execution
add_filter('wp_title', 'set_custom_title', 9999999, 3);
function set_custom_title($title, $sep, $seplocation){
return 'test';
}
In my case Yoast SEO was changing the way title was rendered and only the following worked:
function filter_lp_title($title) {
return 'New title';
}
add_filter( 'pre_get_document_title', 'filter_lp_title', 25 );

Replacing parent action of Custormizr theme

I created my own child theme. Everything works great except I can't seem to unregister a hoook.
$this is class TC_footer_main and the following code is in the __construct
add_action ( '__colophon' , array( $this , 'tc_colophon_center_block' ), 20 );
I tried several remove actions with no success. I am just trying to change/remove the footer:
remove_action( '__colophon' , 'tc_colophon_center_block' , 55);
or
remove_action( '__colophon' , array('TC_footer_main','tc_colophon_center_block') , 55);
I've also tried
remove_action( '__colophon' , TC_footer_main::$instance->tc_colophon_center_block() , 55);
But that threw an error as TC_footer_main was not loaded by the time my functions.php file ran.
I am just trying to change/remove the footer:
I think you're making it way more complex, to modify the output of the tc_colophon_center_block() method, than it has to be.
Just use the tc_credits_display filter:
add_filter( 'tc_credits_display', function( $html )
{
// Modify output to your needs!
return $html;
} );
to modify that block to your needs.
To totally remove the output (if that's allowed), simply use:
add_filter( 'tc_credits_display', '__return_null', PHP_INT_MAX );
You have further access to filters like:
tc_copyright_link
tc_credit_link
tc_wp_powered
to choose from.
That's it!
For your purpose add the following code in function.php. It will get call on after_setup_theme hook.
// replace parent function
function child_theme_function () {
// your code goes here
}
function my_theme_setup () {
remove_action( '__colophon', 'tc_colophon_center_block', 1000 );
add_action( '__colophon', 'child_theme_function', 1000 );
}
add_action( 'after_setup_theme', 'my_theme_setup' );
You can also try for overriding the parent class from child class as described here: https://thethemefoundry.com/tutorials/advanced-customization-replacing-theme-functions/
you werent too far away...one problem you may have is you are trying to remove the hook before it has been added by your parent theme..the class could be initialized at a later stage...
im not too sure when your hook runs, but hopefully its after init
add_action('init', 'remove_parent_hook');
function remove_parent_hook(){
remove_action( '__colophon' , array('TC_footer_main','tc_colophon_center_block') , 20); // needs to be the same priority
}
you can obviously now just add a action for your new function.
There is a offchance that a anonymous function has been added, often the significance of &$this is overlooked when trying to remove a hooked function. This is a pain because wp will assign a random string as the key name & the function name for the function, its different every time so it cant be guessed. But we can search for the function name within the key so something like this will work
function remove_anon_hk($hook, $function, $priority=10 ){
global $wp_filter;
$hooks= $wp_filter[$hook][$priority];
if(empty ($hooks))
return;
foreach($hooks as $hk=>$data):
if(stripos($hk, $function) !== false ){
unset($wp_filter[$hook][$priority][$hk]);
}
endforeach;
}
add_action('init', function(){
remove_anon_hk('__colophon', 'tc_colophon_center_block');
});

Wordpress add filter to the_content()

I'm trying to add a code to the_content() function. I tried the following
function add_something($content) {
echo "test";
}
add_filter( 'the_content', 'add_something', 6);
After adding the filter my posts return just the echo test without the content. How can I execute my custom code without omitting the content?
I would surmise you need something like that (if it's indeed a filter callback):
function add_something($content) {
return "test" . $content;
}
Seems what the docs say:
http://wordpress.org/support/topic/add-something-to-the_content
you omitted the return statement.
function add_something($content) {
echo "test";
... change $content ......
return $content;
}
Be advised that if you want to modify the content, you must append it to the variable. Using echo will output 'test' at the time the script is called. It will not append or prepend it to the_content()
Use this (the_content filter needs 1 parameter)
add_filter( 'the_content', 'add_something', 1);

Wordpress: Parameter for Shortcode function

I am trying to create a shortcode in Wordpress, in which the function that is called with the shortcode tag gets the shortcode tag as parameter.
So say I have
<?php
var $shortcode = 'my_shortcode_tag';
add_shortcode( $shortcode, 'my_shortcode_function');
?>
then I want 'my_shortcode_function' to know the shortcode tag by it was called. I know that I could use attributes as in [my_shortcode_tag tag='my_shortcode_tag'] when I call the shortcode in my actual post, but I want to be able to just write [my_shortcode_tag] and my function to know that it was called by that tag. Is there a way to do this?
This is sent in as the third argument to a shortcode function (as mentioned in the Shortcodes API).
for example:
add_shortcode( 'shortcode1', 'my_shortcode_function');
add_shortcode( 'shortcode2', 'my_shortcode_function');
function my_shortcode_function($atts, $content, $sc) {
return $sc;
}
this will output the name of the shortcode called for that function.

How to pass extra variables in URL with WordPress

I am having trouble trying to pass an extra variable in the url to my WordPress installation.
For example /news?c=123
For some reason, it works only on the website root www.example.com?c=123 but it does not work if the url contains any more information www.example.com/news?c=123. I have the following code in my functions.php file in the theme directory.
if (isset($_GET['c']))
{
setcookie("cCookie", $_GET['c']);
}
if (isset($_SERVER['HTTP_REFERER']))
{
setcookie("rCookie", $_SERVER['HTTP_REFERER']);
}
Any Ideas?
To make the round trip "The WordPress Way" on the "front-end" (doesn't work in the context of wp-admin), you need to use 3 WordPress functions:
add_query_arg() - to create the URL with your new query variable ('c' in your example)
the query_vars filter - to modify the list of public query variables that WordPress knows about (this only works on the front-end, because the WP Query is not used on the back end - wp-admin - so this will also not be available in admin-ajax)
get_query_var() - to retrieve the value of your custom query variable passed in your URL.
Note: there's no need to even touch the superglobals ($_GET) if you do it this way.
Example
On the page where you need to create the link / set the query variable:
if it's a link back to this page, just adding the query variable
<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>">
if it's a link to some other page
<a href="<?php echo esc_url(
add_query_arg( 'c', $my_value_for_c, site_url( '/some_other_page/' ) )
)?>">
In your functions.php, or some plugin file or custom class (front-end only):
function add_custom_query_var( $vars ){
$vars[] = "c";
return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
On the page / function where you wish to retrieve and work with the query var set in your URL:
$my_c = get_query_var( 'c' );
On the Back End (wp-admin)
On the back end we don't ever run wp(), so the main WP Query does not get run. As a result, there are no query vars and the query_vars hook is not run.
In this case, you'll need to revert to the more standard approach of examining your $_GET superglobal. The best way to do this is probably:
$my_c = filter_input( INPUT_GET, "c", FILTER_SANITIZE_STRING );
though in a pinch you could do the tried and true
$my_c = isset( $_GET['c'] ) ? $_GET['c'] : "";
or some variant thereof.
There are quite few solutions to tackle this issue. First you can go for a plugin if you want:
WordPress Quickie: Custom Query String Plugin
Or code manually, check out this post:
Passing Query String Parameters in WordPress URL
Also check out:
add_query_arg
Since this is a frequently visited post i thought to post my solution in case it helps anyone. In WordPress along with using query vars you can change permalinks too like this
www.example.com?c=123 to www.example.com/c/123
For this you have to add these lines of code in functions.php or your plugin base file.
From shankhan's anwer
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'c'; // c is the name of variable you want to add
return $vars;
}
And additionally this snipped to add custom rewriting rules.
function custom_rewrite_basic()
{
add_rewrite_rule('^c/([0-9]+)/?', '?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');
For the case where you need to add rewrite rules for a specifc page you can use that page slug to write a rewrite rule for that specific page. Like in the question OP has asked about
www.example.com/news?c=123 to www.example.com/news/123
We can change it to the desired behaviour by adding a little modification to our previous function.
function custom_rewrite_basic()
{
add_rewrite_rule('^news/([0-9]+)/?', 'news?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');
Hoping that it becomes useful for someone.
add following code in function.php
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'var1'; // var1 is the name of variable you want to add
return $vars;
}
then you will b able to use $_GET['var1']
<?php
$edit_post = add_query_arg('c', '123', 'news' );
?>
Go to New page
You can add any page inplace of "news".
One issue you might run into is is_home() returns true when a registered query_var is present in the home URL. For example, if http://example.com displays a static page instead of the blog, http://example.com/?c=123 will return the blog.
See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.
What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint(). It should be run during the init action as it affects the rewrite rules. Eg.
add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );
function add_custom_setcookie_rewrite_endpoints() {
//add ?c=123 endpoint with
//EP_ALL so endpoint is present across all places
//no effect on the query vars
add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}
This should give you access to $_GET['c'] when the url contains more information like www.example.com/news?c=123.
Remember to flush your rewrite rules after adding/modifying this.
to add parameter to post urls (to perma-links), i use this:
add_filter( 'post_type_link', 'append_query_string', 10, 2 );
function append_query_string( $url, $post )
{
return add_query_arg('my_pid',$post->ID, $url);
}
output:
http://yoursite.com/pagename?my_pid=12345678
This was the only way I could get this to work
add_action('init','add_query_args');
function add_query_args()
{
add_query_arg( 'var1', 'val1' );
}
http://codex.wordpress.org/Function_Reference/add_query_arg
In your case, Just add / after url and then put query arguments. like
www.example.com/news/?c=123 or news/?c=123
instead of
www.example.com/news?c=123 or news?c=123

Categories