0

I am try to get rid of the category name appearing from the list of post titles. Here's the code I am using:

<?php
$category = get_queried_object();
if ($category) {
    $category_name = $category->name; // Get the name of the current category
    $category_id = $category->term_id;
    $query = new WP_Query(array(
        'cat' => $category_id,
        'tag_id' => 11, // Show posts with tag ID 11
        'posts_per_page' => 10
    ));

    if ($query->have_posts()) {
        echo '<ul>';
        while ($query->have_posts()) {
            $query->the_post();
            $post_title = get_the_title();
            // Remove the category name from the post title
            $escaped_category_name = preg_quote($category_name, '/');
            $title_without_category = preg_replace('/\b' . $escaped_category_name . '\b/i', '', $post_title);
            echo '<li><a href="' . get_permalink() . '" style="text-decoration: none;">' . $title_without_category . '</a> </li>';
        }
        echo '</ul>';
    } else {
        echo '<p class="noposts" style="padding-left: 2em;">No posts found for ' . $category_name . '. If you have any suggestions, please let us know.</p>';
    }

    wp_reset_postdata();
}
?>

The code above works if there is no apostrophe included in the category name. For example, let's say the post title is Hello World and Me. Hello World is the category. I am getting the correct output which is and me. But when the category name has apostrophe like Hello World's and me. I am not getting the expected output which is the and me post title only.

Can anyone help me with this issue? Thanks!

I am try to get rid of the category name appearing from the list of post titles.

Sekiroweb
  • 5
  • 2

1 Answers1

0

Apostrophes can be tricky, because they can be curly/smart () or straight ('). Using this answer, you can convert "fancy" entities to "casual" entities.

Tested:

$category_name = 'Hello World’s';
// $category_name = 'Hello World\'s';
// $post_title    = 'Hello World’s and me';
$post_title    = 'Hello World\'s and me';

// Convert fancy entities to casual entities.
$category_name = iconv( 'UTF-8', 'ASCII//TRANSLIT', $category_name );
$post_title    = iconv( 'UTF-8', 'ASCII//TRANSLIT', $post_title );

$escaped_category_name  = preg_quote( $category_name, '/' );
$title_without_category = preg_replace( '/\b' . $escaped_category_name . '\b/i', '', $post_title );

echo $title_without_category;
Caleb
  • 1,058
  • 1
  • 7
  • 18
  • Thank you. I also tried that but it seems it's still not working on my end. The apostrophe showing on my end looks like this `’` which is the same as the one you have. – Sekiroweb Jul 01 '23 at 13:07
  • Just copy and pasted into W3Schools' PHP Tryit Editor, and it worked there as well. What is the exact text of the category, and what is the exact text of the post? – Caleb Jul 01 '23 at 16:26