Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save azizultex/64fc4ea49febecc74897acb76679ca4c to your computer and use it in GitHub Desktop.
Custom Search and Category Widgets WordPress
/*
WEBSITE : http://www.oldstructures.com/tag/projects/
*/
/* customer search form for widgets azizultex */
add_filter('widget_text','do_shortcode');
/* search form shortcode that populate tag automatically by tag page */
function searchFormByTag() {
$tag = get_queried_object();
$placeholderTxt = (is_search()) ? get_search_query() : 'Enter keywords';
return '<form action="'.get_bloginfo('url').'" method="get">
<input type="text" name="s" placeholder="'.$placeholderTxt.'" />
<input type="hidden" name="filter_tag" value="'.$tag->slug.'" />
</form>';
}
add_shortcode('searchbytag', 'searchFormByTag');
/* filter search by tag */
function searchfilter($query) {
if ($query->is_search && !is_admin() ) {
$query->set('tag', $_GET['filter_tag']);
}
return $query;
}
add_filter('pre_get_posts','searchfilter');
/* filter category acchieve page posts by filter_tag */
function filterCategoryPosts($query) {
if ($query->is_category && !is_admin() ) {
$query->set('tag', $_GET['filter_tag']);
}
return $query;
}
add_filter('pre_get_posts','filterCategoryPosts');
/* find posts numbers by specific cat and tag */
function catTagMatchedPosts($cat, $tag) {
$args = array(
'cat' => $cat,
'tag' => $tag,
'posts_per_page' => -1
);
$posts = query_posts( $args );
return count($posts);
}
/* category shortcode get categories have posts with the tags only */
function categoriesbytags_func() {
$tag = get_queried_object();
$args = array(
'tag' => $tag->slug,
'posts_per_page' => -1
);
$posts = query_posts($args);
$ids = wp_list_pluck($posts, 'ID');
$output = '';
$cat_ids = array();
foreach ($ids as $id) {
$post_categories = wp_get_post_categories( $id ); // get categories of the post
foreach($post_categories as $c){ // loop through all categories of that post
$cat = get_category( $c );
$cat_ids[] = $cat->term_id;
}
}
$unique_ids = array_unique($cat_ids); // remove duplicate categories
foreach ($unique_ids as $uid ) { // loop through all category ids
$cat = get_category( $uid ); // get category object
$cat_link = get_category_link($cat->term_id);
$cat_tag_link = esc_url(add_query_arg( 'filter_tag', $tag->slug, $cat_link )); // tag slug to category link to make it possible to filter only matched posts
$output .= '<ul>';
$output .= '<li><a href="'.$cat_tag_link.'">'.$cat->name.'</a> ('.catTagMatchedPosts($cat->term_id, $tag->slug).')</li>';
$output .= '</ul>';
}
return $output;
}
add_shortcode('categoriesbytags', 'categoriesbytags_func');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment