Skip to content

Issue in do_action implementation for twig #1528

@nkmaurya-dev

Description

@nkmaurya-dev

Hi Team,

I have found that the Timber is passing context by default to every do_action hook.

So if any callback function has any parameter or first parameter in case of multiple , that would be replaced as Timber context. It must be not happen, because any plugin or theme would have written them for their own use.

The timber is adding the action function to the Twig and passing the context there. I think it should not or in some way, if we can override that method to not the pass the context to any hook by default.

Please see the method add_timber_functions line: 37 and below is the do_action hook code snippet:
See: https://github.com/timber/timber/blob/master/lib/Twig.php

$twig->addFunction(new Twig_Function('action', function( $context ) {
	$args = func_get_args();
	array_shift($args);
	$args[] = $context;
	call_user_func_array('do_action', $args);
}, array('needs_context' => true)));

For testing , if I did comment the line: 42, it means no context is passing to the callback functions and everything works well.

I'm explaining here the detailed explanation of code flow. Its just an example of that issue.

In tease-product.twig, I have used the hook as:

{% do action( 'woocommerce_after_shop_loop_item') %}

and the plugin YITH WooCommerce Quick View used this hook in their class as:

add_action( 'woocommerce_after_shop_loop_item', array( $this, 'yith_add_quick_view_button' ), 15 );

where $this : current class object
yith_add_quick_view_button : the callback function

So function declaration is:

public function yith_add_quick_view_button( $product_id = 0, $label = '', $return = false ) {
	global $product;
                
	// get product id
	! $product_id && $product_id = yit_get_prop( $product, 'id', true );
	// get label
	! $label && $label = $this->get_button_label();

	$button = '<a href="#" class="button yith-wcqv-button" data-product_id="' . $product_id . '">' . $label . '</a>';
    $button = apply_filters( 'yith_add_quick_view_button_html', $button, $label, $product );

	if( $return ) {
		return $button;
	}

	echo $button;
}

Now, the first parameter i.e $product_id = 0 is automatically changed to Timber context, instead it should be 0 , if no value is passed for first parameter. Timber context is an array so it is causing the error in button HTML reasonably.

We can't force to pass the context as argument to do_action callback function.

Please suggest me here.

WordPress 4.8.1,
PHP 7.1,
Timber 1.4.1 (installed via WordPress.org)

Thanks,
Neeraj Maurya

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions