Skip to content

Instantly share code, notes, and snippets.

@axxe16

axxe16/functions.php

Created May 15, 2020
Embed
What would you like to do?
Crea filtro di ricerca per un campo ACF object #acf #filter #backend
//Crea filtro dropdown backend per un campo ACF di tipo object
/** Create the filter dropdown */
add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );
<?php
function wpse45436_admin_posts_filter_restrict_manage_posts(){
global $post;
$type = 'materiale';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
//add filter to the post type you want
if ('materiale' == $type){ //Replace NAME_OF_YOUR_POST with the name of custom post
$values = array();
//genero array [label] = valore per i campi option
$args = array(
'post_type' => 'product',
'posts_per_page' => 500,
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
$values[get_the_title()] = get_the_ID();
endwhile;
}
wp_reset_postdata();
?>
<select name="ADMIN_FILTER_FIELD_VALUE">
<option value=""><?php _e('Filtra per corso', 'wose45436'); ?></option>
<?php $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:''; foreach ($values as $label => $value) {
printf
(
'<option value="%s"%s>%s</option>',
$value,
$value == $current_v? ' selected="selected"':'',
$label
);
}
?>
</select>
<?php } } /** if submitted filter by post meta */
add_filter( 'parse_query', 'wpse45436_posts_filter' );
function wpse45436_posts_filter( $query ){
global $pagenow;
$type = 'materiale';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
//Replace NAME_OF_YOUR_POST with the name of custom post
if ( 'materiale' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') {
$query->query_vars['meta_key'] = 'corso'; //Replace META_KEY to the actual meta key
$query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
$query->query_vars['meta_compare'] = 'IN'; //necessario per la query di tipo object
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment