How to automatically add IDs to headings using functions.php in WordpressCan I install/update WordPress plugins without providing FTP access?How to add a PHP page to WordPress?Wordpress capabilities and current_user_can() in functions.phpCorrect file permissions for WordPressCreate new user automatically via functions.php in WordPressWordpress automatic head tagRemove and add actions in Wordpress using functions.phpAdd “vc_add_shortcode_param” in WordPress functions.phpWhy post.php and functions.php of a WordPress site are automatically emptied?add js to <head> of specific page via functions.php in wordpress

What does grep -v "grep" mean and do?

Generate and graph the Recamán Sequence

Automatically convert a number to use the correct SI unit prefix

Skipping over failed imports until they are needed (if ever)

What is "oversubscription" in Networking?

I hit a pipe with a mower and now it won't turn

How to expand abbrevs without hitting another extra key?

Different budgets within roommate group

Can a Federation colony become a member world?

In the context of a differentiator circuit, what is a “current-sensing resistor”?

Does Anosov geodesic flow imply asphericity?

Can you sign using a digital signature itself?

Attempt to de-reference a null object: list initialization

Meaning of もてり and use of が

cannot execute script while its permission is 'x'

Why isn’t the tax system continuous rather than bracketed?

Is there a way for presidents to legally extend their terms beyond the maximum of four years?

When are digital copies of Switch games made available to play?

One folder two different locations on ubuntu 18.04

Why don't all electrons contribute to total orbital angular momentum of an atom?

Most elegant way to write a one shot IF

Getting geometries of hurricane's 'cone of uncertainty' using shapely?

Is it allowed to spend a night in the first entry country before moving to the main destination?

Way to find when system health file is rolling over



How to automatically add IDs to headings using functions.php in Wordpress


Can I install/update WordPress plugins without providing FTP access?How to add a PHP page to WordPress?Wordpress capabilities and current_user_can() in functions.phpCorrect file permissions for WordPressCreate new user automatically via functions.php in WordPressWordpress automatic head tagRemove and add actions in Wordpress using functions.phpAdd “vc_add_shortcode_param” in WordPress functions.phpWhy post.php and functions.php of a WordPress site are automatically emptied?add js to <head> of specific page via functions.php in wordpress






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I am wondering how I could implement unique IDs for each heading element in a post (excluding pages) in Wordpress. That is, if two headings are identical, they should get different IDs. The IDs should also be descriptive. A dashed version of the actual title text is great.



I have found this code online:



// This function adds nice anchor with id attribute to our h2 tags for reference
// @link: http://www.w3.org/TR/html4/struct/links.html#h-12.2.3

function anchor_content_h2($content)

// Pattern that we want to match
$pattern = '/<h2>(.*?)</h2>/';

// now run the pattern and callback function on content
// and process it through a function that replaces the title with an id
$content = preg_replace_callback($pattern, function ($matches)
$title = $matches[1];
$slug = sanitize_title_with_dashes($title);
return '<h2 id="' . $slug . '">' . $title . '</h2>';
, $content);
return $content;


add_filter('the_content', 'anchor_content_h2');


My concern here is that two identical headings will get the same ID. It also only works for H2-elements. Is there a better way to do what I want, or is this kind of thing generally not smart to implement?










share|improve this question




























    1















    I am wondering how I could implement unique IDs for each heading element in a post (excluding pages) in Wordpress. That is, if two headings are identical, they should get different IDs. The IDs should also be descriptive. A dashed version of the actual title text is great.



    I have found this code online:



    // This function adds nice anchor with id attribute to our h2 tags for reference
    // @link: http://www.w3.org/TR/html4/struct/links.html#h-12.2.3

    function anchor_content_h2($content)

    // Pattern that we want to match
    $pattern = '/<h2>(.*?)</h2>/';

    // now run the pattern and callback function on content
    // and process it through a function that replaces the title with an id
    $content = preg_replace_callback($pattern, function ($matches)
    $title = $matches[1];
    $slug = sanitize_title_with_dashes($title);
    return '<h2 id="' . $slug . '">' . $title . '</h2>';
    , $content);
    return $content;


    add_filter('the_content', 'anchor_content_h2');


    My concern here is that two identical headings will get the same ID. It also only works for H2-elements. Is there a better way to do what I want, or is this kind of thing generally not smart to implement?










    share|improve this question
























      1












      1








      1








      I am wondering how I could implement unique IDs for each heading element in a post (excluding pages) in Wordpress. That is, if two headings are identical, they should get different IDs. The IDs should also be descriptive. A dashed version of the actual title text is great.



      I have found this code online:



      // This function adds nice anchor with id attribute to our h2 tags for reference
      // @link: http://www.w3.org/TR/html4/struct/links.html#h-12.2.3

      function anchor_content_h2($content)

      // Pattern that we want to match
      $pattern = '/<h2>(.*?)</h2>/';

      // now run the pattern and callback function on content
      // and process it through a function that replaces the title with an id
      $content = preg_replace_callback($pattern, function ($matches)
      $title = $matches[1];
      $slug = sanitize_title_with_dashes($title);
      return '<h2 id="' . $slug . '">' . $title . '</h2>';
      , $content);
      return $content;


      add_filter('the_content', 'anchor_content_h2');


      My concern here is that two identical headings will get the same ID. It also only works for H2-elements. Is there a better way to do what I want, or is this kind of thing generally not smart to implement?










      share|improve this question














      I am wondering how I could implement unique IDs for each heading element in a post (excluding pages) in Wordpress. That is, if two headings are identical, they should get different IDs. The IDs should also be descriptive. A dashed version of the actual title text is great.



      I have found this code online:



      // This function adds nice anchor with id attribute to our h2 tags for reference
      // @link: http://www.w3.org/TR/html4/struct/links.html#h-12.2.3

      function anchor_content_h2($content)

      // Pattern that we want to match
      $pattern = '/<h2>(.*?)</h2>/';

      // now run the pattern and callback function on content
      // and process it through a function that replaces the title with an id
      $content = preg_replace_callback($pattern, function ($matches)
      $title = $matches[1];
      $slug = sanitize_title_with_dashes($title);
      return '<h2 id="' . $slug . '">' . $title . '</h2>';
      , $content);
      return $content;


      add_filter('the_content', 'anchor_content_h2');


      My concern here is that two identical headings will get the same ID. It also only works for H2-elements. Is there a better way to do what I want, or is this kind of thing generally not smart to implement?







      wordpress






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 25 at 12:34









      SpacePilotSpacePilot

      447 bronze badges




      447 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          1














          There are plenty of ways to do this but if you use the post_name, you'll end up with a unique, dashed and descriptive value.
          https://codex.wordpress.org/Class_Reference/WP_Post#Member_Variables_of_WP_Post



          If it were me, I would likely throw the code below into the respective template file.



          the_title( '<h2 class="' . get_post_field( 'post_name', get_post() ) . '">', '</h2>' );


          EDIT - So each h2 isn't tied to a post? You could just append $slug with a unique ID.



          $slug = sanitize_title_with_dashes($title) . '-' . uniqid();





          share|improve this answer

























          • I am not sure that this is what I want to do. My goal is to have every H2-heading in a post have it's own unique and descriptive ID. I don't see how this will help in doing that? What am I missing here?

            – SpacePilot
            Mar 25 at 14:48











          • Ah, to have the mind of a programmer. Thanks, that will work. Feeling kind of stupid, but I'll go for it :)

            – SpacePilot
            Mar 25 at 15:29










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55337918%2fhow-to-automatically-add-ids-to-headings-using-functions-php-in-wordpress%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          There are plenty of ways to do this but if you use the post_name, you'll end up with a unique, dashed and descriptive value.
          https://codex.wordpress.org/Class_Reference/WP_Post#Member_Variables_of_WP_Post



          If it were me, I would likely throw the code below into the respective template file.



          the_title( '<h2 class="' . get_post_field( 'post_name', get_post() ) . '">', '</h2>' );


          EDIT - So each h2 isn't tied to a post? You could just append $slug with a unique ID.



          $slug = sanitize_title_with_dashes($title) . '-' . uniqid();





          share|improve this answer

























          • I am not sure that this is what I want to do. My goal is to have every H2-heading in a post have it's own unique and descriptive ID. I don't see how this will help in doing that? What am I missing here?

            – SpacePilot
            Mar 25 at 14:48











          • Ah, to have the mind of a programmer. Thanks, that will work. Feeling kind of stupid, but I'll go for it :)

            – SpacePilot
            Mar 25 at 15:29















          1














          There are plenty of ways to do this but if you use the post_name, you'll end up with a unique, dashed and descriptive value.
          https://codex.wordpress.org/Class_Reference/WP_Post#Member_Variables_of_WP_Post



          If it were me, I would likely throw the code below into the respective template file.



          the_title( '<h2 class="' . get_post_field( 'post_name', get_post() ) . '">', '</h2>' );


          EDIT - So each h2 isn't tied to a post? You could just append $slug with a unique ID.



          $slug = sanitize_title_with_dashes($title) . '-' . uniqid();





          share|improve this answer

























          • I am not sure that this is what I want to do. My goal is to have every H2-heading in a post have it's own unique and descriptive ID. I don't see how this will help in doing that? What am I missing here?

            – SpacePilot
            Mar 25 at 14:48











          • Ah, to have the mind of a programmer. Thanks, that will work. Feeling kind of stupid, but I'll go for it :)

            – SpacePilot
            Mar 25 at 15:29













          1












          1








          1







          There are plenty of ways to do this but if you use the post_name, you'll end up with a unique, dashed and descriptive value.
          https://codex.wordpress.org/Class_Reference/WP_Post#Member_Variables_of_WP_Post



          If it were me, I would likely throw the code below into the respective template file.



          the_title( '<h2 class="' . get_post_field( 'post_name', get_post() ) . '">', '</h2>' );


          EDIT - So each h2 isn't tied to a post? You could just append $slug with a unique ID.



          $slug = sanitize_title_with_dashes($title) . '-' . uniqid();





          share|improve this answer















          There are plenty of ways to do this but if you use the post_name, you'll end up with a unique, dashed and descriptive value.
          https://codex.wordpress.org/Class_Reference/WP_Post#Member_Variables_of_WP_Post



          If it were me, I would likely throw the code below into the respective template file.



          the_title( '<h2 class="' . get_post_field( 'post_name', get_post() ) . '">', '</h2>' );


          EDIT - So each h2 isn't tied to a post? You could just append $slug with a unique ID.



          $slug = sanitize_title_with_dashes($title) . '-' . uniqid();






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 25 at 15:04

























          answered Mar 25 at 14:06









          epierpontepierpont

          1568 bronze badges




          1568 bronze badges












          • I am not sure that this is what I want to do. My goal is to have every H2-heading in a post have it's own unique and descriptive ID. I don't see how this will help in doing that? What am I missing here?

            – SpacePilot
            Mar 25 at 14:48











          • Ah, to have the mind of a programmer. Thanks, that will work. Feeling kind of stupid, but I'll go for it :)

            – SpacePilot
            Mar 25 at 15:29

















          • I am not sure that this is what I want to do. My goal is to have every H2-heading in a post have it's own unique and descriptive ID. I don't see how this will help in doing that? What am I missing here?

            – SpacePilot
            Mar 25 at 14:48











          • Ah, to have the mind of a programmer. Thanks, that will work. Feeling kind of stupid, but I'll go for it :)

            – SpacePilot
            Mar 25 at 15:29
















          I am not sure that this is what I want to do. My goal is to have every H2-heading in a post have it's own unique and descriptive ID. I don't see how this will help in doing that? What am I missing here?

          – SpacePilot
          Mar 25 at 14:48





          I am not sure that this is what I want to do. My goal is to have every H2-heading in a post have it's own unique and descriptive ID. I don't see how this will help in doing that? What am I missing here?

          – SpacePilot
          Mar 25 at 14:48













          Ah, to have the mind of a programmer. Thanks, that will work. Feeling kind of stupid, but I'll go for it :)

          – SpacePilot
          Mar 25 at 15:29





          Ah, to have the mind of a programmer. Thanks, that will work. Feeling kind of stupid, but I'll go for it :)

          – SpacePilot
          Mar 25 at 15:29








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.




















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55337918%2fhow-to-automatically-add-ids-to-headings-using-functions-php-in-wordpress%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현