Get Wordpress child category from specific parent - wordpress

I'm building a small thumbnail gallery with posts from a category that has the ID 406.
Some of the posts are in multiple categories and I'm not sure how to grab the category name that is a child of 406. $post_cat[0]->name; returns a category, but I only need it to return children of 406.
$thumbnails = get_posts('posts_per_page=10&cat=406');
foreach ($thumbnails as $thumbnail) {
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => 406,
);
$categories = get_categories ( $args );
foreach ( $categories as $category) {
$cat_name = $category->name;
$cat_slug = $category->slug;
}
echo $cat_name;
echo $cat_slug;
}
*EDIT**
$thumbnails = get_posts('posts_per_page=10&cat=406');
foreach ($thumbnails as $thumbnail) {
$post_cat = get_the_category( $thumbnail->ID );
echo '<li><a class="side-thumb" href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
if ( has_post_thumbnail($thumbnail->ID)) {
echo get_the_post_thumbnail($thumbnail->ID, 'thumbnail');
$upload_dir = wp_upload_dir();
$art_image = ''.$upload_dir['basedir'].'/icons/'.$post_cat[0]->slug.'.png';
if (file_exists($art_image)) {
echo '<p class="artist-latest"><img src="http://site.com/wp-content/uploads/icons/'.$post_cat[0]->slug.'.png" alt="'.$post_cat[0]->slug.'"/>'.$post_cat[0]->name.'</p>';
} else{
echo '<p class="artist-latest">'.$post_cat[0]->name.'</p>';
}
} else {
}
echo '</a></li>';
}

So now I'm fetching a list of category and its child, then I fetch posts having parent category assigned to it, after I get posts array, I loop into it and get all the categories assigned to the post, If there are additional categories other than the required category and its child I skip the post, otherwise do whatever I want to do.
$category = get_category_by_slug( 'category-name' );
$args = array(
'type' => 'post',
'child_of' => $category->term_id,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => FALSE,
'hierarchical' => 1,
'taxonomy' => 'category',
);
$child_categories = get_categories($args );
$category_list = array();
$category_list[] = $category->term_id;
if ( !empty ( $child_categories ) ){
foreach ( $child_categories as $child_category ){
$category_list[] = $child_category->term_id;
}
}
$posts_args = array(
'posts_per_page' => 10,
'cat' => $category->term_id,
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true
);
$posts = new WP_Query ( $posts_args );
if ( $posts->have_posts() ){
while ( $posts->have_posts() ){
$posts->the_post();
$category_array = array();
$post_categories = get_the_category ( get_the_ID() );
if ( !empty ( $post_categories ) ){
foreach ( $post_categories as $post_category ) {
$category_array[] = $post_category->term_id;
}
}
//Checks if post has an additional category
$result = array_diff( $category_array, $category_list );
if ( empty ( $result ) ) { ?>
<li>
<a href="<?php the_permalink(); ?>" class="side-thumb" title="<?php the_title(); ?>"> dfdf<?php
if ( has_post_thumbnail() ){
echo get_the_post_thumbnail();
}
//Put your default icon code here
?>
</a>
</li> <?php
}
}
}
wp_reset_postdata();
Above answer is as per your explanation, but I think what you want is, like you have a category Artists and there are subcategories each having a specific name, So for Artist gallery you want to display list of all the artists with their pictures.

I also needed to get list of child categories of selected parent category with url,
I found following code so useful
<?php
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 5
) );
foreach ( $categories as $category ) {
printf( '<li><a class="btn btn-light btn-light-custom mt-2" href="%1$s">%2$s</a></li>',
esc_url( get_category_link( $category->term_id ) ),
esc_html( $category->name )
);
}
?>
Replace "5" with your selected parent category ID

Related

Display Users attached to Custom Post Type - ACF

I am trying to display users attached to a Custom Post Type. I created an ACF-Users-Field which returns the ID. This field is displayed at my Custom Post Type. Now I would like to display the names of the users selected in this field.
I am able to display all names of my users (if I remove the part 'meta_query' of my arguments, but if i add the meta_query array to my arguments nothing is displayed. I am not sure, maybe the mistake is the 'value', but I have no idea what to change there. Below I show the relevant code:
<article>
<?php
$args = array(
'role' => 'Subscriber',
);
$my_user_query = new WP_User_Query( $args );
$editors = $my_user_query->get_results();
if ( ! empty( $editors ) ) {
foreach ( $editors as $editor ) {
$editor_info = get_userdata( $editor->ID );
$args = array(
'post_type' => 'projekt',
'meta_query' => array(
array(
'key' => 'projektteilnehmer', // name of custom field - return ID
'value' => $post->ID ,
'compare' => 'LIKE'
)
)
);
// The User Query
$user_query = new WP_User_Query( $args );
// The User Loop
if ( ! empty( $user_query->results ) ) { ?>
<?php foreach ( $user_query->results as $user ) {
echo $user->user_firstname;;
}
} else {
echo 'nothing found';
}
} // endforeach
} else {
echo __( 'Kein Mitglied gefunden.' );
}
?>
</article>
Any help appreciated
By what your describing this code should do what you want. given that the participant's are returned as userID
<article>
<?php
$teilnehmers = get_field('projektteilnehmer', $post->ID);
if ( ! empty( $teilnehmers ) ) {
foreach ( $teilnehmers as $teilnehmer ) {
$user = get_user_by('ID', $teilnehmer);
if($user){
echo $user->user_firstname;;
}
}
} else {
echo __( 'Kein Mitglied gefunden.' );
}
?>
</article>
or if they are returned as user objects
<article>
<?php
$teilnehmers = get_field('projektteilnehmer', $post->ID);
if ( ! empty( $teilnehmers ) ) {
foreach ( $teilnehmers as $teilnehmer ) {
echo $teilnehmer->user_firstname;;
}
} else {
echo __( 'Kein Mitglied gefunden.' );
}
?>
</article>
The answer of Jasper B pushed me in the right direction. Thank you very much:) It is working with this query:
<?php // projekte
$projekte = get_posts(array(
'post_type' => 'projekt',
'meta_query' => array(
array(
'key' => 'projektteilnehmer', // name of custom field - return value id
'value' => $editor_info->ID,
'compare' => 'LIKE'
)
)
));
?>
<?php if( $projekte ): ?>
<strong>Projekte:</strong>
<ul>
<?php foreach( $projekte as $projekt ):?>
<li>
<a href="<?php echo get_permalink( $projekt->ID ); ?>">
<?php echo get_the_title( $projekt->ID ); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif;
// ende projekte ?>

Wordpress query only returns 1 result, but all with nonpaging = true

Completely confused with this one.
If I add the nonpaging => true to the query, I get all the results. However, I wish to only have 4 displayed in this particular loop. If I use the post_per_page => 4, I only get one.
Worse, if I add in orderby => 'rand' I will get some number between 1-5.
What the hell is going on?!?!?
// WP_Query arguments
$args = array (
'post_type' => array( 'bottin' ),
'posts_per_page' => 4,
);
// The Query
$bottin = new WP_Query( $args );
// The Loop
if ( $bottin->have_posts() ) {
while ( $bottin->have_posts() ) {
$bottin->the_post();
$voir_plus = get_field('voir_plus');
if ( !empty($voir_plus) ) {
// Vars
$link = get_the_permalink();
$image_url = get_the_post_thumbnail_url();
$name = get_the_title();
$posttags = get_the_tags();
echo '<a href="' . $link . '"><div class="elementor-row"><div class="elementor-col-50"><img src="' . $image_url . '" class="img-responsive" width="300"></div><div class="elementor-col-50 intervenant-info"><h6>' . $name . '</h6><p>';
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
}
echo '</p></div></div></a>';
}
}
} else {
// no posts found
}
I think you need this, "paged" and you might need to check this out https://codex.wordpress.org/Pagination
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'bottin'
'posts_per_page' => 4,
'paged' => $paged
);
$bottin = new WP_Query( $args );
?>

Products dropdown from same category inside Woocommerce product short description

In Woocommerce, I would like to add a drop down in product short description that shows all products that have the same category(ies). It will be even better if it was possible to go to the product page of the selected product.
I didn't see any threads that fulfill what I am trying to do.
Any help will be appreciated.
2021 Update - Added product_id as argument, allowing the shortcode to be used for a defined product ID (for example on a page).
The following will make a custom shortcode that you can use in your product short description (or even in the product description) and will display a dropdown from same product category than the current product.
The code:
add_shortcode( 'products_dropdown', 'wc_products_from_cat_dropdown' );
function wc_products_from_cat_dropdown( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts( array(
'product_id' => '',
), $atts, 'products_dropdown' );
$product_id = is_product() ? get_the_id() : $atts['product_id'];
if ( empty($product_id) )
return;
ob_start();
$query = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '-1',
'post__not_in' => array( $product_id ),
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) ) ,
) ),
) );
if ( $query->have_posts() ) :
echo '<div class="products-dropdown"><select name="products-select" id="products-select">
<option value="">'.__('Choose a related product').'</option>';
while ( $query->have_posts() ) : $query->the_post();
echo '<option value="'.get_permalink().'">'.get_the_title().'</option>';
endwhile;
echo '</select> <button type="button" style="padding:2px 10px; margin-left:10px;">'._("Go").'</button></div>';
wp_reset_postdata();
endif;
?>
<script type='text/javascript'>
jQuery(function($){
var a = '.products-dropdown', b = a+' button', c = a+' select', s = '';
$(c).change(function(){
s = $(this).val();
console.log(s); // just for testing (to be removed)
});
$(b).click(function(){
if( s != '' ) location.href = s;
});
});
</script>
<?php
return ob_get_clean();
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
USAGE
1). For single product pages: Just paste the following shortcode in the product short description (or descrition):
[products_dropdown]
2). For single product pages, inside php code:
echo do_shortcode("[products_dropdown]");
3). on any post or page within the text editor, define the product_id argument (below the defined product id is 37):
[products_dropdown product_id="37"]
Add this to your theme's 'functions.php' which will display all products of your current product's category.
function add_products_short_description() {
$product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );
if ( $product_cats ) {
$single_cat = array_shift( $product_cats );
$product_args = array( 'post_type' => 'product', 'posts_per_page' => '-1', 'product_cat' => $single_cat->name );
$products = new WP_Query( $product_args );
if ( $products->have_posts() ) : echo '<ul>';
while ( $products->have_posts() ) : $products->the_post(); global $product;
echo '<li>'.get_the_title($products->ID).'</li>';
endwhile;
echo '</ul>';
endif;
}
}
add_action( 'woocommerce_single_product_summary', 'add_products_short_description', 15 );

WordPress search is not working with more than 2 characters

I have created a custom template for search our products with lots of filters and one input field to search with characters. However, it works only with one or two characters like "a", "ag" but not with more than two characters. If I search for something like "pol" or "polar" it redirects me to WordPress 404 - PAGE NOT FOUND.
Update:
I have tried two solutions: one with the custom query ajax and that works fine with a search but the only problem I faced is with the pagination; the other one used WordPress standard query object, it works well with pagination but I'm getting a problem with search character length. Below are the two attempts that I tried.
Attempt #1: with the Ajax. this code is written down in function.php file
function get_search_results()
{
global $wpdb;
if(!empty($_POST['search_input'])) {
$search_input = $_POST['search_input'];
$where = 'pm.meta_value LIKE '. "'%".$search_input."%'".' AND pm.meta_key LIKE "%pattern_number"';
$where1 = 'p.post_title LIKE '."'%".$search_input."%'".' AND p.post_type = "product"';
$search_sql = 'SELECT DISTINCT(pm.post_id), ph.lightness, ph.color_label FROM wp_posts p
INNER JOIN wp_products_huecolor ph on p.ID = ph.post_id
INNER JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE p.post_status = "publish" AND p.post_type = "product" AND (('.$where.') OR ('.$where1.')) ORDER BY ph.color_label, ph.lightness ASC';
$total_query = "SELECT COUNT(1) FROM (${search_sql}) AS combined_table";
$total = $wpdb->get_var( $total_query );
$items_per_page = 10;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$page = $wpdb->get_results( $search_sql.' LIMIT '.$offset.', '.$items_per_page );
//echo "SQL = ".$wpdb->last_query; wp_die();
echo '<ul>';
foreach ($page as $object)
{
// get custom fields values related to a post by post id
$fields = get_fields($object->post_id);
// get post details by post id
$post_detail = get_post($object->post_id, $object );
$brand_name = $fields[brand]->name;
$full_sheet_image = $fields[full_sheet_image][sizes][thumbnail];
$post_title = $post_detail->post_title;
$post_name = $post_detail->post_name;
?>
<li class="post-pattern">
<div class="search-productsBoxSecond">
<a target="_blank" href="<?php echo site_url( '/products/'.$post_name.'', 'http' ); ?>"><img src="<?php echo $full_sheet_image; ?>" alt="" class="vc_single_image-img attachment-full"></a>
<div class="search-productNameSecond"><a target="_blank" href="<?php echo site_url( '/products/'.$post_name.'', 'http' ); ?>"><?php echo $post_title; ?></a></div>
<div class="search-productBrandSecond"><?php echo $brand_name; ?></div>
</div>
</li>
<?php
}
echo '</ul>';
echo '<div class="search-product-navigation">';
echo paginate_links( array(
'base' => add_query_arg( 'cpage', '%#%', site_url( '/pattern-search/' ) ),
'format' => '',
'prev_text' => __('«'),
'next_text' => __('»'),
'total' => ceil($total / $items_per_page),
'current' => $page
));
echo '</div>';
}
exit();
}
add_action('wp_ajax_nopriv_filter_featured_products','filter_featured_products');
add_action('wp_ajax_filter_featured_products','filter_featured_products');
Attempt #2: with Standard WP_Query in the custom template.
<?php
$args = array();
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$search_keywords = ( get_query_var( 's' ) ) ? get_query_var( 's' ) : "";
if(isset($search_keywords) && $search_keywords != ''){
$args = array(
'post_type' => 'product',
'search_prod_title' => $search_keywords,
'post_status' => 'publish',
'posts_per_page' => 10,
'paged' => $paged,
'wildcard_on_key' => true,
'meta_query' => array(
array(
'key' => 'product_type_%_pattern_number',
'value' => $search_keywords,
'compare' => 'LIKE',
),
)
);
}else{
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 10,
'paged' => $paged
);
}
// query for getting featured product
add_filter( 'posts_fields', 'products_posts_select_filter', 10, 2 );
add_filter( 'posts_join', 'products_posts_join_filter', 10, 2 );
add_filter( 'posts_where', 'title_filter', 10, 2 );
add_filter( 'posts_orderby', 'products_posts_orderby', 10, 2 );
add_filter('posts_groupby', 'products_posts_groupby', 10, 2);
$sql_query = new WP_Query( $args );
//echo $wpdb->last_query; die();
//echo '<pre>'; print_r($sql_query); die;
//echo $sql_query->request; die;
remove_filter( 'posts_fields', 'products_posts_select_filter', 10, 2 );
remove_filter( 'posts_join', 'products_posts_join_filter', 10, 2 );
remove_filter( 'posts_where', 'title_filter', 10, 2 );
remove_filter( 'posts_orderby', 'products_posts_posts_orderby', 10, 2 );
remove_filter('posts_groupby', 'products_posts_groupby', 10, 2);
if( $sql_query->have_posts()):
echo '<ul>';
while( $sql_query->have_posts()): $sql_query->the_post();
{
//get custom fields meta values related to a post
$fields = get_fields($post->ID);
$full_sheet_image = $fields[full_sheet_image][sizes][thumbnail];
//echo'<pre>'; print_r($post_detail); die;
?>
<li class="post-pattern">
<div class="search-productsBoxSecond">
<a target="_blank" href="<?php echo site_url( '/products/'.$post->post_name.'', 'http' ); ?>"><img src="<?php echo $full_sheet_image; ?>" alt="" class="vc_single_image-img attachment-full"></a>
<div class="search-productNameSecond"><a target="_blank" href="<?php echo site_url( '/products/'.$post->post_name.'', 'http' ); ?>"><?php echo $post->post_title; ?></a></div>
<div class="search-productBrandSecond"><?php echo $fields[brand]->name; ?></div>
</div>
</li>
<?php
}
endwhile; ?>
</ul>
<!-- pagination -->
<div class="search-product-navigation">
<?php
echo paginate_links(array(
'total' => $sql_query->max_num_pages
));
?>
</div>
<?php endif; ?>
here are the filter functions thats written in the function.php
/*Replaced meta_key = with meta_key LIKE */
add_filter( 'posts_where', function ( $where, \WP_Query $q )
{
// Check for our custom query var
if ( true !== $q->get( 'wildcard_on_key' ) )
return $where;
// Lets filter the clause
$where = str_replace( 'meta_key =', 'meta_key LIKE', $where );
return $where;
}, 10, 2 );
function title_filter( $where, &$wp_query )
{
global $wpdb;
if ( $search_term = $wp_query->get( 'search_prod_title' ) ) {
$post_title_clause = '('.$wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\') OR';
$where = substr_replace($where, $post_title_clause , 6, 0);
}
return $where;
}
function products_posts_select_filter( $fields, &$wp_query ){
$fields = 'DISTINCT(wp_posts.ID), wp_posts.post_title, wp_posts.post_name, ph.lightness, ph.color_label';
return $fields;
}
function products_posts_join_filter( $join, &$wp_query ){
$join .= " INNER JOIN wp_products_huecolor ph on wp_posts.ID = ph.post_id";
return $join ;
}
function products_posts_orderby( $orderby, &$wp_query ){
$orderby = 'ph.color_label, ph.lightness ASC';
return $orderby;
}
function products_posts_groupby( $groupby, &$wp_query ){
return $groupby = '';
}

How To Get the children of the parent category by parent id in wordpress

i try to get All child categories from my parent category
like my parent category is news and child is news1 news 2 news 3
Use following code for to get children category of parent category.
<?php
$parent_cat_arg = array('hide_empty' => false, 'parent' => 0 );
$parent_cat = get_terms('category',$parent_cat_arg);//category name
foreach ($parent_cat as $catVal) {
echo '<h2>'.$catVal->name.'</h2>'; //Parent Category
$child_arg = array( 'hide_empty' => false, 'parent' => $catVal->term_id );
$child_cat = get_terms( 'category', $child_arg );
echo '<ul>';
foreach( $child_cat as $child_term ) {
echo '<li>'.$child_term->name . '</li>'; //Child Category
}
echo '</ul>';
}
?>
This code will display all the child categories of selected parent category, tested and works in category.php template file...
$this_category = get_category($cat);
//echo $this_category->cat_ID;
$parent_term_id =$this_category->cat_ID; // term id of parent term
//$termchildren = get_terms('category',array('child_of' => $parent_id));
$taxonomies = array(
'taxonomy' => 'category'
);
$args = array(
// 'parent' => $parent_term_id,
'child_of' => $parent_term_id
);
$terms = get_terms($taxonomies, $args);
if (sizeof($terms)>0)
{
echo ' <div class="categories"> ';
echo '<p> Sub Categories of '. get_cat_name( $parent_term_id ) .'</p>';
foreach ( $terms as $term ) {
$term_link = sprintf( '<div class="custom-cats">%3$s</div>', esc_url( get_category_link( $term->term_id ) ),
esc_attr( sprintf( 'View all posts in %s', 'textdomain' ), $term->name ),
esc_html( $term->name ));
echo sprintf( $term_link );
}
echo '</div><!-- categories div end-->';
}

Resources