Using str_replace to alter a field's display in a Drupal 7 view

568 views Asked by At

I am using the Google Analytics module to retrieve the most popular articles on my site during the past day to populate a 'trending' block.

The problem is that the PageTitle field comes from the meta data and includes a pipe and the site name. I would like to strip that off the end of the string, but I can't figure out how to do it within the view using rewrite results.

I created a views-view-field--pageTitle.tpl.php file and edited it to this:

<?php 
$output = str_replace(" | My Site", "", $output);
print $output;
?>

this doesn't seem to work...

3

There are 3 answers

1
andrefy On

Using the a preprocessor into the template.php will definitely works. There is other options to change the page, but it depends of what modules and what set up you are using to generate that title, clearly is using a patter define somewhere, so without know that my advice is use a preprocessor like this

 function THEME_NAME_preprocess_page(&$variables) {
   //you could use arg to identify your page page
  //https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7.x
    // if the page is the one you are looking then override the title
     drupal_set_title('mytitle');
 }
2
Fky On

I think you have to modify metadata in template.php, so you can do this with :

THEMENAME_html_head_alter(&$head_elements) {
  // dump content of $head_elements and find your value to modify
}

documentation : https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_html_head_alter/7.x

Also you can use metadata module to handle meta : https://www.drupal.org/project/metatag

Hope it helps ;)

2
ZomoXYZ On

If you are sure it always returns it as My Article Title | My Web Site, you could split the string at |.

$result = "My Article Title | My Web Site";   //the string that was returned
$splitResult = explode(" | ", $result);       //split the string at " | ", creating an array: ["My Article Title", "My Web Site"]
$articleTitle = $splitResult[0];              //get the first item in the array