Closed (fixed)
Project:
Metatag
Version:
8.x-1.x-dev
Component:
Code
Priority:
Normal
Category:
Feature request
Assigned:
Unassigned
Reporter:
Created:
19 Feb 2019 at 23:34 UTC
Updated:
6 Mar 2026 at 00:45 UTC
Jump to comment: Most recent, Most recent file
Comments
Comment #2
demonde commentedYou could use
https://www.drupal.org/project/token_default
Comment #3
finex commentedHi @demonde: does token_default let use another token as default value or just a simple string?
Comment #4
markdc@demonde
I tried token_default, but it only seems to work for nodes. Could you please share with us how you got it to work?
Comment #5
thejimbirch commented@samuelmortenson has a great alter that allows you to use
||to specify anORstatement in metatags:https://gist.github.com/mortenson/8dc5a8c79edce7a216a7787fb2be4d48
Add that script to your theme or custom module, and enter your token as something like this:
[node:field_image:medium]||[node:field_legacy_image:medium]||/fallback.pngComment #6
maticb commentedThanks for the link that adds "or" to metatags, this should be included in the base module in some way :D
Comment #7
demonde commentedUsing OR for a fallback is a very helpful concept. I hope it will implemented in the metatags module soon.
Comment #8
jeroenthttps://gist.github.com/mortenson/8dc5a8c79edce7a216a7787fb2be4d48 is a great workaround. Let's set this issue to Needs Review to attract the maintainers attention and so he can decide in which direction this issue should move.
Comment #9
damienmckennaI think this could be handled by #2044621: Allow parent config to override empty values of more specific config.
Comment #10
thejimbirch commented@DamienMcKenna,
I'd like you to consider that this is not a duplicate of #2044621. If I understand it correctly, that ticket covers a more global solution allowing a fallback from Node to Global meta tag setting.
This ticket addresses the need for a fallback inside a setting, when the fallback needs to work from field to field.
Some scenarios I have used this for are:
Text field on a Paragraph falls back to node:summary
Teaser field falls back to node:summary
Social Media Image field falls back to Hero Image field
Thanks,
Jim
Comment #11
damienmckennaThere's also #3067803: Use custom delimiter instead of commas for multiple values to consider..
Comment #12
bburgMortenson's gist seems like a nice feature to add in token...
Comment #13
bohus ulrychI've found this thread and gist very useful. After applying custom code it works like charm!
Comment #14
danielvezaJust adding a +1 to the gist. Would be awesome to have this available OOTB within Metatag.
Comment #15
zanvidmar commentedI am also voting for Mortenson's gist because it is simple and powerful solution.
Comment #16
justin2pin commented+1 for adding this. It would be really useful to be able to chain multiple possible values with a delimiter. Simple patch is attached for handling || logic in MetaNameBase.php.
Couple thoughts:
- If this functionality gets added, perhaps it would be worthwhile to add a config setting for enabling "OR" functionality and choosing the desired delimiter, with "||" as the default.
- The attached patch splits the parsed value on "||". So... if the metatag actually contains the string "||", this will cause unintended results.
Comment #17
oaswebFrom my view Mortenson's gist would be highly welcomed as it seems to be a simple and powerful solution.
Comment #18
thejimbirch commentedMarking as Needs Review to get more eyes on it. Patch looks like a quite simple and elegant solution.
Comment #19
jwilson3Simple one liner; works awesome for my simple usecase where I was able to get rid of 50+ lines of custom code. Unfortunately the patch didn't apply to latest 8.x-1.x so here is a re-roll, with comment improvements: no need to reference the issue in the patch itself, and would be good to comment both kinds of delimiters (comma for multiple tokens and logical OR for fallback tokens).
I'm super tempted to RTBC, alas this really does need a handful of tests to ensure it behaves correctly. Particularly, would be good to explain what happens with strings that have multiple tokens separated by spaces, slashes, dashes periods, or other characters. Eg how would this work for a token that needed a trailing value?
or
Comment #20
inaw commentedI really like this feature, it gives us a lot of flexibility in the configuration of the meta description. The patch didn't apply to latest 8.x-1.x so here is a re-roll
Comment #21
damienmckennaJust to be clear - does everyone know you can have different default configurations for each content type? Do you need this functionality in addition to that?
Comment #22
thejimbirch commentedYes. This gives the ability to have the fallback of tokens inside each tag. Different default configurations for each content type is more global and unrelated.
Say we set up a "Description" field for our admins to specifically set the description meta tags. If they don't fill it out, we could fall back to [node:summary]
Images are a big one where I use this also. Have a Social Media Image field with a fallback to a Hero Image field, or an image field on a Paragraph.
The OR functionality lets you create a stack of tokens inside the tag, and will display the first one that it finds.
Changing to Needs Review so the patch in #20 will get tested.
Comment #23
thejimbirch commentedUpdating the title to reflect that this issue is for individual meta tag fields.
I am also changing the connected issue from Parent to Related as this does not rely on that.
Comment #24
thejimbirch commentedComment #25
chadmandoo commentedThis does not work
[token1]sometrailingvalue||[token2]sometrailingvalue
This does:
[token1]||[token2]sometrailingvalue
In my instanced i wanted to append something to the end no matter which one is evaluated. The patch can be reworked in a better way but its a start.
Comment #26
chadmandoo commentedComment #27
chandeepkhosa commentedIn my use case, I'd like to have fallback values for 2 metatags og:image & og:description.
Before applying the patch, I can confirm that "[node:field_metatag_image:entity:field_media_image:open_graph],https://www.uaces.org/sites/default/files/2021-07/UACES-Logo-TwitterCard..." works as expected for me.
However, if for og:description if I add "[node:field_summary_text],[site:slogan]" and leave the summary text empty, when it displays the fallback site slogan, it also adds an extra unwanted comma before it.
I tried the patch in #26 and it successfully applies for metatag 1.16 (currently the latest version).
I then changed the value to "[node:field_summary_text]||[site:slogan]" and it works perfectly without displaying the extra comma.
I also successfully tested by changing og:description to [node:field_intro_text_body]||[node:field_summary_text] on a node that has 2 field values like thejimbirch has described where one field falls back to another if empty
Comment #28
jay.dansand commented+1 RTBC of the patch in #26. I have the same need/use case: I want to append a common string to the end, which requires mixing "||" and the newly introduced "&&" operator.
My use case is an optional title override field (to separate administrative title from displayed title), either of which should terminate in " | [site:name]". With #26, my title tag is now:
[node:field_display_title]||[node:title]&& | [site:name]And it works great!
Comment #29
danielvezaAdding a POC patch for adding the handling of the || to the tokenManager service.
This is needed for the schema_metatag module. I debated for a long time about where to include the fix for this, but I think it makes sense to do it here rather than in schema_metatag.
Comment #31
danielvezaLets try this for the tests passing.
We may need to consider how to parse && in the Token Service if thats needed.
Comment #32
danielvezaComment #33
amaria commentedLatest patch in 31 actually breaks the && function for me. The one in 26 still works.
Comment #34
kclarkson commentedI confirm that patch from 26 is working as desired.
- I am on Drupal 9.34
- Patch applied cleanly to Metatags 8.x-1.19
I am using the following token patterns.
[term:field_taxonomy_description:summary]||[term:field_taxonomy_description:value]
I have created a custom taxonomy description long text with a summary field.
The goal is to use the summary if entered then use the description field.
Comment #35
thejimbirch commentedLooks like the patch in #26 has been RTBC'd in #34, #28, and #27.
While the patch in #31 broke some of the requested functionality.
I am removing all but the patch in #26 (3034248-22.patch) from the display for clarity's sake.
@TODO Document how to use
||and&&so site builders know how to configure. I'll figure out where is best to do that.Comment #36
gngn commented#26 worked for me too.
Comment #37
anybodyReally nice and helpful idea, while I'm unsure if this really belongs into Metatags. From my perspective, this should better be a separate contrib module for tokens, like token_conditions, .... Furthermore, I'd suggest requiring "()" brackets for such conditions to make it totally clear, in which order to evaluate.
Also don't underestimate the case where someone would like to use || as string, which would require escaping then.
In a separate module, all places using tokens would benefit from this logic, which is NOT Metatag specific. What do the Metatag Maintainers think?
Comment #38
anruetherWith #26 I can do:
[node:field_h4c_metatags:entity:field_h4c_metatags_title]||[current-page:title]&&[node:field_event_date:start_date:h4c_medium]But when I do one of:
[node:field_event_date:start_date:h4c_medium]:&&[node:field_h4c_metatags:entity:field_h4c_metatags_title]||[current-page:title][node:field_event_date:start_date:h4c_medium]:[node:field_h4c_metatags:entity:field_h4c_metatags_title]||[current-page:title]It only prints
[node:field_event_date:start_date:h4c_medium]:[node:field_event_date:start_date:h4c_medium]&&:[node:field_h4c_metatags:entity:field_h4c_metatags_title]||[current-page:title]Results in
[node:field_event_date:start_date:h4c_medium]Comment #39
jwilson3To generalize #38,
It sounds like after
&&is used, to split a string with tokens, if the left side is TRUE, the right side of the string is never printed.I wonder if this has something to do with the
arbitraryString, or if maybe token2 and token3 are both empty strings.What does the following produce?
Comment #40
damienmckennaHas anyone tried using Custom Tokens to do this? I'm disinclined to commit this functionality to the when this module exists.
#1798984 might help too.
Comment #41
pianomansam commented@DamienMcKenna it's hard to tell if the custom_tokens module would provide this functionality as it doesn't say much about what it does. But what it does say seems unrelated.
However, I too am inclined to find a more general approach to this issue. Something directly within a token and reusable anywhere tokens are. The closest thing I've found is the Token or module which doesn't even have a full release.
Comment #42
jwilson3> The closest thing I've found is the Token or module which doesn't even have a full release.
Additionally, Token or module has not been updated to support D9, and is otherwise unmaintained: #3234855: Offering to maintain Token or
Comment #43
pianomansam commented@jwilson3 I'm offering to take over that project. It's a pretty simple project, actually.
Comment #44
jwilson3🎉 Thanks @pianomansam!
I must say that I agree that placing the logic operands inside the token is a bit smarter approach by first glance.
Unfortunately the Token Or module wouldnt be a 1-to-1 replacement for patches here, because this issue supports the logical AND as well as OR.
I personally dont have a good use case for AND conditions, tbh. So yes, the documentation requested in #35 would be really useful. For that reason, this issue badly needs a summary update with some suggested and example usage.
Comment #45
pianomansam commented@jwilson3 I'm new to this issue, having just stumbled upon it today. Help me understand what AND condition this issue attempts to solve that isn't possible by simply putting two tokens next to each other, like this:
[field_one][field_two]Comment #46
jwilson3That is exactly what I'm asking @chadmandoo (who added logical AND to this patch in #25 to do, because I don't quite understand it either!
I read #25 twice and still don't understand what && does!
Comment #47
pianomansam commentedI'm pleased to report that I am now a maintainer of Token or and have successfully updated it to support Drupal 9. By enabling it, I think the original request on this issue is resolved. Can others weigh in?
Comment #48
thejimbirch commented@pianomansam The first difference in Token or that I can see is that it uses a single pipe |. I could see that as a bad thing as many sites use a pipe in their title tag, like
Page name | Site name.This issue uses || which is a PHP logical operator https://www.php.net/manual/en/language.operators.logical.php
To #25, && is also a logical operator, and I assume would print only if both had value (true if both $a and $b are true.). I've never had the need for that in meta tags, but someone in this thread did.
Comment #49
mxwright commented@thejimbirch The way I understand Token or to be used is solely in place of a given token. The single pipe is within the token, (ex: [node:field|node:field_other]) which means you can use Metatags as usual with further pipes or text in the tags. Updating it to use || would make sense from a semantic point of view, however either way I think it works and is a pretty clean solution.
The downside is that the module appears to only fallback to another token, not to other text like a static URL or site title or something, which is one of the use cases outlined in this issue.
Comment #50
pianomansam commented@mxwrite I think that could be added as a feature
@thejimbirch I too have never had to do that, and figuring out a way to do that inside a token seems pretty complicated. I wonder if writing a custom token might be the best approach versus a more generic approach.
That is correct. The regex that looks for the single pipe only looks for it inside a token. Pipes outside tokens are perfectly safe. And yes, while the double pipe is more semantically correct in PHP, it would be a breaking change for anyone already using the module.
Comment #51
pianomansam commentedFor what it's worth, the Token OR module now supports text fallback.
Comment #52
damienmckennaThat's just brilliant, pianomansam!
So rather than building this huge chunk of logic into Metatag for a small portion of site users, I think promoting use of Token OR would be a better idea! How about we add an item to hook_requirements and to the documentation recommending its use?
Comment #53
gngn commentedtoken_or has only 15 reported usages ...
I have been using the fallback mechanism from #26 for a couple of months now and everything works fine for me.
Comment #54
damienmckennaThis provides an extra piece to hook_requirements() and adds a mention in the README.md file.
Comment #55
damienmckennaComment #57
damienmckennaCommitted. Thank you all, especially pianomansam and danielbeeke for providing the Token OR module that makes this functionality available to all site uses, not just Metatag.
Comment #59
jwilson3Sadly there is still a usecase for the patch here due to the situation outlined in comment #49:
I hit this exact issue today on project, where we want a static image fallback for image_src, og:image, og:image:secure_url, and twitter:image metatags.
The metatag should have fallback logic following this pattern:
1) "Hero Banner" Paragraph type (containing a media image reference), if present.
2) "Featured Image" media image reference, if present.
3) a static image from the theme.
The tokens are:
1)
[node:field_hero_banner:0:entity:field_hero_image:entity:field_media_image:og_image]2)
[node:field_featured_image:entity:field_media_image:og_image]3)
[site:url]themes/custom/mysite/images/social-media-share.jpgBecause the "|" operator from Token Or is inside the token, you cannot produce a fallback that concatenates a token and a static string, which has been mentioned in several comments on this issue.
In other words, something like the following will not work with Token Or:
The only solution is to wrap "[site:url]/fallback.jpg" into a custom hook_tokens_info and hook_tokens implementation, or perhaps by using the Token default module, as was previously suggested, but that module appears to not work well with anything except nodes.
On the other hand, the one-liner at #19, and the follow-up in #20, or #26 still does the trick for this situation, with caveats mentioned in #38 and #39 (namely that the only place the static text can be used is in the last final fallback.
Comment #60
damienmckennaMaybe Custom Tokens could help?
Comment #61
jwilson3Thanks Damien, I looked at Custom Tokens very briefly — as you suggested it previously — but wasn't exited with what I saw on the project page, to be perfectly frank. (usage stats vs project age, security coverage, last commit, d9 compat / d10 compat issues in "needs review")
I did see an issue there that compared the module with https://www.drupal.org/project/token_custom and that module seems potentially more appealing to review. (Longer history back to D5, D6, D7, well-known maintainer/committer, stable release, better usage stats, but also many more open issues).
I solved my immediate need with the small patch from #26, but good to keep in mind for another look. In general, less thrilled to add two new modules (token_or + token_custom) versus a small contained and targeted patch to achieve the tightly scoped metatag fallback image for social media. But I understand the reasoning why you dont want to add the patch here — and it is totally fine.
Comment #62
jwilson3This is a clean reroll of the approach from #26 for metatag 2.0.
Comment #63
jwilson3🤦♂️
Comment #64
bramdriesenIs there a new issue open for discussion #59 ~ #63 ?
Because otherwise we'll be using this patch forever :)
Comment #65
damienmckennaIf there are changes you'd like to see in the Token Or module please take it up with that project, Metatag won't be getting involved in custom token logic when there are other solutions available.
Comment #66
pearls commentedTry to test but cannot apply patches #54-62-63.
Comment #67
jane_irwinHere's a reroll of #26 against 2.2.0.
Comment #68
jane_irwinComment #69
jane_irwinApologies; here's a working version.
Comment #70
anybodyFYI: I added a follow-up to list such helpful token modules and metatag extending modules on the module page - to let people help themselves easier... #3552557: List helpful additional modules on the module page and README.md
Comment #71
batkorThanks.
I reroll patch for 2.1.0