News:

Bored?  Looking to kill some time?  Want to chat with other SMF users?  Join us in IRC chat or Discord

Main Menu

Getting content of first post in META Description

Started by Daniel Hofverberg, January 12, 2008, 09:22:01 PM

Previous topic - Next topic

Daniel Hofverberg

Is there any reasonably easy way to add the actual body of the first post of the current topic as the Meta Description tag (or the beginning of the text, if it's a very long post)?

At least with the default theme, the Meta Description tag by default only contain the page title, I e the exact same as the TITLE tag, which isn't of much help. It would be much better to actually use the text from the first post as the description - as the description often is used in search results from search engines, text from the first post would be of much bigger use to people searching than an exact duplicate of the Title tag.

I would imagine that it should be possible to accomplish this by just editing the templates. But unfortunately my knowledge of the templating system and the available functions in SMF really isn't good enough to be able to do this myself. So can anyone help me, or at least point me in the right direction? I've tried searching on all boards here, with no success.

I'm running SMF 1.1.4 with the default theme.

karlbenson



flickernever

But isn't there a way to do this without SEO4SMF? This mods seems buggy to me.

Daniel Hofverberg

I would also prefer to do it without SEO4SMF, as I'd rather not install such a big mod just for this purpose. But thanks for the suggestion anyway. If I take my time, it should be possible to figure out how to do it by looking at the code for that mod and then do it myself. But of course, if anyone has already managed to, it would save me the trouble.

flickernever

Quote from: Daniel Hofverberg on January 15, 2008, 03:15:45 AM
I would also prefer to do it without SEO4SMF, as I'd rather not install such a big mod just for this purpose. But thanks for the suggestion anyway. If I take my time, it should be possible to figure out how to do it by looking at the code for that mod and then do it myself. But of course, if anyone has already managed to, it would save me the trouble.


Absolutely, I agree with you.

I was able to pull out the function code that creates descriptions on SEO4SMF:

function create_description()
{
    global $context, $modSettings;
    $description = "";
    $oldlevel = error_reporting(0);
    if (isset($context['description_']))
        return 'meta name="description" content="'.$context['description_'].'" /';
     
    if (isset($context['current_action']))
        if ($context['current_action'] == "profile")
    {
        return 'meta name="description" content="Profile for member '.$context['member']['username'].'" /';
    }
     
    if (!isset($context['current_board']) && !isset($context['current_topic'])) //we are on root
    {
        $description = $modSettings['seo4smf_description_content_index'];
    }
    else
    {
        if (!isset($context['board_description']))
        {
            switch ($modSettings['seo4smf_description_content_boards'])
            {
                case 1:
                $description = $context['name'];
                break;
                case 2:
                $description = $context['description'];
                break;
                case 3:
                $description = $context['name'].' '.$context['description'];
                break;
                case 4:
                $description = $context['name'].' '.$modSettings['seo4smf_description_content_index'];
                break;
                case 5:
                $description = $context['name'].' '.$modSettings['seo4smf_description_content_index'].' '.$context['description'];
                break;
            }
        }
        else
        {
            switch ($modSettings['seo4smf_description_content_topics'])
            {
                case 1:
                $description = $context['first_message_body'].' '.$context['board_name'];
                break;
                case 2:
                $description = $context['first_message_body'].' '.$context['page_title'];
                break;
                case 3:
                $description = $context['first_message_body'].' '.$context['page_title'].' '.$context['board_name'];
                break;
                case 4:
                $description = $context['first_message_body'].' '.$context['board_name'].' '.$context['page_title'];
                break;
                case 5:
                $description = $context['first_message_body'].' '.$context['board_description'];
                break;
                case 6:
                $description = $context['first_message_body'];
                break;
                case 7:
                $description = $context['page_title'].' '.$context['board_name'];
                break;
                case 8:
                $description = $context['page_title'];
                break;
                 
            }
             
        }
    }
    $description = str_replace("\n"," ",$description);
    $description = preg_replace('/<a(.*)<\/a>/', '', $description); //removing url's ... is that enough ?
    $description = trim(strip_tags($description));
    $description = un_htmlspecialchars($description);
    $description = str_replace(array("<", ">", "\\", "\"", "="), " ", $description);
    $description = substr($description, 0, $modSettings['seo4smf_description_length']);

    $description = 'meta name="description" content="'.$description.'" /';
    error_reporting($oldlevel);
    return $description;
}



I don't know any PHP though, maybe someone with knowledge of PHP understands this code and could help us out.

rsw686

Here's what I did to the meta tags on my forum.

http://www.simplemachines.org/community/index.php?topic=193205.msg1229898#msg1229898

I agree that the SEO4SMF mod is buggy. I use the sitemaps.php file from it. Although it had redundant code, etc so I modified it a bit. Works great now. The had the idea down, just the implementation is a bit off.
The Reptile File
Everything reptile for anyone reptile friendly

Aquaria Talk
Community for freshwater and saltwater aquariums enthusiasts

Daniel Hofverberg

rsw686: Your code in the linked post is excellent for the index of each boards (adding the board description), but it doesn't add parts of the first post on message display, which is what I was asking for. But thanks for the suggestion on board level.

Quote from: flickernever on January 15, 2008, 07:59:49 PM
Absolutely, I agree with you.

I was able to pull out the function code that creates descriptions on SEO4SMF:

I don't know any PHP though, maybe someone with knowledge of PHP understands this code and could help us out.
I do know PHP quite well, but what I don't know enough about is SMFs functions, arrays and templating system.

I can somewhat understand the function that you posted that actually creates the description, but I can't seem to find that SEO4SMF actually modifies the existing Meta Description line in Index.template.php; so I really can't make any sense out of it... Can anyone else help?

rsw686

Quote from: Daniel Hofverberg on January 16, 2008, 09:53:21 AM
rsw686: Your code in the linked post is excellent for the index of each boards (adding the board description), but it doesn't add parts of the first post on message display, which is what I was asking for. But thanks for the suggestion on board level.

It adds the message subject. With a quick sql query for $topicinfo['ID_FIRST_MSG'] you could grab the first message text. Look at the code right after where I add to Display.php and you'll see what I'm getting at.
The Reptile File
Everything reptile for anyone reptile friendly

Aquaria Talk
Community for freshwater and saltwater aquariums enthusiasts

rsw686

Heres the code for Display.php. You would need to use this in conjunction with the link I posted above.


$request = db_query("
SELECT body FROM {$db_prefix}messages
WHERE ID_MSG = '" . $topicinfo['ID_FIRST_MSG'] . "'", __FILE__, __LINE__);
list ($meta) = mysql_fetch_row($request);
mysql_free_result($request);

$context['page_title'] = $topicinfo['subject'] . ' - '. $context['forum_name'];
$context['meta_description'] = substr($meta,0,100);
$context['meta_keywords'] = $topicinfo['subject'];
The Reptile File
Everything reptile for anyone reptile friendly

Aquaria Talk
Community for freshwater and saltwater aquariums enthusiasts

Daniel Hofverberg

Thank you for your help. I will try to add this, and will report back.

If I manage to get this to work, I will of course post a complete description for flickernever and other people without PHP knowledge.

Stüldt Håjt

I think that the best option for topics is to be without meta description. When people make searches it will show relevant text instead of the description.

http://2optimize.wordpress.com/2007/02/27/google-snippets-better-than-meta-description/

I for index page I have my own description, for boards I have the board description and for topics I don't have a meta description.

rucanunes

Hello,

I saw your this about Meta Tags and I would like to ask you a few questions, if you don't mind...

I placed the 3 blocks of code in the 3 files you mention but I'm having a problem;
- If you look at my Meta Description and Meta Keywords, you'll see:

<meta name="description" content="O maior portal para professores de Portugal., Sexo em casas de banho dá polémica nos EUA" />
<meta name="keywords" content="fórum,sala dos professores, saladosprofessores, professores, ensino, Portugal, ensino em Portugal, disciplina, disciplinas, educadores, educadoras, educadores de infância, professor universitário, português, inglês, francês, alemão, matemática, história, geografia, e.v.t., educação musical, educação física, filisofia, estudo acompanhado, formação cívica, área de projecto, professor, professores, fórum, ciências da natureza, biologia, fisico-química, economia, informática, desporto, e.m.r.c., , Sexo, em, casas, de, banho, dá, polémica, nos, EUAPosta Restante,, Sexo, em, casas, de, banho, dá, polémica, nos, EUA" />


As you can see there are some duplicated commas and 1 comma missing at "EUAPosta". That sould be "EUA, Posta".
And the keywords are duplicated too.

Here's the code of my Index.template.php

<meta name="keywords" content="', !empty($context['meta_keywords']) ? $context['meta_keywords'] . ', ' : '', '" />
<meta name="description" content="', empty($context['meta_description']) ? '' : $context['meta_description'], '" />', empty($context['robot_no_index']) ? '' : '
<meta name="robots" content="noindex" />', '


Also, could you please tell me (step by step), if you don't mind, how can I place the content of the first post on Meta Description?

Thank you,
R Nunes
Sala dos Professores http://www.saladosprofessores.com

Daniel Hofverberg

Quote from: Stüldt Håjt on January 17, 2008, 06:15:41 AM
I think that the best option for topics is to be without meta description. When people make searches it will show relevant text instead of the description.

http://2optimize.wordpress.com/2007/02/27/google-snippets-better-than-meta-description/

I for index page I have my own description, for boards I have the board description and for topics I don't have a meta description.
I guess that's a matter of opinion, and could likely differ between different sites. For my sites, I consider Meta Description to be better than Google's generated snippets. Anyway, I think we can all agree that SMF's default way to use the page title as meta description is completely useless, as it makes the meta description tag identical to the title tag. In that case, it's better to remove the meta tag altogether.

rsw686

Quote from: Stüldt Håjt on January 17, 2008, 06:15:41 AM
I think that the best option for topics is to be without meta description. When people make searches it will show relevant text instead of the description.

http://2optimize.wordpress.com/2007/02/27/google-snippets-better-than-meta-description/

I for index page I have my own description, for boards I have the board description and for topics I don't have a meta description.

Then why does Google have a meta section in their Webmasters website. I just use the subject text and it has told me a couple of them are too short.
The Reptile File
Everything reptile for anyone reptile friendly

Aquaria Talk
Community for freshwater and saltwater aquariums enthusiasts

rsw686

Quote from: rucanunes on January 17, 2008, 07:54:02 AM
Here's the code of my Index.template.php

<meta name="keywords" content="', !empty($context['meta_keywords']) ? $context['meta_keywords'] . ', ' : '', '" />
<meta name="description" content="', empty($context['meta_description']) ? '' : $context['meta_description'], '" />', empty($context['robot_no_index']) ? '' : '
<meta name="robots" content="noindex" />', '


I don't see where the extra commas are coming from. This makes no sense to me as there are no commas in the above code. The rest is generated from the message subject and board description. So maybe those have the extra commas in them.
The Reptile File
Everything reptile for anyone reptile friendly

Aquaria Talk
Community for freshwater and saltwater aquariums enthusiasts

Daniel Hofverberg

#16
Okay, I have finally managed to add the contents of the first post in MÉTA Description, by using the code mentioned by rsw686 in this post and the linked thread, combined with code of my own. It seems to work, but I'm sure there are more efficient and more elegant ways to do it.

For everyone interested, do the following:

Open MessageIndex.php. Find these lines:
// 'Print' the header and board info.
$context['page_title'] = strip_tags($board_info['name']);


Add directly after that:
$context['meta_description'] = $board_info['description'];


Open Display.php. Find these lines:
// Censor the title...
censorText($topicinfo['subject']);
$context['page_title'] = $topicinfo['subject'];


Add directly after that:
$request = db_query("
SELECT body FROM {$db_prefix}messages
WHERE ID_MSG = '" . $topicinfo['ID_FIRST_MSG'] . "'", __FILE__, __LINE__);
list ($meta) = mysql_fetch_row($request);
mysql_free_result($request);

//Remove quote tags, quotation marks and other unsuitable characters before passing it as meta description
$meta = html_entity_decode($meta, ENT_QUOTES);
$meta = preg_replace('/\[quote(.*)\]/', '', $meta);
$meta = preg_replace('/\[url\=(.*?)\]/', '', $meta);
$meta = str_replace('[/url]', '', $meta);
$meta = str_replace('<br />', ' ', $meta);
$meta = strip_tags($meta);
$meta = str_replace(array('"', '\'', '  '), array('', '', ' '), $meta);
if (strlen($meta) > 200) {
$meta = substr($meta,0,200);
$last_space = strrpos($meta, ' ');
$context['meta_description'] = trim(substr($meta, 0, $last_space));
} else
$context['meta_description'] = $meta;


Finally, open Index.template.php in the theme you're using (only the standard theme that guests will see matter, as search engines won't notice any other selectable themes). Find these lines:

<meta name="description" content="', $context['page_title'], '" />',


Replace that with:

<meta name="description" content="', empty($context['meta_description']) ? 'Add a default short description here, that will be used on the forum index.' : $context['meta_description'], '" />',


Of course change the description to suit your forum. Be sure not to touch the rest of the line in Index.template.php (empty($context['robot_no_index']) etc).

This works on my forum, but use it on your own risk and be sure to backup all files you edit beforehand. It will make all topic pages use the first 200 characters of the first post in that topic as the meta description and board index pages (each individual board) will use the board description as meta description. Other pages, such as the forum index, will use the hard-coded description in Index.template.php. I didn't bother to use rsw686's code for Meta Keywords, as pretty much no search engine cares about that anymore, but feel free to follow his instructions in the linked topic if you want to do that.

One warning: I'm using the PHP function html_entity_decode in one place. That function only exists as of PHP 4.3.0, so it doesn't work with older versions than that. It shouldn't be a big problem for most, as most web hosts should use a version higher than 4.3.0 by now.

Once again, thanks to rsw686 for the help to get me started. Please let me know if anything doesn't work, or if you have any suggestions to improve it, and I will try to fix it.

flickernever

Thats great work Daniel Hofverberg. Thanks a lot for sharing!  :)

rsw686

Quote from: Daniel Hofverberg on January 27, 2008, 05:29:11 AM

//Remove quote tags, quotation marks and other unsuitable characters before passing it as meta description
$meta = html_entity_decode($meta, ENT_QUOTES);
$meta = preg_replace('/\[quote(.*)\]/', '', $meta);
$meta = preg_replace('/\[url\=(.*?)\]/', '', $meta);
$meta = str_replace('[/url]', '', $meta);
$meta = str_replace('<br />', ' ', $meta);
$meta = strip_tags($meta);
$meta = str_replace(array('"', '\'', '  '), array('', '', ' '), $meta);
if (strlen($meta) > 200) {
$meta = substr($meta,0,200);
$last_space = strrpos($meta, ' ');
$context['meta_description'] = trim(substr($meta, 0, $last_space));
} else
$context['meta_description'] = $meta;


This seems like a lot of work when you could just use parse_bbc and then strip the html tags. I made a mod for 2.0 that does something similar to what your accomplishing. The below is a modified version that should be able to replace the above code. Hopefully I didn't make any typos.


// Convert breaks to spaces. Otherwise there won't be a space between words.
$meta = str_replace('<br />', ' ', parse_bbc($meta))
// Deal with double quotes and remove the html tags.
$meta = str_replace('"', '&quot;', strip_tags(html_entity_decode($meta, ENT_QUOTES)))

// Less than the teasear limit, just return.
if(strlen($meta) < 150)
$context['meta_description'] = $meta;
// Otherwise grab the teaser making sure to not cut a word in half.
else
{
$meta = substr($meta, 0, 150);
$context['meta_description'] = substr($meta, 0, strrpos($meta, ' '));
}
The Reptile File
Everything reptile for anyone reptile friendly

Aquaria Talk
Community for freshwater and saltwater aquariums enthusiasts

Autoteilekauf.com

wow! Big thx to Daniel Hofverberg!

I searched this forum for many hours but now i found this
and it works great! Now the robots can come. :-))

Advertisement: