Afficher toutes les valeurs d'un champ personnalisé créé avec ACF sur une page
-
-
Veuillez être unpeuplus clair sur ce que vousessayezexactement de réaliser.ACFest conçupour afficher la sortie des champspersonnalisés sur lefrontend,et nonpour autoriser l'entréefrontend.Please be a bit more clear about what exactly you're trying to achieve. ACF is built to show the output of the custom fields on the frontend, not to allow frontend input.
- 0
- 2012-03-28
- SickHippie
-
2 réponses
- votes
-
- 2013-06-13
Lafonction
get_field_object
ACFpeut être utiliséepourobtenir desinformationset des optionspour un champ spécifique.Tout d'abord,vous avezbesoin de la clé de champ du champ spécifique que vous souhaitez afficher.Lors de lamodification d'ungroupe de champs,cliquez sur l'onglet des options d'écranen haut de lapage.Vous devriez voir une optionpourbasculer l'affichage de la clé de champ (elleestmasquéepar défautpour économiser de l'espace):
Unefois que vous avez la clé,vouspouvez charger l'objet champet afficher ses valeurs:
$field_key = "field_5039a99716d1d"; $field = get_field_object($field_key); if( $field ) { echo '<select name="' . $field['key'] . '">'; foreach( $field['choices'] as $k => $v ) { echo '<option value="' . $k . '">' . $v . '</option>'; } echo '</select>'; }
The
get_field_object
ACF function can be used to get info and options for a specific field.First you need the field key of the specific field you wish to output. When editing a field group, click on the screen options tab at the top of the page. You should see an option to toggle the display of the field key (it is hidden by default to save space):
Once you have the key, you can load the field object and output its values:
$field_key = "field_5039a99716d1d"; $field = get_field_object($field_key); if( $field ) { echo '<select name="' . $field['key'] . '">'; foreach( $field['choices'] as $k => $v ) { echo '<option value="' . $k . '">' . $v . '</option>'; } echo '</select>'; }
-
Ce seraitbien sinouspouvions référencer lenom,aussifacilement que d'utiliser la clé.de cettefaçon,si vous l'avez dans unpluginet que vous avezbesoin de letester sur une autreinstance de WordPress avec acf activé,vousn'avezpas à rechercher la cléet à lamodifier ànouveau simplementparce que votreenvironnement B.It would be nice if we could reference the name, as easily as it is to use the key. this way if have this in a plugin and ever needed to test it on another instance of WordPress with acf enabled, you don't have to hunt down the key and change it again just because your in environment B.
- 0
- 2018-08-09
- klewis
-
- 2012-03-27
Si vousessayez deproduire quelque chose si une case à cocher était cochée,utilisez:
<?php if(in_array('news', get_field('checkbox') )): ?> <h1>News was ticked!</h1> <?php endif; ?>
Si vousessayez d'afficher simplement une liste des options cochées,utilisez ceci:
<p>Categories: <?php get_field('checkbox'); ?></p>
Cela vous donnera untableau de valeurs que vouspouvezgérer avec une déclaration
foreach
. L'utilisation dethe_field('checkbox')
vous donnera une chaîne séparéepar des virgules des options que vouspouvez également diviser.Je vous suggère également de vous rendre sur le site d'ACF et deparcourir le Documentation. Laplupart des questions de cetype ytrouveront une réponse détaillée,et le développeurest également actif dans sesforums de support.
EDIT: Si vous voulez que la liste des options disponibles s'affiche dans unepagepourgénérer une requête dynamique,j'aiexactement ce qu'il vousfaut. C'est unepièce queje viens de créer hierpourextraire une liste deméta-valeurs àpartir d'une clé de champpersonnalisé donnée (en utilisant ACF). Je l'ai rendu assezgénériquepour vous. Il y a un autremorceau de JSpourgérer la requête ajax,et unmorceau dephpplutôt alambiqué quiproduit lesmessages résultants. Jene peuxpas vraiment les réécrire - le JSest un appel/réponse ajax standard WP orienté vers l'avant,et le PHPest un désordre de vérifications conditionnellespour les 12 différents champs ACF quenous affichons (dont 2 sont des répéteurs). Lesbases sont ce codeici,lebouton
onClick
appelle lafonction ajax dans unfichier JS séparé,et lephp de lafonction ajax lui-même définitessentiellement untableau d'argumentspour la requête,dont l'unest$selectedOption
ou$_POST['option']
commemeta_value. Celaesttransmis à unenew WP_Query( $args );
,quiestensuite utilisée dans uneboucle,dont la sortieest renvoyée auxjs viaadd_action('wp_ajax_the_ajax_hook', 'fetch_option_list');
etadd_action( 'wp_ajax_nopriv_the_ajax_hook', 'fetch_option_list' ); //for non logged-in users
.// Get list of meta_values for given meta_key and post_type (page, post, custom post type) function meta_list($key = '', $type = '', $status = 'publish'){ global $wpdb; $r = $wpdb->get_col($wpdb->prepare( " SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = '%s' AND p.post_status = '%s' AND p.post_type = '%s' ORDER BY pm.meta_value ASC", $key, $status, $type)); return $r; } // ADD EG A FORM TO THE PAGE function meta_ajax_frontend(){ $formlist = meta_list('metakey', 'posttype'); echo '<form id="optionSelect">'; echo '<select id="optionList" name="optionList">'; foreach($formlist as $fl => $val) { echo '<option>' . $val . '</option>'; } echo '</select>'; echo '<input name="action" type="hidden" value="the_ajax_hook" /> <input id="submit_button" value = "Search" type="button" onClick="fetch_meta();" /> </form> <div id="meta_list"> Please select an option from the list </div>'; }
If you're trying to output something if a checkbox was checked, use:
<?php if(in_array('news', get_field('checkbox') )): ?> <h1>News was ticked!</h1> <?php endif; ?>
If you're trying to just display a list of the checked options, use this:
<p>Categories: <?php get_field('checkbox'); ?></p>
This will give you an array of values that you can manage with a
foreach
declaration. Usingthe_field('checkbox')
will give you a comma separated string of the options that you can split up as well.I would also suggest you go to ACF's site and go through the documentation. Most questions of this type will be answered there in decent detail, and the developer is active in his support forums as well.
EDIT: If you're wanting the list of available options output into a page for generating a dynamic query, I have just the thing. This is a piece I just built out yesterday for pulling a list of meta values from a given custom field key (using ACF). I've made it fairly generic for you. There's another chunk of JS for handling the ajax request, and a rather convoluted piece of php that outputs the resulting posts. I can't really rewrite those - the JS is standard WP forward-facing ajax call/response, and the PHP is a mess of conditional checks for the 12 different ACF fields we're displaying (2 of which are repeaters). The basics are this code here, the button
onClick
calls the ajax function in a separate JS file, and the php for the ajax function itself essentially sets up an array of arguments for the query, one of which is$selectedOption
or$_POST['option']
as meta_value. That gets fed to anew WP_Query( $args );
, which is then used in a loop, the output of which gets fed back to the js viaadd_action('wp_ajax_the_ajax_hook', 'fetch_option_list');
andadd_action( 'wp_ajax_nopriv_the_ajax_hook', 'fetch_option_list' ); //for non logged-in users
.// Get list of meta_values for given meta_key and post_type (page, post, custom post type) function meta_list($key = '', $type = '', $status = 'publish'){ global $wpdb; $r = $wpdb->get_col($wpdb->prepare( " SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = '%s' AND p.post_status = '%s' AND p.post_type = '%s' ORDER BY pm.meta_value ASC", $key, $status, $type)); return $r; } // ADD EG A FORM TO THE PAGE function meta_ajax_frontend(){ $formlist = meta_list('metakey', 'posttype'); echo '<form id="optionSelect">'; echo '<select id="optionList" name="optionList">'; foreach($formlist as $fl => $val) { echo '<option>' . $val . '</option>'; } echo '</select>'; echo '<input name="action" type="hidden" value="the_ajax_hook" /> <input id="submit_button" value = "Search" type="button" onClick="fetch_meta();" /> </form> <div id="meta_list"> Please select an option from the list </div>'; }
-
Mm,sije fais cela,je sortirai les options assignées au "post",ce dontj'aibesoinest demontrertoutes les options dans une "page" comme une liste complète d'options.Mm, if i do this, i will output the options assigned to the "post", what i need is to show all options in a "page" as a complete list of options.
- 0
- 2012-03-28
- Bob
-
Je suis curieux de savoirpourquoi vous avezbesoin que la liste d'options dubackend s'affiche sur lefrontend.Voulez-vous simplement afficher la liste des options avec les éléments sélectionnés dans l'administrateur sélectionné?Si vousessayez de l'utiliser dans le cadre d'unformulaire (permettant à l'utilisateur demodifier les données vérifiées),cen'estpas lebonplugin ou labonneméthodepour lefaire.Cependant,si vous souhaitez que la liste d'options soit utilisée commepré-filtrepour réécrire la requête,j'aipeut-être ce qu'il vousfaut.Je vaisbientôtmodifiermonmessage ci-dessus avec ce codeici.I'm curious as to why you need the backend's option list showing on the frontend. Are you wanting to just display the options list with the items selected in the admin selected? If you're trying to use this as part of a form (allowing user alteration of the checked data), this isn't the right plugin or method to do so. However, if you're wanting the option list to use as pre-filter for rewriting the query, I may have just the thing for you. I'll edit my above post with that code here shortly.
- 0
- 2012-03-28
- SickHippie
-
Salutim Bob avec un autre acc,j'aibesoin des options dubackendpour créer une sorte de "menu" aveceux.Jepense que votre code récupère lesmessageset les options qui leur sont attribuées.Jen'aibesoin que de la liste des options comme celle qui apparaît sur lebackend lorsque vous créez un article.Je continuerai àtravailler avec votre codepour voir sije peuxtrouver quelque chose.Merci @SickHippieHi im Bob with another acc, I need the backend's options to create a kind of "menu" with them. I think that your code retrieves posts and the options assigned to them. I only need the list of options like the one that appears on the backend when you create a post. I will keep working with your code to see if i can figure out something. Thanks @SickHippie
- 0
- 2012-03-28
- Dunning-Kruger
-
Non,ilextrait la liste des options qui ont été sélectionnées àpartir de cette case à cocher - c'est-à-dire qu'il dit "voici la case à cocher,il y a desmessages auxquels les valeurs ont été attribuées 'option 1','option 2','option 4'et ainsi de suite. Ilextrait littéralement la listemeta_valueen fonction de cettemeta_key. J'en avaisbesoinpour une liste dynamique,mais si vous avez créé unbrouillon depublication,toutes les cases à cocher seront sélectionnées,toutes les options serontextraites d'untableaupour vous. C'est letableauJ'utilise le `foreach`pourpasseren boucle. Lesfonctions suivantes apportent la liste desmessages via ajax,maisj'ai laissé cepetit bout.No, it pulls the list of options that have been selected from that checkbox - that is to say, it says "here's the checkbox, there are posts that have been assigned values 'option 1', 'option 2','option 4' and so on. It literally just pulls the meta_value list based on that meta_key. I needed it for a dynamic list, but if you created a draft post will all checkboxes selected it will pull all options out in an array for you. That's the array I'm using the `foreach` to loop through. The later functions bring the list of posts via ajax, but I left that bit out.
- 0
- 2012-03-28
- SickHippie
J'utilise Champspersonnalisés avancés/ACF pour créer des champspersonnalisés.L'une d'ellesest une liste de cases à cocher qui affichent certaines options (option1,option2,option3 ...) .
Maintenant,je veux affichertoutes les options de ce champ sur unepage séparée dufrontend comme ceci:
Options:
- option 1
- option 2
- option 3
- ...
Commentpuis-je récupérertoutes les options avec des clés d'ACF?