Using WordPress ‘permalink_anchor()’ PHP function

The permalink_anchor() WordPress PHP function displays the permalink anchor for the current post.

Usage

permalink_anchor( $mode )

Input:

permalink_anchor('title');

Output:

<a id="your-post-title"></a>

Parameters

  • $mode (string) Optional. Permalink mode. Accepts ‘title’ or ‘id’. Default ‘id’.

More information

See WordPress Developer Resources: permalink_anchor

Examples

Display anchor with post title as ID

This example will display the permalink anchor next to a post’s title using the post title for the id attribute.

<h3>
  <?php permalink_anchor('title'); ?>
  <?php the_title(); ?>
</h3>

Display anchor with post ID as ID

This example will display the permalink anchor next to a post’s title using the post ID for the id attribute.

<h3>
  <?php permalink_anchor('id'); ?>
  <?php the_title(); ?>
</h3>

This example will use the_permalink() function to create a link with the anchor ID generated by permalink_anchor().

<a href="<?php the_permalink(); ?>#<?php permalink_anchor('id'); ?>">
  <?php the_title(); ?>
</a>

Adding custom attributes to the anchor

This example will add a custom class and data attribute to the anchor generated by permalink_anchor().

<a id="<?php permalink_anchor('title'); ?>" class="custom-anchor" data-toggle="tooltip">
  <?php the_title(); ?>
</a>

This example will display a list of post titles with their respective permalink anchors in a loop.

<?php if ( have_posts() ) : ?>
  <ul>
    <?php while ( have_posts() ) : the_post(); ?>
      <li>
        <a href="<?php the_permalink(); ?>#<?php permalink_anchor('id'); ?>">
          <?php the_title(); ?>
        </a>
      </li>
    <?php endwhile; ?>
  </ul>
<?php endif; ?>

Tagged in

Leave a Comment

Your email address will not be published. Required fields are marked *