Support » Developing with WordPress » Using excerpt as tag description

  • Resolved Galaxy_High

    (@galaxy_high)



    Hello everyone,

    I’m trying to create a function that allows me to replace the tag description with the excerpt of the same name/slug.

    i.e. mypage.com/category/apples and mypage/tags/apple

    Is this possible?

    Here is what I have so far:

    function tags(){
    if (is_page('tag')){$tags = get_tags();}
    else{$tags = get_the_tags();}	
    if (! $tags){echo "";}
    else{
    $html = '<ul class="tags">' . "\r\n\t" . '<li>Tags: </li>' . "\r\n\t" . '';
    foreach ( $tags as $tag ){
    	$tag_link = get_tag_link( $tag->term_id );
    	$tag_group_labels = get_option( 'tag_group_labels', array() );
    	$tag_group_ids = get_option( 'tag_group_ids', array() );
    	$i = array_search($tag->term_group, $tag_group_ids);
    	$lower = array_map('strtolower', $tag_group_labels);
    	$description = str_replace('"', "''", $tag->description);
    	global $post;
    
    	$post_id = $tag->slug;
    	$id = get_post($post_id);
    			
    	$html .= '<li class="' . $lower[$i] . ' ' . $tag->slug . ' tag">' . "\n\t";
    	$html .= '<a href="' . $tag_link . '"';
    	$html .= ' title="' . $tag->name . "\n\n";
    			
    	$html .= 'tag name: ' . $post_id . "\n\n";
    	$html .= 'post name: ' . $post->post_name . "\n\n";
    	$html .= 'post id:' . get_the_ID() . "\n\n";
    	$html .= 'tag description: ' . $description . "\n\n";
    			
    	$html .= 'Tagged in ' . $tag->count . ' posts' . "\n\n";
    	$html .= 'Catergory: ' . $tag_group_labels[$i] . "\n" . '">';
    	$html .= $tag->name;
    	$html .= '</a></li> '. "\n\n\t";
    	}
    $html .= '</ul>';
    echo $html;
    echo "\r\n";
    }
    }

    $description is pulling in the actual description of the tag not the excerpt of the corresponding post.

    Thanx for looking,
    Sam

    • This topic was modified 1 year, 7 months ago by  Galaxy_High. Reason: Formatting
    • This topic was modified 1 year, 7 months ago by  Galaxy_High.
Viewing 12 replies - 1 through 12 (of 12 total)
  • Moderator bcworkz

    (@bcworkz)

    To get a post object by slug, you need to use get_posts() using the appropriate argument, as in $args = array('name'=> $tag->slug,); As there can be only one slug match, get_posts() will return at most an array of one element. From that the excerpt can be extracted. Something like $description = $posts[0]->post_excerpt;

    Sorry for the late reply, alert went to my spam folder.

    Thanx for getting back to me. I’ll report how it goes on Monday.

    Regards,
    Sam

    Hello again,

    I’m not sure I’m implementing the code correctly.

    I’ve declared my variables and called [0] from the array.

    foreach ( $tags as $tag ){
    ...
    $tagslug = $tag->slug;
    $args = array('name' => $tagslug);
    $excerpt = get_posts($args);
    $output = $excerpt[0]->post_excerpt;
    ...
    $html .= 'relative excerpt to tag: ' . $output . "\n\n";
    }

    The tag description is generating from the excerpt but only if it matches the post it’s nested in, if that makes sense?

    My foo tag is pulling in the foo post excerpt when the foo tag is in the foo post but it doesn’t pull in any of the other tag’s relative excerpts.

    What am I doing wrong?

    Thanks again for your help,
    Sam

    Moderator bcworkz

    (@bcworkz)

    Maybe I’ve misconstrued what you’re trying to do. It sounds like your script is doing what I expected.

    > “it doesn’t pull in any of the other tag’s relative excerpts.”

    I don’t understand. Where are the other tags supposed to get excerpts if not from the excerpt of a post name that matches the tag’s slug?

    I do want it to get the excerpt from the post with the slug the same name as the tag and use it as the tag description but I’m doing something wrong.

    The code works when the post slug and tag slug are equal.

    • post apples
      excerpt
      tag: apples (returns post apples excerpt as description)
      tag: banana (returns nothing)
    • post banana
      excerpt
      tag: apples (returns nothing)
      tag: banana (returns post banana excerpt as description)

    The problem is me not explaining it very well.

    Thanks again.

    • This reply was modified 1 year, 7 months ago by  Galaxy_High. Reason: formatting
    Moderator bcworkz

    (@bcworkz)

    Ah! I see what you mean now. Would you please post your entire function declaration for tags output? And confirm: this tags() function is called from a template within a typical posts loop.

    Here’s my tag function…

    function tags(){
    
    if (is_page('tag')){$tags = get_tags();}
    else{$tags = get_the_tags();}		
    if (! $tags){echo "";}
    else{
    $html = '<ul class="tags">' . "\r\n\t" . '<li>Tags: </li>' . "\r\n\t" . '';
    foreach ($tags as $tag){
    	$tag_link = get_tag_link($tag->term_id);
    
    	$tag_group_labels = get_option('tag_group_labels', array());
    	$tag_group_ids = get_option('tag_group_ids', array() );
    	$i = array_search($tag->term_group, $tag_group_ids);
    	$lower = array_map('strtolower', $tag_group_labels);
    	$description = str_replace('"', "''", $tag->description);
    	global $post;
    
    	//testing variables
    	$tagslug = $tag->slug;
    	$args = array('name' => $tagslug);
    	$excerpt = get_posts($args);
    	$output = $excerpt[0]->post_excerpt;
    	
    	$html .= '<li class="' . $lower[$i] . ' ' . $tag->slug . ' tag">' . "\n\t";
    	$html .= '<a href="' . $tag_link . '"';
    	$html .= ' title="' . $tag->name . "\n\n";
    	
    	//testing variables
    	$html .= 'tag slug: ' . $tag->slug . "\n\n";
    	$html .= 'post name: ' . $post->post_name . "\n\n";
    	$html .= 'post id: ' . get_the_ID() . "\n\n";
    	$html .= 'tag id: ' . $tag->term_id . "\n\n";
    	$html .= 'tag description: ' . $description . "\n\n";
    	$html .= 'post excerpt: ' . $post->post_excerpt . "\n\n";
    	$html .= 'relative excerpt to tag: ' . $output . "\n\n";			
    	
    	$html .= 'Tagged in ' . $tag->count . ' posts' . "\n\n";
    	$html .= 'Catergory: ' . $tag_group_labels[$i] . "\n" . '">';
    	$html .= $tag->name;
    	$html .= '</a></li> '. "\n\n\t";
    	}
    $html .= '</ul>';
    echo $html;
    echo "\r\n";
    }
    }

    …and here’s how I’m calling it in the loop…

    $cats = array(
    'corporations',//2
    'events',//3 
    'media',//4
    'operations',//5
    'organisations',//6
    'people',//7
    'places',//8
    'products',//9
    'projects',//10
    'recent-enteries');//3685
    
    foreach ($cats as $c){
    $posts = query_posts( $query_string . '&orderby=' . $_SESSION['selection'] . '&order=' . $_SESSION['order'] . '&cat=' . $c );
    
    if( $posts ) : while (have_posts()) : the_post();
    
    echo '<article>' . "\n";
    	title();
    	thumbnail();
    	echo '<div class="content_container">';
    		echo '<div class="excerpt">' . the_excerpt() . '</div>' . "\n";
    		if(strpos($post->post_content, '<!--nextpage-->')){
    			echo '<p class="postcount">This post contains multiple pages: ';
    			single_link_pages();
    			echo '</p>';
    			}
    		echo '<div class="post_footer">';
    			if (function_exists(posted)){posted();}
    			if (function_exists(updated)){updated();}
    			if (function_exists(wordcount)){wordcount();}
    			echo '</div><!--end post_footer-->';
    		echo '</div><!--end content_container-->';
    	<strong>tags();</strong>
    	echo '</article>' . "\n\n";
    endwhile;
    endif;
    }

    Thanks for getting back to me. I’ve hit a wall and struggling to understand.

    Moderator bcworkz

    (@bcworkz)

    FYI, you original long code listing post eventually went through, it got put in the moderation queue, probably because of the long code. One of our mods eventually released it. I should have warned you about posting a lot of code. For future reference, please use pastebin.com for extended code snippets and just link to it here. I also removed redundant and superfluous posts from view to keep things orderly. Generally speaking, if a post that should have gone through (i.e. not actual spam) does not appear to go through, just wait a while, things usually sort themselves out. Either the cache refreshes or a mod releases your post from moderation. Going to moderation does not mean you did anything wrong, the posts the system finds needing further examination have no rhyme or reason to what it picks. It picks posts, mods look at it and typically release it. It just takes a while.

    Anyway, back to your code. I tried to adapt it to my installation with minimal adjustments. I did find a few issues that should be addressed, but they are unrelated (I think) to getting post excerpts from tag slugs. The excerpts from tag slugs works fine AFAICT. So address these items I noticed and see if that helps any. Fixing these will at least allow you to be closer to determining the cause if it’s not fixed outright.

    In the loop, in those function_exists() arguments (posted, updated, wordcount), each argument must be presented as a string: function_exists('posted'))

    If there is not already a similar line on your template, add a global $post; line first thing in the loop.

    This line: <strong>tags();</strong> is bad syntax. Make it into proper echo statements

    echo '<strong>';
    tags();
    echo '</strong>';

    In the tags() function, I got invalid index errors due to the $i value. Probably because I do not have any tag groups. I commented out any lines with $i. If these work for you, then fine. I just cannot confirm if they work correctly or not.

    If there is any chance at all that there is a tag slug without a corresponding post with excerpt, you need to add this line right below the get_posts() call:
    if (!$excerpt ) continue;

    The tags() output was not displaying because all of the debug content ended up being illegal anchor tag attributes. Just so the output displays, I changed this line: $html .= ' title="' . $tag->name . "\n\n"; to this:
    $html .= ' title="' . $tag->name . "\">link</a>\n\n";

    And removed the </a> from this line: $html .= '</a></li> '. "\n\n\t";

    The above may be fine without the debug output. I only changed it to easily see the output. I queried for posts completely unrelated to the posts I added that matched tag slugs, so this should be the same situation as “bannana” being unrelated to “apples”, which in your case returned nothing. In my testing, your code, except altered as noted, returned excerpts from posts with the same tag slug, even though the tag slugs did not relate to posts in the loop. The loop posts merely had tags assigned, their slugs had nothing similar to tag slugs.

    If, after making the corrections I suggested, you still have trouble getting unrelated tag->post excerpts, first double check the page’s HTML source to make sure the data is not simply hidden from view. If not that, apparently some plugin or your theme is causing unwanted interactions. Try deactivating all plugins and switching to the twentysixteen theme. Make a copy of twentysixteen’s page.php, giving it a new name. Replace the header comment with something like /* Template Name: Tag Excerpt Test */ Replace all of the loop code with your own. Place the tags() function declaration between the header comment and get_header(); ?>

    Create a new WP page based on this template. View the new page. If all was done correctly, you should see a complete list as you expected, in particular the tag->post excerpts should work for all tags.

    Reactivate your plugins one by one. Test your custom page after each. Once the output goes bad again, the last activated plugin is the culprit. If you activate all of your plugins and no problems recur, the problem was likely your theme. Confirm by copying your custom template to your normal theme, the reactivate your normal theme and view the new page. It should fail. If it looks good, determine why the page works and your original code does not. What’s different?

    • This reply was modified 1 year, 7 months ago by  bcworkz. Reason: added missing backticks in line with tags()

    This is gold!

    Thank you. I’ll try these suggestions tomorrow when I have some spare time. Think I’m going to install the 20 16 theme and step through each point as you suggest.

    Really appreciate you taking time to help me out.

    Thanx again.

    It’s what you predictided; I broke my theme somehow.

    Started from scratch and everything seems to be working fine.

    Thanks for all your help.

    Regards,
    Sam

    Moderator bcworkz

    (@bcworkz)

    You’re welcome. Probably just as well. Many times I’ve embarked on a project, only to run into unforeseen issues. In dealing with these issues, the code becomes a mess. Starting over while knowing what issues will be encountered results in much better code. I write off the initial effort as a trial, proof of concept run 🙂

Viewing 12 replies - 1 through 12 (of 12 total)
  • The topic ‘Using excerpt as tag description’ is closed to new replies.