Get custom post type label instead of name - WordPress + Timber - wordpress

I created 3 custom post types in WordPress : dissertation, subject-imposed, subject-free
In each custom post type the user is allowed to create only ONE post.
I created a menu composed with those three custom post types which allow to switch from post to another from the same user.
But I got a problem. The menu item display the name of the post type and not the label.
I got : DISSERTATION / SUBJECT-IMPOSED / SUBJECT FREE
And I would like the label (labels are in french) : MEMOIRE / SUJET IMPOSE / SUJET LIBRE
How can I get the label instead ? Thank you in advance.
In single.php :
$post_queried = get_queried_object();
$context['post_type_current'] = get_post_type_object(get_post_type($post_queried));
$get_post_current_user = get_posts( array(
'author' => $current_user->ID,
'post_type' => array('dissertation', 'subject-imposed', 'subject-free'),
));
$context['list_posts_current_user'] = $get_post_current_user;
In single.twig :
<ul class="menu-secondary__list">
{% for item in list_posts_current_user %}
{% set active = (post_type_current.name == item.post_type) ? 'active' : '' %}
<li class="menu-secondary__item">{{ item.post_type }}</li>
{% endfor %}
</ul>

Two steps to fix this one, first ...
Convert into an array of Timber\Posts
$get_post_current_user is an array of WP_Posts we need to convert these to Timber\Posts in order to interact with Timber's methods. Many ways to do this, but the easiest ...
{% for item in Post(list_posts_current_user) %}
Access the type method:
Now you can use the Post::type() method in your Twig template and access the labels:
{{ item.type.labels.name }}
The {{ item.type }} property will give you everything from here:
https://developer.wordpress.org/reference/functions/get_post_type_object/

Related

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 %}

Display dynamically informations in a Symfony layout

I have a layout included in another one that display my menu. The labels of my menu items need to be dynamic (like the unread messages number of a mailbox). Then I did this :
My orders
(
{{ render(controller('MyController', {'etat':2})) }}
<span style="color:red">with {{ render(controller('MyController', {'etat':2})) }} in late</span>
)
I would like to display labels according to the number that return my controller. I don't know how to get it in a variable.
When rendering your template in your controller
return $this->render('twig_template_name.html.twig', array('variable_name' => $variable);
you pass a variable to the twig template in the array of options as I showed. Your code
{{ path('mypath',{'etat': '2' }) }}
prints a path defined in the routing.yml under the 'mypath' section and ends up adding a GET request variable to the link ('?etat=2'), if 'mypath' showed an absolute route 'www.website.com/yourpath',
{{ path('mypath',{'etat': '2' }) }} would produce 'www.website.com/yourpath?etat=2', which would send your controller for a route /yourpath/{etat} a variable etat with a value of 2 so all you need to do now is change 2 with an actual dynamic value which you receive from another controller.
I am not sure what etat is but lets say it's an article and it has it's id, you have a blog page with lots of articles and the controller that prints them all out sends an array of articles to the twig template, on your twig template you do something like:
{% foreach article in articles %}
{{ article.title }}
{{ article.story }}
read more
{% endforeach %}
And you end up something like:
Catchy Title
Awesome story about code without bugs and where deadlines depend on how creative and well designed and implemented the solutions are
[read more]
and you ofcourse click on "read more" and end up on the url ~/article/2 because the article had an id of 2, your controller for that url receives a variable id in the request, you do a $id = $_GET['id']; and grab the article from the repository and send it to the template.
Hopefully this answered your question, I am very tiered so forgive me if i was confusing which I surely was.

Get parent of term

I might have missed it in the Timber Docs but is there a possibility to get the parent terms of a given taxonomy?
two methods depending on Twig vs. PHP and what exactly you're looking to do.
Consider a post which as been assigned a category of "Politics" (which is a child category of "News")
Example 1: Get a parent term in a Twig file
<p>Find more posts in {{ post.category.name }} and {{ post.category.parent.name }}</p>
<!--- outputs as ... --->
<p>Find more posts in Politics and News</p>
Example 2: Get the top-level terms from a taxonomy
$context['parent_categories'] = Timber::get_terms(array('taxonomy' => 'category', 'parent' => 0));
Use in Twig like...
Top-level categories for my site are...
{% for term in parent_categories %}
<li>{{ term.name }}</li>
{% endfor %}
<!-- Outputs as... -->
<li>News</li>
<li>Sports</li>
<li>Opinion</li>
Let's say you are trying to use the parent of a category in a twig view. That was the case I tried to solve when stumbling upon this post.
In category.php you can get the parent category by getting the parent category ID of the currently viewed category:
$category = new TimberTerm();
$context['category'] = $category;
if ($category->parent) {
$context['parent_category'] = new TimberTerm($category->parent);
}
$category->parent corresponds to the ID of the parent category. It is null if the category doesn't have a parent. You can then use the resulting category in your template.
<a class="category_{{parent_category.slug|lower}}" href="{{parent_category.link}}">
{{parent_category.title}}
</a>

How can I print Google Books api description?

Hie I am trying to get the synopsis and other items like author and published date printed. But I am Able to achieve this only with certain search terms, an error occurs with other words or terms
Key "description" for array with keys "title, subtitle, authors, publishedDate, industryIdentifiers, readingModes, pageCount, printType, categories, maturityRating, allowAnonLogging, contentVersion, imageLinks, language, previewLink, infoLink, canonicalVolumeLink" does not exist.
I am using symfony and twig. this is what the twig file looks like :
{% for item in items %}
<article>
<img src="{{ item.volumeInfo.imageLinks.thumbnail}}"/>
<h4>{{ item.volumeInfo.title}}</h4>
{{ item.volumeInfo.description }}
<strong> {{ item.volumeInfo.publishedDate }}</strong><br/>
<b>{{ item.volumeInfo.authors | join }}</b>
</article>
What am I doing wrong? why does this work only sometimes ? how can I make it work correctly all the time?
class GoogleBooksController extends Controller
{
public function getVolumeAction($title)
{
$client =new client();
$response = $client- >get("https://www.googleapis.com/books/v1/volumes?q=$title");
$data=$response->json();
$items=$data['items'];
return $this->render('BookReviewBundle:GoogleBooks:volume.html.twig', array('items'=>$items
// ...
)); }
Thanks
I belive the description field is not mandatory, so you can do follow
{% if item.volumeInfo.description is defined %}
{{ item.volumeInfo.description }}
{% endif %}

Using doctrine database object in a template

I am new to Symfony and am finally beginning to understand how to query a database using a Doctrine. However, I am lost as far understanding how to use the database object content in a Twig template.
Lets say my database object contains product Id's, names, prices, for 50 different products. After I am done querying the database in the controller, I do the following, to pass the database object into the Twig template:
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
$dataObject; // contains query results
return $this->render('GreatBundle:Default:search.html.twig', array('word' => $word));
}
This is where I am stuck. Now I have a Twig template, I would like to pass the DB object from the controller and then print out the database data in my Twig template.
I appreciate any suggestions as to how I can accomplish this.
Many thanks in advance!
I'll respond with an example (more easier for me to explain)
You want to search something with a slug (the var $word in your example). Let's say you want to find a article with that.
So your controller :
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
// Search the list of articles with the slug "$word" in your model
$articleRepository = $this->getDoctrine()->getRepositoy('GreatBundle:Article');
$dataObject = $articleRepository->findBySlug($word);
// So the result is in $dataObject and to print the result in your twig, your pass the var in your template
return $this->render('GreatBundle:Default:search.html.twig', array('result' => $dataObject));
}
The twig template 'GreatBundle:Default:search.html.twig'
{% for item in result %}
{{ item.title }} : {{ item.content }}
{% endfor %}
Just look the second example in the Symfony2 Book (Sf2 Book - templating), you have to use the function "for" to parse your object (like an array in php !)
Example in your twig template :
{% for item in word %}
{{ item.id }} - {{ item.name }} - {{ item.description }}{# etc... #}<br>
{% else %}
<h2>Aoutch ! No data !</h2>
{% endfor %}
Ah, and it's not the good var in your render method (but it's was for your example !)
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
$dataObject; // contains query results
return $this->render('GreatBundle:Default:search.html.twig', array('word' => $dataObject));
}

Resources