Get a specific posts in array in Wordpress - php

For a single page I need to change the code to get the list of items from a specific category only. So like: select items where category food is 15.
I tried different things, but I'm not so good in php. So could you please help me to change the code. Here is the part where the listing are published.
<div class="col-md-6">
<div class="box_style_2" id="main_menu">
<h2 class="inner">Menu</h2>
<?php
$terms = get_terms( 'foodcat', array(
'include' => $category_food,
));
?>
<?php
$i = 1;
foreach($terms as $term){ ?>
<h3 <?php if($i=1){?>class="nomargin_top"<?php }else{}?> id="<?php echo esc_attr($term->slug);?>"><?php echo esc_attr($term->slug);?></h3>
<p><?php echo esc_attr($term->description);?></p>
<table class="table table-striped cart-list">
<thead>
<tr>
<th>
<?php echo esc_html__( 'Item', 'quickfood' );?>
</th>
<th>
<?php echo esc_html__( 'Price', 'quickfood' );?>
</th>
<th>
<?php echo esc_html__( 'Order', 'quickfood' );?>
</th>
</tr>
</thead>
<tbody>
<?php
$food_arr = new WP_Query(
array(
'post_type' => 'food',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'foodcat',
'field' => 'id',
'terms' => $term->term_id,
)
)
)
);
$ii = 1;
if($food_arr->have_posts()) : while($food_arr->have_posts()) : $food_arr->the_post();
$textmoney = get_post_meta(get_the_id(), '_cmb2_textmoney', true);
?>
<tr id="detail-<?php the_id();?>">
<input type="hidden" value="<?php the_id();?>">
<td>
<h5><?php echo esc_attr($ii);?>.<span class="name-<?php the_id();?> item_name"><?php the_title();?></span>
<input type="hidden" id="name-<?php the_id();?>" value="<?php the_title();?>">
</h5>
<p>
<?php the_content();?>
</p>
</td>
<td>
<strong><?php if(isset($currency_menu) && !empty($currency_menu)){ echo esc_attr($currency_menu);}else{}?><span class="price-<?php the_id();?> price"> <?php echo esc_attr( $textmoney );?></span></strong>
<input type="hidden" id="price-<?php the_id();?>" value="<?php echo esc_attr( $textmoney );?>">
</td>
<td class="options">
<i class="icon_plus_alt2 add-to-cart-button" id="<?php the_id();?>"></i>
</td>
</tr>
<?php $ii++; endwhile;endif;?>
</tbody>
</table>
<hr>
<?php } ?>
</div>
</div>

If I understood you right, all you need is to put the category number in this code:
$food_arr = new WP_Query(
array(
'post_type' => 'food',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'foodcat',
'field' => 'id',
'terms' => $term->term_id,
)
)
)
);
exactly where it says 'terms' => $term->term_id, add the number like this:
'terms' => '15',

Related

WP_Query with multiple filters ajax

Just started learning about filtering custom queries in Wordpress. I want to be able to filter through products (custom post types) by their taxonomies. I am able to get this working sort of. The problem is that when I apply more than one filter, only the last on works. I'm assuming the last one cancels the others out? How can I make all filters work simultaneously? Any help would be much appreciated!
sidebar.php:
<aside data-css-sidebar="sidebar">
<form data-js-form="filter">
<h3>Filter <?php echo ucfirst($type); ?></h3>
<fieldset style='display:none'>
<label name='product-category' for="product-category"><input id='product-category' name='product-category' value=<?php echo $cat_id; ?>></label>
</fieldset>
<fieldset>
<label for="product-prices">Prices</label>
<?php
$prices = get_terms(array(
'taxonomy' => 'price',
'hide_empty' => false,
));
?>
<select id="product-price" name="product-price">
<option>Search by Price</option>
<?php foreach ($prices as $price) : ?>
<option value="<?= $price->term_id; ?>"><?= $price->name; ?></option>
<?php endforeach; ?>
</select>
</fieldset>
<fieldset>
<label for="product-brand">Brands</label>
<?php
$prices = get_terms(array(
'taxonomy' => 'brands',
'hide_empty' => false,
));
?>
<select id="product-brand" name="product-brand">
<option>Search by Brand</option>
<?php foreach ($prices as $price) :
?>
<option value="<?= $price->term_id; ?>"><?= $price->name; ?></option>
<?php endforeach; ?>
</select>
</fieldset>
<fieldset>
<label>Colors</label>
<?php
$colors = get_terms(array(
'taxonomy' => 'color',
'hide_empty' => false,
));
foreach ($colors as $color) :
?>
<div>
<input type="checkbox" id="<?= $color->slug; ?>" name="product-colors[]" value="<?= $color->term_id; ?>"><label for="<?= $color->slug; ?>"><?= $color->name; ?></label>
</div>
<?php endforeach; ?>
</fieldset>
<fieldset>
<button>Filter</button>
<input type="hidden" name="action" value="filter">
</fieldset>
</form>
</aside>
filter.php:
<?php
add_action('wp_ajax_nopriv_filter', 'filter_ajax');
add_action('wp_ajax_filter', 'filter_ajax');
function filter_ajax()
{
$product_cat = $_POST['product-category'];
$product_color = $_POST['product-colors'];
$product_price = $_POST['product-price'];
$product_brand = $_POST['product-brand'];;
$args = array(
'post_type' => 'products',
'posts_per_page' => -1,
'cat' => $product_cat,
);
if (isset($product_price) && !empty($product_price)) {
$args['tax_query'] = array(
array(
'taxonomy' => 'price',
'field' => 'term_id',
'terms' => array($product_price)
),
);
}
if (isset($product_brand) && !empty($product_brand)) {
$args['tax_query'] = array(
array(
'taxonomy' => 'brands',
'field' => 'term_id',
'terms' => array($product_brand)
)
);
}
if (isset($product_color) && !empty($product_color)) {
$args['tax_query'] = array(
array(
'taxonomy' => 'color',
'field' => 'term_id',
'terms' => $product_color
)
);
}
$query = new WP_Query($args);
// start the loop
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
$no_img = get_field('no_image', 'options')['url'];
?>
<div class="card mx-4 mx-md-2 mx-xl-4">
<div class="card__inner">
<?php if (has_post_thumbnail()) { ?>
<img src="<?php the_post_thumbnail_url(); ?>" alt="" />
<?php } else {
?>
<img src="<?php echo $no_img ?>" alt="no-image" />
<?php } ?>
<h6 class="mt-3"><?php the_title(); ?></h6>
<p>$ <?php echo get_field('price'); ?></p>
</div>
</div>
<?php endwhile;
else : ?>
<div>
<p>No items found</p>
</div><?php
endif; ?>
<?php wp_reset_query();
die();
}
script.js
$.noConflict();
$(document).ready(function () {
//ajax filtering
$(document).on("submit", "[data-js-form=filter]", function (e) {
e.preventDefault();
let data = $(this).serialize();
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: data,
type: "post",
success: function (result) {
console.log(result);
$("#target").html(result);
},
error: function (result) {
console.warn("error :" + result);
},
});
});
})
Try changing to something like the following
if (isset($product_color) && !empty($product_color)) {
$args['tax_query'][] = array(
'taxonomy' => 'color',
'field' => 'term_id',
'terms' => $product_color
);
}
And the same for the others
You might also need to change this (adding the tax_query)
$args = array(
'post_type' => 'products',
'posts_per_page' => -1,
'cat' => $product_cat,
'tax_query' => ['relation' => 'or']
);

Post filtering in wordpress returns all posts

I have this function to filter posts by fields and taxonomies. The problem is that when I use the taxonomy filter it doesn't work and it returns all the posts without filtering.
I didn't include js files because ajax is working well.
Here's the PHP in functions.php:
function post_filter()
{
$number = $_POST['number'];
$autor = $_POST['autor'];
$args = array(
'post_type' => 'publicaciones',
'orderby' => 'date',
'order' => 'ASC',
'meta_key' => 'numero',
'meta_value'=> $number
);
if( isset( $autor ) )
$args['tax_query'] = array(
array('taxonomy' => 'autors',
'field' => 'id',
'terms' => $autor)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
//Post content
endwhile;
wp_reset_postdata();
else :
echo 'No results.';
endif;
wp_die();
}
And this is the form:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" class="my-5" id="buscador_numero">
<div class="row">
<div class="col-3">
<?php
if( $terms = get_terms( array( 'taxonomy' => 'autors', 'orderby' => 'name' ) ) ) :
echo '<select name="autor"><option value="">Autor/a</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
?>
</div>
<div class="col-2">
<input type="number" class="w-100 p-2" name="number" placeholder="Número">
</div>
<div class="col-2">
<button id="btn_buscar"><span class="dashicons dashicons-search"></span></button>
</div>
</div>
<input type="hidden" name="action" value="post_filter">
</form>
Thanks in advance :)

How get terms of specific taxonomy in wordpress?

I am working on properties project and need to get terms of specific taxonomy. I mean properties of cities base of their states.
Here is the code I have written for:
<div class="row">
<div class="col-md-2">
<?php
$taxonomy = 'property-state';
$terms = get_terms($taxonomy);
?>
<ul>
<?php foreach ( $terms as $term ) { ?>
<li>
<a href="<?php echo get_term_link($term->slug, $taxonomy); ?>">
<?php echo $term->name . ' ('. $term->count .')' ?>
</a>
</li>
<?php } ?>
</ul>
<?php
?>
</div>
<div class="col-md-2">
<?php
$taxonomy = 'property-city';
$terms = get_terms($taxonomy);
?>
<ul>
<?php foreach ( $terms as $term ) { ?>
<li>
<a href="<?php echo get_term_link($term->slug, $taxonomy); ?>">
<?php echo $term->name . ' ('. $term->count .')'?>
</a>
</li>
<?php } ?>
</ul>
<?php
?>
</div>
</div> <!-- end of row -->
What I need is to list properties of cities base of state, how should I change these codes?
I found my answer myself, I wanted to list properties of specific state with specific status.
for example the properties of Kabul state with status of (for-rent) and the properties count on each city of that state.
<?php $terms = get_terms("property-city");
foreach($terms as $term)
{
$items = get_posts(array(
'numberposts' => -1,
'post_type' => 'property',
'post_status' => 'publish',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'property-city',
'field' => 'slug',
'terms' => $term->slug
),
array(
'taxonomy' => 'property-state',
'field' => 'name',
'terms' => 'هرات',
'operator' => 'NOT IN'
),
)
));
$count = count( $items );
?>
<ul>
<li>
<a href="<?php echo get_term_link($term);?>" <?php if ($count == 0) echo " style='display: none';"; ?>>
<?php echo $term->name. ' ('. $count .')';?>
</a>
</li>
</ul>
<?php
}
?>

Is there a way to list all the authors who have published videos in a certain category and show them together, like a list?

Please help me with this website https://desarrollowebtotal.space/yoentrenoencasa/
I'm using goWatch theme from touchsize as parent theme.
What I need is this:
When I click on any of the categories listed on the home page, e.g. Yoga, the site will navigate to an archive with all the videos created in that taxonomy, it is not the behavior I want.
What I want is for that archive to return a list of authors who have published videos in that category and nested, as a list, show the videos associated with that author within that category.
Is it possible to do this?
// This query brings the videos within the videos_categories taxonomy that match the current slug
$term = get_queried_object();
$loop = new WP_Query( array(
'post_type' => 'video',
'posts_per_page' => 10,
'tax_query' => array( //(array) - use taxonomy parameters (available with Version 3.1).
'relation' => 'AND', //(string) - Possible values are 'AND' or 'OR' and is the equivalent of running a JOIN for each taxonomy
array(
'taxonomy' => 'videos_categories', //(string) - Taxonomy.
'field' => 'slug', //(string) - Select taxonomy term by ('id' or 'slug')
terms' => $term->slug, //(int/string/array) - Taxonomy term(s).
include_children' => true, //(bool) - Whether or not to include children for hierarchical taxonomies. Defaults to true.
'operator' => 'IN' //(string) - Operator to test. Possible values are 'IN', 'NOT IN', 'AND'.
),
),
) );
This is what I've done so far, I have no idea how to nest the video listings so that the parent is the author and the child the videos associated with that author
//UPDATE 1
$argsA = array(
'orderby' => 'name',
'order' => 'ASC',
'number' => null,
'optioncount' => false,
'exclude_admin' => true,
'show_fullname' => false,
'hide_empty' => false,
'echo' => true,
// 'feed' => [empty string],
// 'feed_image' => [empty string],
// 'feed_type' => [empty string],
'style' => 'list',
'html' => true,
);
$authors = wp_list_authors($argsA);
// This query brings the videos within the videos_categories taxonomy that match the current slug
$term = get_queried_object();
HTML PART WHERE I LOOP THE RESULTS
<div class="container airkit-archive-content">
<div class="row">
<?php if (!empty($authors)): ?>
<?php foreach ($authors as $author): ?>
<?php
$author_id = $author->ID;
$author_display_name = $author->name;
$query_args = array(
'author' => $author_id,
'post_type' => 'video',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'videos_categories',
'field' => 'slug',
'terms' => $term->slug,
'include_children' => true,
'operator' => 'IN'
),
),
);
?>
<?php endforeach; ?>
<?php endif ?>
</div>
</div>
The OUTPUT
Cristian Entrenador
j.b
Jose Miguel
Yonatan T.
What i need
Trainer name
Videos he/she posted in the current category
UPDATE 2:
Doing as #Tokant requested/recommended i copy/pasted his snippet, it worked, it printed an author, i think it's because he's the only one who has posted videos
<div class="row">
<?php $term = get_queried_object(); ?>
<?php $authors_args = array(
'echo' => false,
'orderby' => 'name',
'order' => 'ASC',
);
$author_list = wp_list_authors($authors_args);
if (!empty($author_list)):
echo $author_list;
foreach ($author_list as $author):
$author_id = $author->ID;
$author_display_name = $author->name;
$query_args = array(
'author' => $author_id,
);
$the_query = new WP_Query( $query_args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
endwhile;
wp_reset_postdata();
endif;
endforeach;
endif; ?>
</div>
OUPUTS THIS
Jose Miguel
Good morning guys, thanks to Tokant I was able to find the solution in my own way.
What I did was put the layout together so that the hierarchy would be like this.
Author
- Videos posted in the current category.
This is the solution:
You have to install Buddypress plugin for 'orden' key to work, and add this script to functions.php of your child theme
/*Función para ordenar los autores*/
add_action('show_user_profile', 'extra_user_profile_fields');
add_action('edit_user_profile', 'extra_user_profile_fields');
function extra_user_profile_fields($user)
{ ?>
<?php if (current_user_can('administrator')) { ?>
<h3><?php _e("Administrar Posiciones", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="orden"><?php _e("Modificar Orden"); ?></label></th>
<td>
<input type="number" name="orden" id="orden" value="<?php echo esc_attr(get_the_author_meta('orden', $user->ID)); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Campo solo para administradores"); ?></span>
</td>
</tr>
<tr>
</table>
<?php } ?>
<?php }
add_action('personal_options_update', 'save_extra_user_profile_fields');
add_action('edit_user_profile_update', 'save_extra_user_profile_fields');
function save_extra_user_profile_fields($user_id)
{
if (!current_user_can('edit_user', $user_id)) {
return false;
}
update_user_meta($user_id, 'orden', $_POST['orden']);
}
Loop for the authors:
<?php
// Theme's WP_Query arguments
$airkit_video = '';
$figure_attributes = array();
$airkit_is_img = airkit_single_option('img');
$airkit_img_src =wp_get_attachment_url(get_post_thumbnail_id($videos->ID));
$airkit_video_type = get_post_meta($videos->ID, 'video_type', true);
$airkit_external_video = get_post_meta($videos->ID, 'video_url', true);
$airkit_embedded_video = get_post_meta($videos->ID, 'video_embed', true);
$airkit_uploaded_video = get_post_meta($videos->ID, 'video_upload', true);
//Arguments for users Query
$arg_user = array(
'role__in' => ['author'],
'post_type' => 'video',
'has_published_posts' => ['video'],
'fields' => ['ID'],
'meta_query' => array(
array(
'relation' => 'OR',
array('key' => 'orden', 'value' => '0', 'compare' => '!='),
array('key' => 'orden', 'compare' => 'NOT EXISTS'),
),
),
'orderby' => 'meta_value',
'order' => 'ASC',
);
//var_dump($arg_user);
$yec_args = get_users($arg_user); //We obtain the list of all the users of the site to compare with the criteria of the query, it will look for in the author role, the users that have published entries in the custom post type video and it will avoid to bring the ones that do not have entries.
$yec_user_id = wp_list_pluck($yec_args, 'ID');
//print_r($yec_user_id);
?>
?>
Then we loop through each author and output the html
<div class="container container-todo" style="transform: none; display: flex;">
<div class="post-details-row current-reading" style="transform: none;">
<?php
// Loop & retrieve el ID authors ID
foreach ($yec_user_id as $author_id): //main FOREACH
// We get the ID of the current author who is returning the loop
$curauth = get_userdata($author_id);
//var_dump($curauth->user_nicename);
$args = array(
'posts_per_page' => -1,
'post_type' => 'video',
'author' => $author_id,
'groupby' => 'author',
'tax_query' => array(
array(
'taxonomy' => 'videos_categories',
'field' => 'slug',
'terms' => get_queried_object()->slug,
),
),
'meta_key' => 'airkit_views',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
//We return the videos and count them.
$posts = get_posts($args);
$number_post = count($posts);
//var_dump($number_post);
//if this author has posts, then include his name in the list otherwise don't
if (isset($posts) && !empty($posts)) { // MAIN IF?>
<div class="row" style="display: flex; align-items: center;">
<div class="sidebar-right col-lg-12 col-md-12 col-xs-12" style="display: flex; justify-content: center; flex-wrap: wrap;">
<!-- Datos del autor -->
<div class="tszf-author-body">
<div class="item col-md-12 col-xs-12" style="text-align: center;">
<div class="yec-user-image">
<img src="<?php echo esc_url(get_avatar_url($author_id)); ?>" />
</div>
<div class="item col-xs-12">
<span class="yec-authors"> <?php echo "" . $curauth->first_name . " " . $curauth->last_name . ""; ?> </span>
</div>
</div>
</div>
<div class="tszf-user-name">
<ul class="social"><?php echo airkit_var_sanitize($social_icons, 'the_kses'); ?></ul>
</div>
<!-- Fin de datos del autor -->
<!-- Aquí deben ir los vídeos de ese autor -->
<?php $count = 0; ?>
<?php foreach ($posts as $post) { ?>
<?php if ($count == "4") {
// Si hay vídeos no imprimas más de 2 y salte del condicional
break;
} else{ ?>
<!-- Este es el bloque iterable -->
<div class="item col-lg-4 col-md-6 col-sm-6 col-xs-12">
<article class="video type-video status-publish has-post-thumbnail hentry has-lazy-placeholder airkit_view-article text-left below-image effect-always hidden-excerpt has-image" itemscope="" itemtype="http://schema.org/Article">
<figure class="image-holder has-background-img lazy lazyloaded" style="background-image: url(<?php echo get_the_post_thumbnail_url($post->ID, 'full') ?>); display: block;">
<a class="post-format-link" href="<?php the_permalink(); ?>" title="<?php echo $post->post_title; ?>">
<span class="post-type"><i class="icon-play-full"></i></span>
</a>
<div class="overlay-effect ">
<a href="<?php the_permalink(); ?>" class="overlay-link darken">
</a>
</div>
</figure>
<header class="entry-content-below">
<div class="entry-content">
<ul class="entry-categories">
<li class="term">
<?php $slug = get_queried_object()->slug; ?>
<?php echo $post->post_title; ?>
<!-- <?php echo $slug; ?> -->
</li>
</ul>
<h2 class="entry-title" itemprop="name headline">
<?php echo $video->post_title; ?>
<div class="widget-meta">
<ul class="list-inline">
<li class="red-comments">
<a href="<?php echo get_permalink($post->ID) . '#comments' ?>">
<i class="icon-comments"></i>
<span class="comments-count">
<?php echo airkit_var_sanitize($post->comment_count, 'the_kses') . ' '; ?>
</span>
</a>
</li>
<li class="meta-views">
<i class="icon-views-1"></i> <?php airkit_get_views($post->ID, true); ?>
</li>
</ul>
</div>
</h2>
</div> <!-- Aquí termina el contenido de los vídeos -->
</header>
</article>
</div>
<!--Fin del bloque iterable -->
<?php $count++; } //CIERRE DEL IF DEL COUNT ?>
<?php } //CIERRE FOREACH DE POST ?>
</div>
<!-- Flecha que nos lleva al perfil del autor -->
<a href=" <?php echo get_option('siteurl') . '/members/' . $curauth->user_nicename . '/posts' ?>" class="post-link">
<span style="font-size: 3em; color: rgba(60,185,207,1);">
<i class="fas fa-angle-double-right" style="margin-top:50px"></i>
</span>
<br />
</a>
<span style="color: rgba(60,185,207,1);"> (<?php echo $number_post; ?>) <i class="fas fa-video"></i> </span>
</div>
<?php } // END of MAIN IF ?>
<?php endforeach; //END OF MAIN FOREACH ?>
You could do a WP_Query for all authors. In the loop for each author you first get the author's ID and then create a WP_Query for the 'video' post type, just like you have already done but adding the authour's ID in the $args, like so:
$authors_args = array(
'echo' => false,
'orderby' => 'name',
'order' => 'ASC',
);
$authors = wp_list_authors($args);
if (!empty($authors)):
foreach ($authors as $author):
$author_id = $author->ID;
$author_display_name = $author->name;
$query_args = array(
'author' => $author_id,
[your args]
);
$the_query = new WP_Query( $query_args );
if ( $the_query->have_posts() ) :
[output author name]
while ( $the_query->have_posts() ) : $the_query->the_post();
[output post/video]
endwhile;
wp_reset_postdata();
endif;
endforeach;
endif;

How to get the list of terms with its CPT?

I have a map in my website with dots that I localize the number of office per country on a map picture.
How it works is basically I have CPT as office and I create posts as city name like New York, London etc.
For example, if I have an office in New York, USA, I will create the post as New York and custom category will be country name as the USA. Also, in office CPT, I have custom fields for coordinating the dots on the map as Home_x and Home_Y.
So the outcome with the below code is like:
USA/New York
USA/Chicago
United Kingdom/London
United Kingdom/Bristol
Spain/Barcelona
Spain/Granada
My code for loop is;
<div class="map-wrapper">
<div class="map">
<?php
$terms = get_terms(array(
'taxonomy' => 'office-country',
'hide_empty' => false,
));
?>
<?php foreach ($terms as $term) : ?>
<?php
$re = explode('-', $term->name);
$args = array (
'post_type' => 'office', //
'posts_per_page' => -1,
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'office-country',
'field' => 'id',
'terms' => $term->term_id,
),
),
);
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
$title = get_the_title();
$info = get_post_meta(get_the_ID(), '_post_info', true);
$link = get_term_meta($term->term_id, 'link', true);
?>
<a href="<?php echo $link ?>"
class="point <?php if ($term->slug === $_GET['country']) echo 'active' ?>"
style="left: <?php echo $info['home_x']; ?>px; top: <?php echo $info['home_y']; ?>px;"
data-target=".country-popup-<?php echo $term->term_id ?>">
<div class="inner"></div>
<div class="text">
<span class="name"><?php echo $re[0] ?> </span>
<span class="number"><?php echo " / ".$title; ?>
</span>
</div>
</a>
<?php
}
}
endforeach; ?>
</div>
</div>
and my custom field for CPT is;
<tr>
<th>
<label><?php _e('Home X'); ?></label>
</th>
<td>
<input type="text" name="_post_info[home_x]" value="<?php echo $info['home_x'] ?>">
</td>
</tr>
<tr>
<th>
<label><?php _e('Home Y'); ?></label>
</th>
<td>
<input type="text" name="_post_info[home_y]" value="<?php echo $info['home_y'] ?>">
</td>
</tr>
Above code works perfectly for this purpose.
But I want to change the custom taxonomy as office and post as a country name now. Instead of creating multiple posts for the city, creating a country post and adding cities as custom taxonomy is much easier. So I am trying to change below code for a new way.
I have changed the loop code as below, and create a custom field for custom-taxonomy, I also indicate it below too.
New loop;
<div class="map-wrapper">
<div class="map">
<?php
$terms = get_terms(array(
'taxonomy' => 'office-city',
'hide_empty' => false,
));
?>
<?php foreach ($terms as $term) : ?>
<?php
$re = explode('-', $term->name);
$args = array (
'post_type' => 'office-country', //
'posts_per_page' => -1,
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'office-city',
'field' => 'id',
'terms' => $term->term_id,
),
),
);
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
$title = get_the_title();
// $info = get_post_meta(get_the_ID(), '_post_info', true);
$link = get_term_meta($term->term_id, 'link', true);
$MapY = get_term_meta($term->term_id, 'home_y', true);
$MapX = get_term_meta($term->term_id, 'home_x', true);
?>
<a href="<?php echo $link ?>"
class="point <?php if ($term->slug === $_GET['country']) echo 'active' ?>"
style="left: <?php echo $MapY ?>px; top: <?php echo $MapX ?>px;"
data-target=".country-popup-<?php echo $term->term_id ?>">
<div class="inner"></div>
<div class="text">
<span class="name"><?php echo $title; ?> </span>
<span class="number"><?php echo " / ".$re[0] ?>
</span>
</div>
</a>
<?php
}
}
endforeach; ?>
</div>
</div>
Custom field for taxonomy;
add_action( 'office-country_edit_form_fields', 'office_country_taxonomy_custom_fields', 10, 2 );
function office_country_taxonomy_custom_fields($tag) {
?>
<tr>
<th>
<label><?php _e('Home X'); ?></label>
</th>
<td>
<input type="text" name="_term_meta[home_x]" value="<?php echo get_term_meta($tag->term_id, 'home_x', true) ?>">
</td>
</tr>
<tr>
<th>
<label><?php _e('Home Y'); ?></label>
</th>
<td>
<input type="text" name="_term_meta[home_y]" value="<?php echo get_term_meta($tag->term_id, 'home_y', true) ?>">
</td>
</tr>
<?php
}
But when I applied this code, it partly works and I have no idea to change the query.
The result;
USA/New York
United Kingdom/London
Spain/Barcelona
So, it does only show posts per taxonomy but I want to show all the cities per country like below;
USA/New York
USA/Chicago
United Kingdom/London
United Kingdom/Bristol
Spain/Barcelona
Spain/Granada
Sorry, it is a long question. I hope you guys can help on this, and I hope you guys understood my broken English.
Your loop is working correctly as i got result what you wanted.
<?php
$terms = get_terms(array(
'taxonomy' => 'office-city',
'hide_empty' => false,
));
foreach ($terms as $term) :
$args = array (
'post_type' => 'office-country', //
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'title',
'tax_query' => array(
array(
'taxonomy' => 'office-city',
'field' => 'id',
'terms' => $term->term_id,
),
),
);
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
$title = get_the_title();
echo '<p>'. $title . '/' . $term->name . '</p>';
}
}
endforeach; ?>

Categories