1

I have been working on a code, that finds particular words from my content and converts them to wordpress Taxonomy Tags. I want to prefix them with a '#' symbol... But somehow it doesn't work

This is the code:

 preg_match_all('/ #([A-Za-z\/\.]*) /', $content, $matches, PREG_PATTERN_ORDER); 
if(isset($matches[1])){ 
foreach($matches[1] as $matchKey){ 
    $HashTag= $matchKey;
wp_set_post_tags( $ID, '#'.$HashTag, true); 
} 

The issue is in the second last line of the code...

wp_set_post_tags( $ID, '#'.$HashTag, true); 

I put a # symbol behind my text when setting post tags... But when the code executes the # is ommited and only $HashTag is echoed....

I tried to see if the issue is with something else so i tried using other words and alphabets other than '#'

wp_set_post_tags( $ID, 'ABC'.$HashTag, true); 

It worked perfectly and had ABC behind each of my tags. I tried to do it with single alphabet and yet again it worked.

wp_set_post_tags( $ID, 'Z'.$HashTag, true); 

But still I fail to do the trick with '#' symbol, so please help me out...

Thanks in Advance...

  • It looks like term names are sanitized internally. Could you go through sanitize_term_field() and check if one of those filters removes the #? – kero Oct 17 at 12:27
  • Hey there, i have no knowledge of how sanitize_term_field works... But may i tell you i tried this 'ab#'.$HashTag basically adding 2 alphabets before the hash, and suprisingly it worked. It had presevered the # along with 2 alphabets in the output... – Aditya Agarwal Oct 17 at 12:35
  • I can't test this right now, sorry. Check the source code of the method I linked, there are a couple of apply_filter('...', $var) calls there. You can try these out inside your own code, my guess is that one of those strips special characters from beginning and end – kero Oct 17 at 15:08
  • When you add a tag via the standard admin page (for managing tags), does #example and ex#ample both work? But as kero pointed, there could be a code (in a plugin or the active theme) which is stripping the # when put at the start of the tag name. – Sally CJ Oct 17 at 16:25
  • Okay, So i am not good at code... I assumed that if wordpress cuts first few characters, i added few spaces before it but that didn't work. I honestly couldn't understand how to tackle the sanitize thing... Things didn't work... I tried to str_replace() to change space with hashtag.... And it didn't work too... – Aditya Agarwal Oct 17 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.