Filtrer 'the_title' avec l'option de retourner le sous-titre?
2 réponses
- votes
-
- 2013-05-10
Jene suispas sûr debien comprendre votreproblème,maisje suppose que c'est votre énigme: comment accéder autitre quin'estpasmodifiépar votrefiltre,si vous lefiltrezpartout?
Vouspouvez utiliser lafonction
get_post_field()
pour obtenir une copiebrutede celui-ci àpartir de l'objet depublication.Cependant,au lieu dejouer avec la sortie (et de rendre vos donnéesenregistrées dépendantes de laprésence defiltres),je recommanderais detravailler sur lefractionnement d'untitre lors de l'enregistrement dumessage - affectez lapremièrepartie autitre comme d'habitudeet rangez la deuxièmepartie dans un champpersonnalisé.
I am not sure I understand your issue right, but my guess is your conundrum - how to get to the title that is unchanged by your filter, if you are filtering it everywhere?
You can use
get_post_field()
function to get a raw copy of it from the post object.However instead of messing with output (and making your saved data dependent on filters being present) I would recommend to work on splitting a title when saving post - assign first part to title as usual and tuck away second part into custom field.
-
Merci @rarst!+1,je vaisexplorer votreidée d'utiliser un champpersonnalisé.Je suppose qu'uninconvénient serait que l'application WPne sachepas comment recharger le sous-titre lors de lamodification d'un article.Thanks @rarst! +1, I'll explore your idea of using a custom field. I guess one disadvantage would the the WP app wouldn't know how to re-load the subtitle when editing a post.
- 0
- 2013-05-14
- mhulse
-
Vousne savezpas si c'estfaisable,mais au lieu de supprimer complètement le sous-titre dutitre avec lefiltre,ne pourriez-vouspas avoir un CSSpourmasquer la deuxièmepartie?Not sure if it's doable, but instead of removing the subtitle completely from the title with the filter, couldn't you have a CSS to hide the second part?
- 0
- 2013-05-14
- gdaniel
-
@gdaniel C'est unebonneidée;Jepense que [ceplugin] (http://wordpress.org/extend/plugins/visual-subtitle/)fait quelque chose de similaire.Malheureusement,pourmesbesoins,je nepensepas que ce serait optimal.J'ai vraimentbesoin d'un `
''et d'un`
``propres (c'est-à-dire quine contient aucunbalisage).
@gdaniel That's a decent idea; I think [this plugin](http://wordpress.org/extend/plugins/visual-subtitle/) does something similar to that. Unfortunately, for my needs, I don't think that would be optimal. I really need a clean `` and `
` (i.e. one that does not have any markup in it).
- 0
- 2013-05-14
- mhulse
-
@rarst J'aimis àjourma question avec une solutionpossible qui utilise [get_post_field ()] (http://queryposts.com/function/get_post_field/).@rarst I've updated my question with a possible solution that uses [get_post_field()](http://queryposts.com/function/get_post_field/).
- 0
- 2013-05-14
- mhulse
-
@MickyHulse,ilestplus conforme auxmécanismes du site depublier des solutionsen tant que réponses (même sur vospropres questions),veuillez le déplacer vers une :)@MickyHulse it is more in line with site's mechanics to post solutions as answers (even on own questions), please move it to one :)
- 0
- 2013-05-14
- Rarst
-
@Rarstmercipour letuyau!Terminé.Appréciez l'aide!:)@Rarst thanks for tip! Done. Appreciate the help! :)
- 0
- 2013-05-14
- mhulse
-
+50 @Rarst!Mercibeaucoup dem'avoirpoussé dans labonne direction.À votre santé!:)+50 @Rarst! Thanks so much for kicking me in the right direction. Cheers! :)
- 0
- 2013-05-15
- mhulse
-
- 2013-05-14
Basé sur ce conseilgénial de @Rarst :
Vouspouvez utiliser lafonction get_post_field () pouren obtenir une copiebrute àpartir de l'objet depublication .
Voici une (possible) solution queje viens degiflerensemble:
/** * Head/deck handling. * * Unaltered example title (no quotes): "First half | Second half" * * @see http://stackoverflow.com/a/16279114/922323 * @see http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/post-template.php#L118 * @see https://wordpress.stackexchange.com/questions/45589/ * @see https://wordpress.stackexchange.com/questions/99039/ */ /** * Private helper function to return a title or deck from the title field. * * @param $title { string } The `post_title`. * @param $part { string } One of "current" or "end". Default: 'current'. * @param $delim { string } Delimiter that separates title from deck. * @return { string } Title before or after delimiter. */ function _foo_the_title_and_deck($title, $part = 'current', $delim = '|') { # ((if there's no delim) ? (if the deck is requested return an empty string, otherwise return the unaltered title) : return the filtered title or deck) return (( ! strpos($title, $delim)) ? (($part == 'end') ? '' : $title) : trim($part(explode($delim, $title)))); } /** * Filter the `post_title`. * * @param $title { string } The post title. * @return { string } The filterd post title. */ function foo_the_title($title) { return _foo_the_title_and_deck($title); } # Filter `the_title`: add_filter('the_title', 'foo_the_title', 10, 1); // Is "10" an optimal priority in this case? # Filter `single_post_title`: add_filter('single_post_title', 'foo_the_title', 10, 1); // IBID? /** * Filter the "deck" from the `post_title`. * * @param $post_id { integer } Optional post ID. Default: FALSE. * @return { string } The deck from the post's title. */ function foo_the_deck($post_id = FALSE) { # Use or get the $post_id: $post_id = ($post_id) ? $post_id : get_the_ID(); return _foo_the_title_and_deck(get_post_field('post_title', $post_id), 'end'); } /** * Check for the existence of a deck. * * @param $post_id { integer } Optional post ID. Default: FALSE. * @return { boolean } TRUE if deck exists, otherwise FALSE. */ function foo_has_deck($post_id = FALSE) { if (foo_the_deck($post_id)) return TRUE; }
Utilisation auniveau dumodèle:
<h1><?=the_title()?></h1> <?php if (foo_has_deck()): ?> <h2 class="sh4"><?=foo_the_deck()?></h2> <?php endif; ?>
Cela semblefonctionner! Cependant,je n'aipasencoreeu letemps defaire destests approfondis.
Idées d'amélioration:
-
Conversionen simpleplug-in "must use" de POO.Voir lamise àjour 2013/05/15 ci-dessous. -
Incorporez desMerci au commentaire de @ DanStefancu,j'ai couvert ce cas d'angleen filtrantadd_filter
quiprennenten compte d'autresfonctionsnon affectéesparthe_title
,comme wp_title () .single_post_title
. - Autre?
MISE À JOUR DU 15/05/2013
J'ai créé un pluginpour ce codeet je l'aimisici (je suis ouvert aux commentaires). C'estmonpremierplugin WP,(je sais qu'ilpourrait être considérablement amélioré) alors soyezgentil. :)
Based on this awesome tip by @Rarst:
You can use get_post_field() function to get a raw copy of it from the post object.
Here's a (possible) solution I've just now slapped together:
/** * Head/deck handling. * * Unaltered example title (no quotes): "First half | Second half" * * @see http://stackoverflow.com/a/16279114/922323 * @see http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/post-template.php#L118 * @see https://wordpress.stackexchange.com/questions/45589/ * @see https://wordpress.stackexchange.com/questions/99039/ */ /** * Private helper function to return a title or deck from the title field. * * @param $title { string } The `post_title`. * @param $part { string } One of "current" or "end". Default: 'current'. * @param $delim { string } Delimiter that separates title from deck. * @return { string } Title before or after delimiter. */ function _foo_the_title_and_deck($title, $part = 'current', $delim = '|') { # ((if there's no delim) ? (if the deck is requested return an empty string, otherwise return the unaltered title) : return the filtered title or deck) return (( ! strpos($title, $delim)) ? (($part == 'end') ? '' : $title) : trim($part(explode($delim, $title)))); } /** * Filter the `post_title`. * * @param $title { string } The post title. * @return { string } The filterd post title. */ function foo_the_title($title) { return _foo_the_title_and_deck($title); } # Filter `the_title`: add_filter('the_title', 'foo_the_title', 10, 1); // Is "10" an optimal priority in this case? # Filter `single_post_title`: add_filter('single_post_title', 'foo_the_title', 10, 1); // IBID? /** * Filter the "deck" from the `post_title`. * * @param $post_id { integer } Optional post ID. Default: FALSE. * @return { string } The deck from the post's title. */ function foo_the_deck($post_id = FALSE) { # Use or get the $post_id: $post_id = ($post_id) ? $post_id : get_the_ID(); return _foo_the_title_and_deck(get_post_field('post_title', $post_id), 'end'); } /** * Check for the existence of a deck. * * @param $post_id { integer } Optional post ID. Default: FALSE. * @return { boolean } TRUE if deck exists, otherwise FALSE. */ function foo_has_deck($post_id = FALSE) { if (foo_the_deck($post_id)) return TRUE; }
Usage on template level:
<h1><?=the_title()?></h1> <?php if (foo_has_deck()): ?> <h2 class="sh4"><?=foo_the_deck()?></h2> <?php endif; ?>
It appears to work! Though, I haven't had time yet to do thorough testing.
Ideas for improvement:
Convert to simple OOP "must use" plugin.See 2013/05/15 update below.IncorporateThanks to @DanStefancu's comment, I've covered this corner case by filteringadd_filter
s that account for other functions not affected bythe_title
, like wp_title().single_post_title
.- Other?
2013/05/15 UPDATE
I've created a plugin for this code and put it here (I'm open to feedback). It's my first WP plugin, ever, (I know it could be considerably improved) so please be kind. :)
-
Vous devez égalementfiltrer `single_post_title`pour wp_title ().You should also filter `single_post_title` for wp_title().
- 1
- 2013-05-15
- Dan Ștefancu
-
Merci Dan!J'avais remarqué que `wp_title ()`n'étaitpas affectépar `the_title`;Jene savaispas sije devais égalementfiltrer cela.Mercipour le conseil/clarification.Je vousferai savoir dès quej'aurai ajouté cela àmonexemple de code.Merci!!!Très appréciée.:)Thanks Dan! I had noticed that `wp_title()` was not affected by `the_title`; I was not sure if I should filter that as well. Thanks for the tip/clarification. I'll let you know as soon as I have added that to my example code. Thanks!!! Much appreciated. :)
- 0
- 2013-05-15
- mhulse
-
Ma réponse a étémise àjour.J'ai également [créé un dépôt] (https://github.com/mhulse/wp-deck)pour une version depluginplus complexe,mais stupidement simple.My answer's been updated. I've also [created a repo](https://github.com/mhulse/wp-deck) for a more involved, yet stupidly simple, plugin version.
- 0
- 2013-05-15
- mhulse
Problème:
L'applicationiPhone de WordPress (et d'autres applicationspour smartphone liées à WordPress)ne permettentpas autre chose que les champs Titreet Corps (c'est-à-direpas d'accès aux champspersonnalisés).
Objectif:
Monprojet actuelnécessite quenous donnions ànosblogueursmobiles lapossibilité d'inclure un sous-titre avec leurspublicationsmobiles (et debureau).
Solution:
Je voudrais utiliser un délimiteurfacultatif dans letitre. Exemple:
Capture d'écran:
Où le
|
est le délimiteur qui sépare letitreprincipal:... du sous-titre:
Code requis:
Tout le codeintégré et leplug-in qui utilisent lesméthodes WP d'obtention de "titre" doiventtoujours renvoyer lamoitié avant le délimiteur (en utilisant l'exemple ci-dessus):
En d'autrestermes,par défaut , aucune fonction d'obtention detitrene renvoiejamais:
Mon codejusqu'àprésent:
Le code ci-dessousest un simplepoint de départ.
Comme vouspouvez le voir,je filtre
the_title
et je supprime:Enfaisant ce quiprécède,j'évite d'avoir àme soucier des autresfonctions crachant le délimiteur (et lestrucs qui le suivent),non? Je suppose quetoutes lesfonctions/méthodes d'obtention de "titre" seront affectéespar lefiltre
the_title
? Peut-être queje manque un cas de coinici? MISE À JOUR: J'aitrouvé un cas d'angle: wp_title () ... Jeme demande ce qu'il y a d'autre là-bas?Question (s):
Voici oùje suis coincé.
Commentpuis-je écrire unefonctionpersonnalisée (oufiltre/autre) qui renverra la secondemoitié dutitre?
Jejouais avec ceci:
Évidemment,celane fait rien d'utile (j'aibesoin depouvoirmanipuler la variable code/
$title
dansfoo_the_title()
).Parexemple,ce quej'aimerais vraimentfaireest quelque chose comme ceci (lepseudo code suit,ne pas utiliser dans lemonde réel ):
Conclusion:
Honnêtement,j'espère que vouspourrezm'aider àtrouver une conclusion. :)
MISE À JOUR (2013/05/14):
Voirma réponse ci-dessous .