Getting Woocommerce product price with Timber - woocommerce

How do I get the Woocommerce product price I would get using <?php echo $product->get_price_html(); ?> in a non Timber Wordpress template?
I tried {{ product.price }} but it triggers an error which says:
price was called incorrectly. Product properties should not be accessed directly.
I know that I can get it through the Woocommerce template using {% do action('woocommerce_single_product_summary') %}, but:
I want the raw unformatted text, not the content of the Woocommerce template.
the Woocommerce action also gets a bunch of other stuff I don't need.
So, how do I access it correctly?

I ended up adding a custom function to Timber that returns the raw price value. This goes in the functions.php file:
public function add_to_twig( $twig ) {
$function = new Twig_Function('myprice', function () {
global $product;
$myprice = $product->get_price();
return $myprice;
});
$twig->addFunction($function);
return $twig;
}
it can be used in any Twig template with {{ myprice() }}

Related

Display ACF fields on WooCommerce single product page via hook

This method works fine
Display ACF fields on WooCommerce single product page
but what if I want to use this code below. How do I have to format the code so that it works with the functions.php
$my_title = get_field('the_subtitle');
<?php if($my_title):?>
<span id="product-subtitle" class="product-subtitle subtitle"><?php echo $my_title;?></span>
<?php endif;?>

Search all posts by an author in Wordpress/Timber

I'm trying to display all posts by a given author on the search results page using Timber. I've found that this works if I manually type it in:
/s?&author_name={username}
But I need to create these links dynamically in a loop, and unfortunately Timber's User object doesn't have access to a User's username. Going by ID also doesn't work (/s?&author={author_id}).
What's the solution here?
I would suggest you make a function available in Twig which allows you to pass in the author id and return the author archive link via get_author_posts_url() or access the WP user class.
See documentation on how to achieve this:
https://timber.github.io/docs/guides/functions/#make-functions-available-in-twig
php
add_filter( 'timber/twig', 'add_to_twig_author_link' );
function add_to_twig_author_link( $twig ) {
$twig->addFunction( new Timber\Twig_Function( 'get_author_posts_url', 'get_author_posts_url' ) );
return $twig;
};
twig
{{ get_author_posts_url( author_id ) }}
If you need to access author archive via link, you can do it by Timber\Post object
{% for post in posts %}
{{ post.author.name }}
{% endfor %}
But as I understood, your problem is to pass user login into twig templates. This way you can add to a global context all of your users.
search.php
$ctx = Timber::context();
$ctx['users'] = get_users(); // it will return array of WP_User objects
Timber::render( 'search.twig', $ctx );
search.twig
{% for user in users %}
{{ user.user_login }} // this will show user login
{% endfor %}

Timber how to implement get_current_url wp

Ive been using Wordpress for more than a year now. But I was stuck with the implementation of Timber twig framework get the current URL. I tried these codes below codes but no luck,.
{{ site.url.current }}
{{ app.request.getRequestUri() }}
Twig templates engine: get current url
Have you tried:
URLHelper::get_current_url()
Doc: https://timber.github.io/docs/reference/timber-urlhelper/#get_current_url
So, you should be able to feed this as a variable into your template.
Or if you want to get a step further and extend Timber's Twig i.e. creating a filter or function like:
$twig->addFilter(new \Twig_SimpleFilter('is_current_url', function ($link) {
return (URLHelper::get_current_url() == $link) ? true : false;
}));
Which should bring things down to:
{{ 'http://example.org/2015/08/my-blog-post' | is_current_url }}
BTW: Internally, get_current_url() returns: $_SERVER['HTTP_HOST']/$_SERVER['SERVER_NAME'] + $_SERVER["REQUEST_URI"]
Adding ['current_url'] in functions.php under add_to_context function worked for me:
public function add_to_context($context)
{
// $context['foo'] = 'bar';
$context['current_url'] = Timber\URLHelper::get_current_url();
$context['site'] = $this;
return $context;
}
You then will be able to use it globally in your twig templates:
<pre>
Current Url: {{ dump(current_url) }}
</pre>

can i pass my php code to twig code of timber

I would like to know if I can convert any types of PHP code to twig, what I want to know is, for example, whether I can pass the code.
<?php
if (ICL_LANGUAGE_CODE == 'in'):?
to
{{ lang.en }}
Is there a way to add any PHP code and turn it into a twig and recognize it?
I use the Timber template for WordPress.
There is a good way to pass your functions (more correctly, register the function to Twig).
Using Timber Hook: timber/twig
There is a class in filter hook timber/twig could help us pass functions to Twig. It calls Timber\Twig_Function.
new Timber\Twig_Function(
'function_name_that_will_be_called_in_Twig',
'function_name_in_php'
);
// OR
new Timber\Twig_Function(
'function_name_that_will_be_called_in_Twig',
function( $input ) {
// anonymous function is ok too.
}
);
functions.php
add_filter( 'timber/twig', 'add_to_twig' );
function hello_in_php( $name = 'world' ) {
$hello = 'Hello ';
$hello .= $name;
return $hello;
}
function add_to_twig( $twig ) {
$func = new Timber\Twig_Function('hello', 'hello_in_php');
$filter = new Timber\Twig_Function('introduce', function( $name ) {
return "I'm ${name}!";
});
$twig->addFunction($func); //Registering a pre-defined function
$twig->addFunction($filter); //Registering a filter function
return $twig;
}
index.twig:
<p id='a'>{{ hello() }}</p>
<p id='b'>{{ hello('who?') }}</p>
<p id='c'>{{ "Batman"|introduce }}</p>
Result is:
<p id='a'>Hello World</p>
<p id='b'>Hello who?</p>
<p id='c'>I'm Batman!</p>
Source: https://timber.github.io/docs/guides/extending-timber/#adding-functionality-to-twig
You mean something like this comparison ?
{% if constant('ICL_LANGUAGE_CODE') == 'en' %}
{# your output here #}
{% endif %}

Can verbatim be used on contents of an include?

I'm sharing templates between client and server and would like to output the raw template inside a script tag which is possible with verbatim.
http://twig.sensiolabs.org/doc/tags/verbatim.html
However it would be nicer if this could be applied as a filter to the include but it doesn't seem possible?
I'm new to twig so excuse me if i've missed obvious functionality.
I ran into the same problem, and this page came up in my search results. In the time since this question was answered, the Twig developers added this functionality into the library. I figured I should add some details for future searchers.
The functionality to include raw text (aka for client-side templates using the same syntax as Twig) is accomplished with the source function.
Ie: {{ source('path/to/template.html.twig') }}
http://twig.sensiolabs.org/doc/functions/source.html
I was looking for something like this too because I'm using Twig.js for some client-side templating along with Symfony. I was trying to share templates between the server-side and client-side code, so I needed content to be parsed in some cases and treated as verbatim in others, which proved to be a bit tricky.
I couldn't find anything built into Twig to help with this, but luckily, it's pretty easy to extend Twig to get what you're looking for. I implemented it as a function, but you may be able to do it as a filter too.
services.yml
statsidekick.twig.include_as_template_extension:
class: StatSidekick\AnalysisBundle\Twig\IncludeAsTemplateExtension
tags:
- { name: twig.extension }
IncludeAsTemplateExtension.php
<?php
namespace StatSidekick\AnalysisBundle\Twig;
use Twig_Environment;
use Twig_Extension;
class IncludeAsTemplateExtension extends Twig_Extension {
/**
* Returns a list of global functions to add to the existing list.
*
* #return array An array of global functions
*/
public function getFunctions() {
return array(
new \Twig_SimpleFunction( 'include_as_template', array( $this, 'includeAsTemplate' ), array( 'needs_environment' => true, 'is_safe' => array( 'html' ) ) )
);
}
function includeAsTemplate( Twig_Environment $env, $location, $id ) {
$contents = $env->getLoader()->getSource( $location );
return "<script data-template-id=\"{$id}\" type=\"text/x-twig-template\">{$contents}</script>";
}
/**
* Returns the name of the extension.
*
* #return string The extension name
*/
public function getName() {
return 'include_as_template_extension';
}
}
Usage in Twig file
{{ include_as_template( 'Your:Template:here.html.twig', 'template-id' ) }}
If you have a Twig file like this:
<ul class="message-list">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
The output will be this:
<script data-template-id="template-id" type="text/x-twig-template">
<ul class="message-list">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</script>
The work is derived from Kari Söderholm's answer here. Hope that helps!

Resources