skip to Main Content

I wanted to divide a WordPress post title by the hyphen, in PHP and HTML in a WordPress page for different div’s.

Here’s an example of the title i wanna divide "Charli XCX ft. Billie Eilish – Guess". I wanna separate the "Charli XCX ft. Billie Eilish" of the "Guess".

Here’s the code I’m using, that i cant make work.

<?php
global $my_query;
$post_number = ($my_query->current_post + 1);
$zero_padding = str_pad($post_number, 2, '0', STR_PAD_LEFT);
?>

<?php
$title = get_the_title(); // Get the title string
$token = strtok($title, '-'); // Split the title by the " – " separator
$artist = $token; // Get the artist
$song = strtok('–'); // Get the song title
?>
        
<div class="col center-elements-top10">
  <div class="img-top10" style="background-image: url(<?php the_post_thumbnail_url() ?>)!important;"></div>
    <div class="div-titles">
    <h5 class="number-top10"><?php echo $zero_padding; ?></h5>
  <div>
    <h6 class="mt-2 titles-top10"><?php echo $artist; ?></h6>
    <h5 class="mt-2 titles-top10"><?php echo $song; ?></h5>
  </div>
</div>

I’ve already changed the $token = strtok($title, '-'); but still it wont work.

2

Answers


  1. Chosen as BEST ANSWER

    i've already solved it, i had to change the $title = get_the_title(); to $title = get_post()->post_title;

    in the end it looks like that:

    <?php
    $title = get_post()->post_title; // Get the title string
    $parts = explode(' - ', str_replace('–', '-', $title)); // Replace em dash with en dash and split the title
    
    $artist = trim($parts[0]); // Get the artist and trim any extra spaces
    $song = trim($parts[1]); // Get the song title and trim any extra spaces
    ?>
    

  2. start from adding one missing </div> closing tag:

    <div class="div-titles">

    seems not closed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search