evu
evu

Reputation: 1061

Automatically populating meta descriptions in Opencart

I'm trying to add meta descriptions to 700+ products on a site I'm working on in Opencart and I'm hoping I don't have to do it manually. There's already product descriptions for each product and I've come across a script that accomplishes this to an extent but I need to tweak it slightly. Not being anywhere near a PHP guru, I was hoping someone on SO could help.

Here's the code:

// Registry
$registry = new Registry();

// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);

// Config
$config = new Config();
$registry->set('config', $config);

function get_meta_desc($string){
    return substr(strip_tags($string), 0, 255); 
}

// Database 
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);

$query = $db->query("SELECT * FROM `" . DB_PREFIX . "product_description` Order By product_id ASC");

foreach ($query->rows as $row){
    $query2 = $db->query("UPDATE `" . DB_PREFIX . "product_description` SET meta_description = '". mysql_real_escape_string(get_meta_desc($row['description'])) ."' WHERE product_id = '".$row['product_id']."'");
}

echo 'done';
@unlink('runonce.php');

The problem though, is it's not stripping out HTML tags. I don't know PHP too well but that looks to me like it should work, I can't figure out why not.

The other thing I was hoping to add to the script was a way of checking if there's already content in the meta description, if so don't do anything and skip to the next one.

Thanks, evu.

Upvotes: 0

Views: 1160

Answers (1)

P. Galbraith
P. Galbraith

Reputation: 2527

The description is usually html encoded before being placed in the database.

So your function should be:

function get_meta_desc($string){
    return substr(strip_tags(html_entity_decode($string)), 0, 255); 
}

To check if a meta description exists you need to check the meta_description column:

function get_meta_desc($string, $meta){
    if(!empty($meta))
        return $meta;

    return substr(strip_tags(html_entity_decode($string)), 0, 255); 
}

get_meta_desc($row['description'], $row['meta_description']);

Upvotes: 1

Related Questions