Browsing custom taxonomy terms on WordPress - wordpress

I ran into a little problem and I might need your help to sort it out.
I an building a website that uses custom taxonomies and tags posts accordingly. So, there is a page like http://example.com/custom-taxonomy/term that displays all the posts tagged with "term".
The visitor should be able to go to http://example.com/custom-taxonomy/ and see a lists of all the terms that are used inside that custom taxonomy in order to browse them. This list should also be "paginated" since some taxonomies could have quite a lot of terms in them.
Any ideas on how I should handle this?
Thanks a bunch!

I'll answer my own question here, maybe it will help others.
I have created a custom page template that uses get_terms to get the terms for a specific taxonomy and iterates through them displaying them in the desired manner.
I then created a page with the exact same slug as the main taxonomy slug (http://example.com/actors in this case) and thus when going to /actors/ you actually see the page created that acts as an index page for the taxonomy. You can see it in effect at http://couch.ro/actori/
In the actual code I am also using the Taxonomy Images plugin for having images on the actual tags so the get_terms is executed through the apply_filter() function. You have the full code for the template below. Any feedback is highly appreciated!
<?php
/*
Template Name: Taxonomy Index
*/
$slug_to_taxonomy=array('actori'=>'actor','regizori'=>'director');
$terms_per_page=get_option( 'c2c_custom_post_limits' );
if ($terms_per_page['archives_limit']==0)
{
$terms_per_page=get_options('posts_per_page');
}
else
{
$terms_per_page=$terms_per_page['archives_limit'];
}
$slug=$post->post_name;
if (!isset($slug_to_taxonomy[$slug]))
{
header("Location: /");exit;
}
else
{
$taxonomy=$slug_to_taxonomy[$slug];
}
$terms_page=get_query_var('paged');
if (empty($terms_page))
{
$terms_page=1;
}
$terms=apply_filters( 'taxonomy-images-get-terms', '',array('having_images'=>false,'taxonomy'=>$taxonomy, 'term_args'=>array('offset'=>($terms_page-1)*$terms_per_page,'number'=>$terms_per_page)) );
if (empty($terms))
{
header("Location: /");exit;
}
$processed_terms=array();
foreach ($terms as $term)
{
if (!empty($term->image_id))
{
$image_src=wp_get_attachment_image_src($term->image_id,'archive-thumbnail');
$image_src=$image_src[0];
}
else
{
$image_src='http://couch.ro/wp-content/uploads/couchie_75.png';
}
$term_posts=get_posts(array('posts_per_page'=>3,'tax_query'=>array(array('taxonomy'=>$taxonomy,'field'=>'slug','terms'=>$term->slug))));
$actual_term_posts=array();
foreach ($term_posts as $post)
{
$actual_term_posts[$post->post_title]=get_permalink($post->id);
}
$processed_terms[]=array(
'name'=>$term->name,
'description'=>$term->description,
'url'=>get_term_link($term),
'image'=>$image_src,
'posts'=>$actual_term_posts,
'count'=>$term->count
);
}
$has_next_page=(isset($processed_terms[$terms_page]));
get_header();
?>
<div class="posts-wrap">
<div class="archive-title_wrap"><h1 class="archive-title"><?php the_title(); ?></h1></div>
<div id="post_list_wrap">
<?php
foreach ($processed_terms as $term)
{
echo "<div class='post post-archive'>
<a href='{$term['url']}' title='{$term['name']}'><img src='{$term['image']}' alt='{$term['name']}'></a>
<div class='rating' style='text-align:right;'>{$term['count']} ".($term['count']==1?'review':'reviewuri')."</div>
<h2 class='index-entry-title'>
<a href='{$term['url']}' title='{$term['name']}'>{$term['name']}</a>
</h2>
<div class='archive-meta entry-meta-index'>
<span>";
$first_term_post=true;
foreach ($term['posts'] as $title=>$link)
{
echo ($first_term_post?'':', ')."<a href='{$link}' title='{$title}'>{$title}</a>";
$first_term_post=false;
}
echo "</span>
</div>
</div>";
}
?>
</div>
<?php if ($terms_page>1 OR $has_next_page) { ?>
<div class="navigation">
<div class="nav-prev left"><?php if ($terms_page>1) echo "<a href='/{$slug}/".($terms_page>2?"page/".($terms_page-1)."/":'')."'>".__('« Previous Page', 'designcrumbs')."</a>"; ?></div>
<div class="nav-next right"><?php if ($has_next_page) echo "<a href='/{$slug}/page/".($terms_page+1)."/'>".__('Next Page »', 'designcrumbs')."</a>" ?></div>
<div class="clear"></div>
</div>
<?php } ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

You can use query_posts function like this
$termname = get_query_var('pagename'); //custom-taxonomy term
query_posts(array(
'post_type' => POST_TYPE,
'showposts' => $limit,
'custom-taxonomy' => $termname // use $term1.','.$term2.','.$term3 to get multiple terms posts
));
see Documentation at Wordpress
To get all Terms under Custom Taxonomy try this you will have full control.
global $wpdb;
$taxonomy = CUSTOM_CAT_TYPE;
$table_prefix = $wpdb->prefix;
$wpcat_id = NULL;
//Fetch category or Term as said
$wpcategories = (array) $wpdb->get_results("
SELECT * FROM {$table_prefix}terms, {$table_prefix}term_taxonomy
WHERE {$table_prefix}terms.term_id = {$table_prefix}term_taxonomy.term_id
AND {$table_prefix}term_taxonomy.taxonomy ='" . $taxonomy . "' and {$table_prefix}term_taxonomy.parent=0 ORDER BY {$table_prefix}terms.name ASC");
$wpcategories = array_values($wpcategories);
foreach ($wpcategories as $wpcat) {
$termid = $wpcat->term_id;
$name = $wpcat->name;
$termprice = $wpcat->term_price;
$tparent = $wpcat->parent;
}

Related

How to get the page/post template

I am trying to add custom divs into my index page and I created some page templates, that i was thinking of using as a way to filter out the pages. So basically if the post uses 'Media template' it would be displayed in that div.
But I am struggling in writing the proper php code that would loop trough all the posts and find the post that uses this template.
In the end I want to find a post/page that uses 'Media template' and post it's content in the folowwing div:
<div class="home-media-content col-sm-3 px-1 pb-2">
<div class="embed-responsive embed-responsive-16by9">
<?php
$pages = get_pages();
foreach ($pages as $page) {
echo $page->post_title; //Posting just for the test
echo $page->template; //SHOULD GET THE TEMPLATE and if the template name is 'Media template' display post content
}
?>
</div>
</div>
I am not sure if it is the best way of displaying custom things so any better suggestions are welcome!
Edited to use WP_Query
See below for how I'd do it, using the setup_postdata() and get_page_template() functions. I think you should be able to get this info from the '_wp_page_template' meta for each page if you don't want to setup postdata, but if you're going to be doing a proper loop anyway then the latter is probably easiest.
<div class="home-media-content col-sm-3 px-1 pb-2">
<div class="embed-responsive embed-responsive-16by9">
<?php
$my_query = new WP_Query(
array(
'post_status' => 'publish',
'post_type' => 'page',
)
);
if ( $my_query->have_posts() ) {
while ( $my_query->have_posts() ) {
$my_query->the_post();
the_title(); // Posting just for the test
if ( get_page_template() === 'media-template.php' ) { // This needs to be the file slug rather than template name
do_something();
} else {
do_something_else();
}
}
}
wp_reset_postdata(); // Reset postdata back to normal
?>
</div>
</div>

Assign an image to a taxonomy in wordpress?

I am trying to get a different icon to appear next to an event in Wordpress. I am use the "The Event Calendar" plugin and the events are stored as taxonomies. I have three taxonomies. "Tax1", "Tax2" and "Tax3".
I cannot seem to figure out how to call to check what the taxonomies are and assign an icon to each one. Here is what I have so far.
" title="" rel="bookmark">
<?php $taxonomy_exist = taxonomy_exists( 'Tax2' ); ?>
<?php if(is_tax($taxonomy_exist)) { ?>
<p>working!!!!!!!!!!</p>
<?php } else { ?>
<img class="cat-icon" src="/wp-content/uploads/2017/11/Heart.png" />
<?php } ?>
<?php $title = get_the_title($event); ?>
<?php if (strlen($title) > 30) { ?>
<?php echo mb_strimwidth($title, 0, 30, '...'); ?>
<?php } else { ?>
<?php echo $title ?>
<?php }?></a></span><!--.event-title-->
So it is getting to the if statement and failing, showing the heart icon. How can I see if it is part of the "Tax2" taxonomy?
Problem 1:
is_tax() accepts taxonomy names as a first argument. But you put $taxonomy_exist parameter which is boolean. (true/false). Of course it should not work and always return zero. Because there is not any taxonomy called "true" or "false".
Problem 2: Are you sure that tax1, tax2 and tax3 are taxnomies? may be they are terms? if they are terms then i will add a solution code as an update to this answer. If they are taxonomies, then i don't see any logic there. Because taxonomies are not objects to be related to posts. Taxonomy is name of categorization, terms are member elements of those taxonomies.

How to list posts from categories with custom post type? (WP)

Hi I am having an issues with custom post type.
So what I am trying to do, list all posts from subcategories while calling a main category. Usualy this worked with no problem with normal post type from Wordpress, but since I tried to use custom post type it's not working...
My category structure is like this:
Category
Sub category
( Posts inside )
Sub category
( Posts inside )
Any help or tips are appreciated. Thanks
<?php
$categories = get_categories('title_li=&hide_empty=1&parent=1430');
foreach($categories as $category) {
echo "<div class='col-12' style='border-bottom: 0'><h1 class=''>".$category->name."</h1></div>";
$args = array('cat'=> $category->term_id);
if (have_posts() ) : while (have_posts() ) : the_post(); ?>
<!-- article -->
<article class="col-3">
<div class="image">
<span class="helper"></span><?php the_post_thumbnail('full');?>
</div>
<h1><?php the_title(); ?></h1>
<?php the_content();?>
</article>
<!-- /article -->
<?php endwhile; endif; }?>
</main>
There are a couple of problems going on here:
First, you're not declaring a loop, or calling get_posts.
Second, if you check out the documentation for WP_Query (which is the "backbone" behind get_posts, so the arguments are essentially the same), you'll see that if you do NOT pass in an argument for post type, the default is post.
So, since you've not shared with us the post type, you'll have to adjust the below as needed:
// .. your code above ....
$args = array(
'cat'=> $category->term_id,
// Include the post_type in the query arguments
'post_type' => 'custom-post-type' // Change this as needed
);
// Now we need to actually query for the posts...
$custom_posts = new WP_Query( $args );
// These are modified to use our custom loop...
if ($custom_posts->have_posts() ) : while ($custom_posts->have_posts() ) : $custom_posts->the_post(); ?>
// .. your code below ... the_title(), etc will work here...

Final posts not showing on last category page on wordpress site

I have a WordPress site that has a ton of posts on it, all categorized. I set up a new theme, with pagination (15 posts per page), so the user can cycle through each page. Some of the categories paginate fine. Others are missing the final page.
So, if a category has 66 posts ... the first 4 pages show 15 different posts. However, when I click to view page 5, the page says "no posts found". Where did the last 6 posts go? They still show up in my administration (as published and visible). However, other category pages do not have this issue - for example, I have a category with 42 post, and it has 3 page ... the last page of which has 12 of the final post.
So, the pagination seems to be working fine (since it clearly shows the correct number of pages, for the number of posts). Please take a look below at the code I have... this is code from my templated index.php page (I didnt set up a category.php page, because it lists very similarly to the homepage).
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; // Page
$args = "posts_per_page=15&paged=".$paged; // Base query
$category = get_queried_object(); // Get Cat info
$thisCat = $category->term_id; // Get Cat ID (if exists)
$tagID = get_queried_object()->term_id; // Get Tag ID (if exists)
echo '<!-- paged: '.$paged.'-->';
echo '<!-- catID: '.$thisCat.'-->';
echo '<!-- tagID: '.$tagID.'-->';
if (is_home() || is_front_page()) { // HOMEPAGE
query_posts($args.'&orderby=rand');
echo '<!-- args: '.$args.'&orderby=rand'.'-->';
} elseif ( is_search() ) { // SEARCH RESULTS ?>
<?php
$search_query = get_search_query();
query_posts($args.'&s='.$search_query);
echo "<!-- args: ".$args.'&s='.$search_query."-->"; ?>
<h1>Search</h1>
<div class="content_labels">
<div class="content_label">SEARCH RESULTS FOR: <?php echo $s; ?></div>
</div>
<div class="clear" style="margin:0 0 10px 0;"></div>
<div class="previouspage">
<< Previous Page
</div><?php
} elseif( is_category() ) { // CATEGORY
query_posts($args.'&cat='.$thisCat);
echo '<!-- args: '.$args.'&cat='.$thisCat.'-->'; ?>
<div class="content_labels">
<div class="content_label">Category:</div>
</div>
<h1><?php single_cat_title( '', true ); ?></h1>
<div class="clear" style="margin:0 0 10px 0;"></div>
<div class="previouspage">
<< Previous Page
</div><?php
} elseif( is_tag()) { // TAGS
echo '<!-- args: '.$args.'&tag_id='.$tagID.'-->';
query_posts($args.'&tag_id='.$tagID); ?>
<div class="content_labels">
<div class="content_label">Tag:</div>
</div>
<h1><?php single_tag_title(); ?> </h1>
<div class="clear" style="margin:0 0 10px 0;"></div>
<div class="previouspage">
Previous Page
</div><?php
}
if ( have_posts() ) :
$i=1;
while ( have_posts() ) : the_post(); ?>
// PAGE CODE GOES HERE
endwhile; ?>
<?php base_pagination(); // PAGINATION CODE ?>
<?php endif; ?>
Here is the pagination code, from my functions.php ... I don't think this is the issue...
function base_pagination() {
global $wp_query;
$big = 999999999; // This needs to be an unlikely integer
// For more options and info view the docs for paginate_links()
// http://codex.wordpress.org/Function_Reference/paginate_links
$paginate_links = paginate_links( array(
'base' => str_replace( $big, '%#%', get_pagenum_link($big) ),
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'mid_size' => 5
) );
// Display the pagination if more than one page is found
if ( $paginate_links ) {
echo '<div class="pagination">';
echo $paginate_links;
echo '</div><!--// end .pagination -->';
}
}
Can anyone see what is going wrong? I've been playing with this for several hours, and I can't seem to find a solution...
So, I did some digging, and tried some things... I couldn't find anything wrong with the code above. The query was correct (showing 15 per page, for each category archive page, etc.), and the pagination was working ... In the end, the default POSTS PER PAGE was conflicting with my own posts_per_page=15 query. Not sure WHERE this conflict was occurring (that is beyond my skills) - but I did learn how to stop it.
Under SETTINGS - READING ...
I just changed the "Blog pages show at most" to "15"
This wasn't an ideal fix (since I don't know where this problem started, and I can't adjust custom "posts_per_page" if it differs from 15)... but my site now works how I want.

Wordpress - Add comma to all but last item, remove underscore

I'm using the advanced custom field plugin for Wordpress to show the results of checkboxes. I have what I want working, I just want to tidy up the code and add the following:
Remove the underscore from the social media tag (some kind of stripping out???).
If possible I'd like to show a comma after each "tag" but not if it's the last one.
Here's my test page, they're the blue "tags" under the discipline section.
Here's my code:
<?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');
foreach($catNames as $name){
if(in_array($name, get_field('categories') )){
echo ''.strtoupper($name).'';
}
}
?>
Well it is pretty basic, you just have to do a loop. I could have write something better with more information... anyway this should do exactly what your code did but in a loop.
<?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');
foreach($catNames as $name){
if(in_array($name, get_field('categories') )){ //I don't know what this is suppose to do
echo ''.strtoupper($name).'';
}
}
?>
Try this out:
<?php foreach( get_field('categories') as $category ): ?>
<?php echo ucwords($category) ?>
<?php endforeach; ?>
Ok this should be better
<?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');
foreach($catNames as $name){
$theID = get_cat_ID($name); // get the ID of each category
echo ''.$theID->name.'';
}
?>

Resources