WordPress: Setting the META Description to part of the page’s content

This code puts the first paragraph of the post into the description meta tag. It tries to strip out leading whitespace and any tags. If you insert an image, it should be stripped.

It could probably use some work – like removing leading nonbreaking spaces, dealing with very short first paragraphs, etc.

An explanation of why they start with “myplugin”. What I do in my install is have a “plugin” that holds a bunch of different functions. This way, when the site upgrades, these functions are retained. They might not work – but the code isn’t wiped out.

function myplugin_meta_description() {
        $default = "The default description goes here, or pull it from some configuration value.";
        if (is_home()) return $default;
        if (is_front_page()) return $default;
        if (is_single() or is_page()) {
                $q = get_queried_object();
                if (is_page()) {
                        $obj = get_page( $q->ID );
                } else {
                        $obj = get_post( $q->ID );
                }
                $text = $obj->post_content;
                return myplugin_first_paragraph( $text );
        }
        return $default;
}

function myplugin_first_paragraph( $s ) {
        $s = ltrim(strip_tags($s));
        preg_match('/(.+?)(rnrn|nn|rr)/mu', $s, $matches);
        return $matches[1];
}

The tricky thing is that we need the page content before we reach The Loop.