To fix the issue with hashtags not working when the Activity page is set as the homepage in BuddyPress, you can add a small code snippet to your theme’s functions.php file, or use a code snippets plugin.
function convert_hashtags_to_spans( $content ) {
// Remove <a> tags ONLY if they directly wrap a hashtag (no nested elements)
if( bp_is_activity_directory() || bp_is_group()){
$content = preg_replace_callback(
'/<a[^>]*>(#[\p{L}\p{N}_]+)<\/a>/u',
function ( $matches ) {
return $matches[1]; // just return the hashtag
},
$content
);
// Replace plain-text hashtags with <span> elements
// Ensure we don't match inside HTML tags or attributes
$content = preg_replace_callback(
'/(?<![&\w])#([\p{L}\p{N}_]+)(?![^<]*?>)/u',
function ( $matches ) {
$tag = $matches[1];
return '<span class="activity-hashtag" data-hashtag="' . esc_attr( $tag ) . '">#' . esc_html( $tag ) . '</span>';
},
$content
);
}
return $content;
}
add_filter( 'bp_get_activity_content_body', 'convert_hashtags_to_spans' );
// JavaScript for Auto-Submitting the BuddyPress Search Form
add_action('wp_footer', function() {
?>
<style>
.activity-hashtag {
display: inline !important;
white-space: nowrap;
cursor: pointer;
color: #0073aa;
text-decoration: underline;
}
.activity-hashtag:hover {
color: #005177;
text-decoration: none;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
// Function to fill the form and submit it
function fillAndSubmitSearchForm(searchQuery) {
<?php
if( bp_is_group() ){
$searchInput = 'group-activity-search';
$searchForm = 'group-activity-search-form';
}else{
$searchInput = 'dir-activity-search';
$searchForm = 'dir-activity-search-form';
}
?>
const searchInput = document.getElementById('<?php echo $searchInput; ?>');
const searchForm = document.getElementById('<?php echo $searchForm; ?>');
if (searchInput && searchForm) {
// Set the search value directly
searchInput.value = searchQuery;
// Trigger input and change events to ensure BuddyPress detects changes
searchInput.dispatchEvent(new Event('input', { bubbles: true }));
searchInput.dispatchEvent(new Event('change', { bubbles: true }));
// Submit the form
searchForm.dispatchEvent(new Event('submit', { bubbles: true }));
}
}
// Event delegation for hashtag clicks
document.body.addEventListener('click', function (event) {
const target = event.target.closest('.activity-hashtag');
if (target) {
event.preventDefault(); // Prevent default link behavior
const searchQuery = target.dataset.hashtag;
if (searchQuery) {
fillAndSubmitSearchForm(`#${searchQuery}`);
}
}
});
});
</script>
<?php
});
