PHP echo incremental number for each item in an array - php

I am using wordpress and am trying to create a dropdown list of users as a metabox within a custom post type.
I have been able to create the dropdown list as follows:
<?php
$users = get_users();
// Array of WP_User objects.
foreach ( $users as $user ) {
echo '<option value="select" >' . esc_html( $user->display_name ) . '</option>';
}
?>
However, the value needs to have an incremental number for each result, i.e. select-1, select-2, select-3 - how can I add this to my results?

Just use an integer which gets incremented.
<?php
$users = get_users();
$i = 0;
// Array of WP_User objects.
foreach ( $users as $user ) {
echo "<option value='select-$i' >" . esc_html( $user->display_name ) . "</option>";
$i++;
}
?>
Alternative: use a for loop directly:
<?php
$users = get_users();
// Array of WP_User objects.
for ($i=0;$i<count($users);$i++) {
$user = $users[$i];
echo "<option value='select-$i' >" . esc_html( $user->display_name ) . "</option>";
}
?>

if i understand correctly try this :
<?php
$users = get_users();
// Array of WP_User objects.
$counter = 1;
foreach ( $users as $user ) {
$value = "value".$counter;
echo '<option value="'.$value.'" >' . esc_html( $user->display_name ) . '</option>';
$counter++;
}
?>

Related

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.

Issue with PHP executing twice

I am displaying a list of filters using Isotope. The functionality works when the first part of the code works however, when the screen is resized the posts don't filter when it executes the last part... Any help is much appreciated!
<?php
$filterLinks = array();
$newarray = array();
$starter = array('name'=>'View All','slug'=>'*');
$filterLinks[] = $starter;
$taxterms = get_terms( $customTax );
if ( ! empty( $taxterms ) && ! is_wp_error( $taxterms ) ){
foreach ( $taxterms as $taxterm ) {
$datafilter = '.' . $taxterm->slug;
$newarray = array(
'name' => $taxterm->name,
'slug' => $datafilter,
);
$filterLinks[] = $newarray;
}
}
echo '<ul id="filters" class="desk-filters button-group">' ."\n";
foreach ($filterLinks as $links) {
echo '<li><button class="button" data-filter="' . $links['slug'] . '">' . $links['name'] . '</button></li>'."\n";
}
echo '</ul>';
// Drop down menu on mobile
echo '<div id="filters" class="resp-filters button-group">'."\n";
echo '<div class="resp-filter-btn">Select Filter</div>'."\n";
echo '<div class="resp-filter-content">'."\n";
foreach ($filterLinks as $links) {
echo '<a class="button" data-filter="' . $links['slug'] . '">' . $links['name'] . '</a>'."\n";
}
echo '</div>'."\n";
echo '</div>';
?>
Functionality Works:
echo '<ul id="filters" class="desk-filters button-group">' ."\n";
foreach ($filterLinks as $links) {
echo '<li><button class="button" data-filter="' . $links['slug'] . '">' . $links['name'] . '</button></li>'."\n";
}
echo '</ul>';
Functionality Doesn't Work:
// Drop down menu on mobile
echo '<div id="filters" class="resp-filters button-group">'."\n";
echo '<div class="resp-filter-btn">Select Filter</div>'."\n";
echo '<div class="resp-filter-content">'."\n";
foreach ($filterLinks as $links) {
echo '<a class="button" data-filter="' . $links['slug'] . '">' . $links['name'] . '</a>'."\n";
}
echo '</div>'."\n";
echo '</div>';
Is this because i'm executing it twice, just hiding one on desktop and showing the other on mobile?
Looking for some direction. Thanks in advance!
You're using id="filters" twice, which is improper use of the id attribute, since it should be unique. Not sure if that is of any concern?

How to display Product Attribute name instead of slug in each loop?

I have a attribute loop and attempting to display the Attributes names in the first selection of the <select> drop-down. But every-time I echo the name, the slug is displayed. So "pa_attribute_metal" is being displayed instead of "Metal".
Below is my current loop & the code I'm currently using. Clearly $attribute['name'] is not pulling the actual name.
$attributes = $product->get_attributes();
foreach ($attributes as $attribute):
echo '<select name="'.$attribute['name'].'" class="example">';
echo '<option name="'.$attribute['name'].'">'.$attribute['name'].'</option>';
echo '</select>';
endforeach;
What is the best way to pull the actual display name of the attribute through the each loop & display it in the <option>?
<select name="attribute_taxonomy" class="attribute_taxonomy">
<option value=""><?php esc_html_e('product attribute', 'woocommerce'); ?></option>
<?php
global $wc_product_attributes;
// Array of defined attribute taxonomies.
$attribute_taxonomies = wc_get_attribute_taxonomies();
if (!empty($attribute_taxonomies)) {
foreach ($attribute_taxonomies as $tax) {
$attribute_taxonomy_name = wc_attribute_taxonomy_name($tax->attribute_name);
$label = $tax->attribute_label ? $tax->attribute_label : $tax->attribute_name;
echo '<option value="' . esc_attr($attribute_taxonomy_name) . '">' . esc_html($label) . '</option>';
}
}
?>
</select>
while ($query->have_posts()) {
$query->next_post();
$result[] = $query->post;
$taxonomy = 'pa_size';
$meta = get_post_meta($result[$i]->ID, 'attribute_'. $taxonomy, true);
$term = get_term_by('slug', $meta, $taxonomy);
array_push($arrayValue, $term);
}
for ($j = 0; $j<count($arrayValue); $j++){
echo $arrayValue[$j]->name;
}

How to set my default option select?

I have a theme options page and a loop which grabs my categories. This code works fine and I am able to save my options. The code like this:
function drop_elements_function(){
$my_cats = get_categories();
$i = 1;
foreach( $my_cats as $my_cat ) :
$my_categories[$my_cat->cat_ID] = array(
'value' => $my_cat->cat_ID,
'label' => $my_cat->cat_name
);
$i++;
endforeach;
$options = get_option('sandbox_theme_social_options');
echo'<select id="featured_cat" name="sandbox_theme_social_options[Drop_Elements]">';
foreach ( $my_categories as $category ){
$label = $category['label'];
$selected = '';
if ( $options['Drop_Elements'] == $category['value'] )
$selected = 'selected="selected"';
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
}
echo '</select>';
//print_r($options['Drop_Elements']);
}/*Function end*/
The output looks like this:
http://www.vasinternetposao.com/img.png
Problem: Now when my theme is installed for the first time i am getting the output like the screen shot above but obviously my option is not yet saved to the database (user must click the save button in order to select that category). So i was thinking to do something like this:
1.) User install the theme for the first time and then output looks like this:
http://www.vasinternetposao.com/img2.png
2.) If user unintentionally select "Choose your category" and clicks the "save button"
the output will be again:
http://www.vasinternetposao.com/img2.png
3.) If the user select the real category (not "Choose Your Category") then "Choose Your Category" Disappears:
http://www.vasinternetposao.com/img.png
This is my attempt but it is not working:
function drop_elements_function(){
$my_cats = get_categories();
$i = 1;
foreach( $my_cats as $my_cat ) :
$my_categories[$my_cat->cat_ID] = array(
'value' => $my_cat->cat_ID,
'label' => $my_cat->cat_name
);
$i++;
endforeach;
$options = get_option('sandbox_theme_social_options');
echo'<select id="featured_cat" name="sandbox_theme_social_options[Drop_Elements]">';
foreach ( $my_categories as $category ){
$label = $category['label'];
$selected = '';
if ( $options['Drop_Elements'] == $category['value'] ){
$selected = 'selected="selected"';
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
}
elseif(!isset($options['Drop_Elements'])){
$selected = 'selected="selected"';
echo '<option selected="selected" value="Choose Your Category">Choose Your Category</option>';
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . '>' . $label . '</option>';
}
}/*Foreach close*/
echo '</select>';
//print_r($options['Drop_Elements']);
}/*Function end*/
Can it be done with PHP? Any help is appreciated! Thank you!
I think what you want to do is something like the following example:
echo '<select id="featured_cat" name="sandbox_theme_social_options[Drop_Elements]">';
echo '<option selected="selected" value="Choose Your Category">Choose Your Category</option>';
foreach ( $my_categories as $category ){
$label = $category['label'];
$selected = ( $options['Drop_Elements'] == $category['value'] ) ? " selected='selected' " : "";
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
}
echo "</select>";

Dumping an Array

I have a fairly basic setup with Wordpress Advanced Custom Fields. I have a need to add extra fields to a custom post and then display them on the post page. I have this code that DOES work, but when I got to a custom field that has multiple checkbox selections, obviously that particular field dumps out the word ‘array’, as it is an array.
How can I make this code below, dump all labels and data for regular fields as well as for fields that have an array in them.
$fields = get_field_objects();
if( $fields )
{
echo '<div class="item-info-custom">';
echo '<dl class="item-custom">';
echo '<dt class="title"><h4>Custom Information</h4></dt>';
foreach( $fields as $field_name => $field )
{
echo '<dt class="custom-label">' . $field['label'] . ': </dt>';
echo '<dd class="custom-data">' . $field['value'] . '</dd>';
}
echo '</dl>';
echo '</div>';
}
This is the final code that I got to work:
<?php
$fields = get_field_objects();
if( $fields )
{
echo '<div class="item-info-custom">';
echo '<dl class="item-custom">';
echo '<dt class="title"><h4>Custom Information</h4></dt>';
foreach( $fields as $field_name => $field )
{
echo '<dt class="custom-label">' . $field['label'] . ': </dt>';
echo '<dd class="custom-data">';
if (is_array($field['value'])) {
echo implode(', ', $field['value']);
}
else {
echo $field['value'];
}
echo '</dd>';
}
echo '</dl>';
echo '</div>';
}
?>
Depending on the composition of the arrays in $field['value'] you can do one of the following:
If it's a simple list of values you can just tape them together with implode.
echo '<dd class="custom-data">' . (is_array($field['value'])?implode(", ", $field['value']:$field['value']) . '</dd>';
If the array contains data represented like the main array (with label and value keys) you can create a function to render the array and call it recursively when you encounter a array value.
<?php
function showFields($data){
echo '<div class="item-info-custom">';
echo '<dl class="item-custom">';
echo '<dt class="title"><h4>Custom Information</h4></dt>';
foreach( $fields as $field_name => $field )
{
echo '<dt class="custom-label">' . $field['label'] . ': </dt>';
if (is_array($field['value'])){
showFields($field['value']);
}
echo '<dd class="custom-data">' . $field['value'] . '</dd>';
}
echo '</dl>';
echo '</div>';
}
$fields = get_field_objects();
if( $fields ) showFields($fields);
You'll need to do some type checking. You can use functions like is_array() and do additional logic.
For example:
echo '<dd class="custom-data">';
if (is_array($field['value'])) {
echo implode(', ', $field['value']);
}
else {
echo $field['value'];
}
echo '</dd>';

Categories