Support » Developing with WordPress » How to generate Page meta description programmatically, on fly?

  • Hi there

    My WordPress pages need to have dynamic (programmatically generated) meta-description and title in the <head> section.

    – Where will I use PHP code for this? In the Page Template? In functions.php? Or somewhere else?
    – How will I ensure that the title and meta description are added between <head> and </head>, and not elsewhere like in the <body> section?


Viewing 3 replies - 1 through 3 (of 3 total)
  • It’s easiest to use a plugin for SEO to do this for you.
    You can output something in the <head> section by using add_action( 'wp_head', 'my_function_name'); if you want to write it yourself. Make a little plugin, so that you can use it with any theme.

    Hi @joyously

    – Where will this code (add_action) go? In functions.php or where exactly?
    – Can I use some code in a custom template, so programmatically generated meta tags are added to the pages based on that template?

    Thanks so much.

    • This reply was modified 1 month, 2 weeks ago by mplusplus.

    As I said, you should use an existing plugin (since you don’t understand how to write one), or study the Plugin Handbook so you can make your own plugin. The code would go in the main plugin file. (If you put code in functions.php, it is tied to your theme, and it’s less convenient to switch themes, like for debugging problems.)
    You can use the Code Reference to look up WordPress functions.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.