Get selected value from dropdown menu, from an array? - php

I feel like I am really missing something here. I did some manual customizations on a short (wordpress) script and try to set a <select><option> to "selected" if it has been selected. In order to accomplish this, I tried to find out if the $term->id = similar to the selected option value (which is an ID as well). All good so far, but I cannot seem to get the submitted <select><option>. All it says is 'array'.
Below is my script. Does anyone see what I am doing wrong here? To be clear, it seems to be all about the $_GET["listing_cat"] here. Also when i try to print the $_GET["listing_cat"] within the foreach all it outputs is 'array'.
<form method="get" action="<?php echo trailingslashit( home_url() ); ?>" class="custsearch">
<select name="listing_cat[]">
<option value="1" disabled="disabled" <?php if(!count($_GET)>0 || !$_GET["listing_cat"] ){ echo 'selected="selected"';} ?>>Pls choose</option>
<?php
$cat_args = array(
'orderby' => 'id',
'parent' => 0,
'hide_empty' => false
);
$terms = get_terms('listing_category', $cat_args );
foreach ($terms as $term) {
printf( '<option class="level-0" value="' . $term->term_id .'"');
if($_GET["listing_cat"] == $term->term_id) { echo 'selected="selected"'; }
printf( '>%s</option>', $term->slug, $term->name );
}
?>
</select>
</form>

Ok here is all that i needed.. quite logical;). I put it into a function and needed the in_array() to check:
//category in dropdown
function the_refine_category_ui2() {
$cat_args = array(
'orderby' => 'id',
'parent' => 0,
'hide_empty' => false
);
$terms = get_terms('listing_category', $cat_args );
foreach ($terms as $term) {
printf( '<option class="level-0"');
if( in_array( $term->term_id, $_GET["listing_cat"] )) { echo 'selected ';}
printf('value="' . $term->term_id .'"');
printf( '>%s' . $term->term_id .'</option>', $term->slug, $term->name );
}
}

Related

WordPress custom post meta filter not displaying options when filter is set

I have two custom post types set up - "Books" and "Authors". I am using custom metadata which allows you to link a book to an author via a select box (by querying posts from the authors post type to create the select options).
This works fine, but I'm also trying to create a custom filter on the posts screen for the books post type that allows you to filter by author, which isn't behaving as expected. Here's the code I'm using to add the filter:
function book_filter() {
global $typenow;
global $wp_query;
if ( $typenow == 'book' ) {
$authors = new WP_Query(
array(
'post_type' => 'author',
'nopaging' => true
)
);
wp_reset_postdata();
/*
$authors = get_posts( array(
'post_type' => 'author',
'numberposts' => -1
));
*/
$current_author = '';
if( isset( $_GET['author'] ) ) {
$current_author = $_GET['author'];
} ?>
<select name="author" id="author">
<option value="all" <?php selected( 'all', $current_author ); ?>>All authors</option>
<?php
if ($authors->have_posts()) {
while ($authors->have_posts()) {
$authors->the_post();
if ($current_author == get_the_ID()) {
echo '<option value="' . get_the_ID() . '" selected>' . get_the_title() . '</option>';
} else {
echo '<option value="' . get_the_ID() . '">' . get_the_title() . '</option>';
}
}
}
/* foreach( $authors as $author ) { ?>
<option value="<?php echo $author->ID; ?>" <?php selected( $author->ID, $current_author ); ?>><?php echo get_the_title($author->ID); ?></option>
<?php } */
?>
</select>
<?php }
}
add_action( 'restrict_manage_posts', 'book_filter' );
function do_book_filter( $query ) {
global $pagenow;
$post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
if ( is_admin() && $pagenow=='edit.php' && $post_type == 'book' ) {
if (isset( $_GET['author'] ) && $_GET['author'] !='all' ) {
$query->query_vars['meta_key'] = 'author';
$query->query_vars['meta_value'] = $_GET['author'];
$query->query_vars['meta_compare'] = '=';
}
}
}
add_filter( 'parse_query', 'do_book_filter' );
Initially, all the authors are shown in the filter, and selecting an author to filter by does actually work. The problem is that, once it's been filtered, the authors disappear from the select box dropdown. I tried adding an else statement to if ($authors->have_posts()) {... and this confirmed that it isn't fetching posts from the authors post type after a filter has been set.
I'm also using another custom filter (removed from the code for simplicity) which just uses a standard array variable rather than a query and that one is working fine, so I guess it must something to do with the custom post type query.
You'll see in the code that I've tried get_posts (commented) as well as WP_Query but they both present the same issue.
Where am I going wrong here?

Custom dropdown list of terms as links (woocommerce, wordpress)

I want to add a custom dropdown list of an attribute (in this case it's the brand), with the options lead to the attribute page as a link.
I got this working
add_filter('woocommerce_before_shop_loop','wc_reg_for_menus', 1, 2);
function wc_reg_for_menus() {
$terms = get_terms( 'pa_marke' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<select>';
foreach ( $terms as $term ) {
echo '<option value="'.$term->name.'">'.$term->name.'</option>';
}
echo '</select>';
}
}
And I think I somehow need to add this part
get_term_link( WP_Term|int|string $term, string $taxonomy = '' )
Thank you!
Felix
Your code works well for getting values for a specific taxonomy (attribute).I only changed the get_terms function.
I also added some data attributes to get the taxonomy and slug of each term (option).
add_filter( 'woocommerce_before_shop_loop','wc_reg_for_menus' );
function wc_reg_for_menus() {
$terms = get_terms( array(
'taxonomy' => 'pa_marke',
'hide_empty' => false,
));
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<select id="shop_pa_marke">';
foreach ( $terms as $term ) {
echo '<option value="' . $term->name . '" data-taxonomy="' . $term->taxonomy . '" data-slug="' . $term->slug . '">' . $term->name . '</option>';
}
echo '</select>';
}
}
Then you will need to use a jQuery script to redirect the user based on the chosen attribute option.
add_action( 'wp_footer', 'redirect_after_select_option' );
function redirect_after_select_option() {
?>
<script type="text/javascript">
jQuery( function($){
$('#shop_pa_marke').change(function(){
const url = window.location.href;
const taxonomy = $(this).children("option:selected").data('taxonomy').replace('pa_','filter_');
const slug = $(this).children("option:selected").data('slug');
let urlParams = new URLSearchParams(window.location.search);
urlParams.set(taxonomy, slug);
window.location.replace( '?'+urlParams.toString() );
});
});
</script>
<?php
}
The code has been tested and works. Add it to your active theme's functions.php.
Thank you!
Just now I found a solution without jQuery, that works quite fine as well:
add_filter('woocommerce_before_shop_loop','wc_reg_for_menus', 1, 2);
function wc_reg_for_menus() {
$terms = get_terms( 'pa_marke' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<select onchange="location = this.value;">';
foreach ( $terms as $term ) {
echo '<option value="'.get_term_link( $term ).'">'.$term->name.'</option>';
}
echo '</select>';
}
}
Only after the new page loaded, the first option of the menu is selected again, but that´s ok for me, because it won't be displayed there later on.

Drop-down filter is not working as it should

My code:
<?php
function filter_profiles_by_country()
{
$url = get_site_url();
if ( $terms = get_terms( array('taxonomy' => 'country','orderby' => 'name') ) )
{
// if categories exist, display the dropdown
echo '<select name="categoryfilter" onchange="if (this.value) window.location.href=this.value">';
echo ' <option value="'.$url.'/profiles">All Profiles...</option>';
foreach ( $terms as $term )
{
// ID of the category as an option value
echo ' <option value="'.$url ."/country/". $term->name . '">' . $term->name . '</option>';
}
echo '</select>';
}
}
?>
When I click on All Profiles, it should take me to /profiles/ page. But it is not working.
<?php
function filter_profiles_by_country(){
$url = get_site_url();
global $wp;
$current_url = home_url(add_query_arg(array(), $wp->request));
if( $terms = get_terms( array(
'taxonomy' => 'country',
'orderby' => 'name'
) ) ) :
// if categories exist, display the dropdown
echo '<select name="categoryfilter" onchange="if (this.value) window.location.href=this.value"><option value="'.$url.'/profiles/">All Profiles...</option>';
foreach ( $terms as $term ) :
$loadedItem = $url."/country/".$term->name;
$selectedItem = ($current_url == $loadedItem)? "selected": "";
echo '<option '.$selectedItem.' value="'.$url ."/country/". $term->name . '">' . $term->name . '</option>'; // ID of the category as an option value
endforeach;
echo '</select>';
endif;
}
?>
Try this.

Trying to truncate string after it's called by loop via ajax

I have a table which include names, the last name of each entry needs to be truncated ex. Miles Davis becomes Miles D.
I achieve this with the following JS:
$('.trunc-name').each(function (d, td) {
$(td).text($(td).text().replace(/^(\S+)\s+(\S).*/, '$1 $2.'));
});
and the td class is set to trunc-name:
<td class="trunc-name"><?php foreach ($resident_name_terms as $object) { echo $object->name; } ?></td>
Those table contents (which are actually WP taxonomy terms) are filterable via a select form - the options of which are getting truncated too.
Select:
if( $terms = get_terms( array(
'taxonomy' => 'resident_name',
'orderby' => 'name'
) ) ) :
echo '<select name="resident_name_filter"><option value="" selected="selected">' . __( 'All Residents', 'mv' ) . '</option>';
foreach ( $terms as $term ) :
echo '<option class="trunc-name" value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
So far everything works fine. The problem is that when I change criteria via a select option for that column (built with AJAX), the newly outputted values are not truncated.
Query Params:
$relation = 'AND';
$params = array();
$args['tax_query']['relation'] = $relation;
foreach ( $taxonomies as $tax ) {
if( isset( $_POST[ $tax . '_filter' ] ) && !empty( $_POST[ $tax . '_filter' ] ) ) {
$args['tax_query'][] = array(
'taxonomy' => $tax,
'field' => 'id',
'terms' => $_POST[ $tax . '_filter' ],
);
}
};
Loop:
$query = new WP_Query( $args );
if( $query->have_posts() ) : ?>
<table style="width:100%" id="incident-reports">
<tr>
<th>Resident</th>
</tr>
<?php
while( $query->have_posts() ): $query->the_post();
$resident_name_terms = get_the_terms( $post->ID, 'resident_name' );
?>
<tr>
<td class="trunc-name"><?php foreach ($resident_name_terms as $object) { echo $object->name; } ?></td>
</tr>
<?php endwhile; ?>
</table>
endif;
Any help is, as always, greatly appreciated!
You need to run the truncate code in the success: function after it creates the new elements.
$.ajax({
...
success: function(response) {
... // code that adds the new HTML
$('.trunc-name').each(function (d, td) {
$(td).text($(td).text().replace(/^(\S+)\s+(\S).*/, '$1 $2.'));
});
}
});

Wordpress WP_Term_Query Custom Taxonomy Select Options

The below code works really well for pulling in a select option list for all the entries in a custom taxonomy called 'make'. It only pulls in parent level ones which is perfect.
<select id="make" name="make">
<option value="">--</option>
<?php $term_query = new WP_Term_Query( array( 'taxonomy' => 'make', 'parent' => 0 ) ); if ( ! empty( $term_query->terms ) ) {
foreach ( $term_query ->terms as $term ) {
echo '<option class="' . $term->name . '" value="' . $term->name . '">' . $term->name . '</option>';
}
} else {
};?>
</select>
However, i would like to create another identical version of this code but instead of pulling in a list of all the parent values, it should pull in all the child values. Not for a particular page or post, but should output a select list of ALL the child entries of a custom taxonomy, ignoring the parents. Any help is massively appreciated!
you could use get_term_children and get_term_by functions to build your second select:
<select id="make" name="make">
<option value="">--</option>
<?php
$term_query = new WP_Term_Query( array( 'taxonomy' => 'make', 'parent' => 0 ) );
if ( ! empty( $term_query->terms ) ) {
foreach ( $term_query ->terms as $term ) {
$term_children = get_term_children( $term->term_id, 'make' );
foreach($term_children as $children){
$child = get_term_by( 'id', $children, 'make' );
echo '<option class="' . $child->name . '" value="' . $child->name . '">' . $child->name . '</option>';
}
}
} else {
};
?>
</select>

Categories