user3550879 user3550879 - 6 months ago 10
PHP Question

Print text and icon link to adjacent posts on Wordpress

I have the following code in my Wordpress which makes my back/next post navigation:

<nav role="navigation" id="<?php echo esc_attr( $nav_id ); ?>" class="<?php echo $nav_class; ?>">

<?php if ( is_single() ) : // navigation links for single posts ?>

<?php next_post_link( '<div class="nav-next">%link</div>', '<span class="fa fa-chevron-right"></span>' . _x( '', 'Previous post link', 'bnNav' ) ); ?>
<?php previous_post_link( '<div class="nav-previous">%link</div>', _x( '', 'Next post link', 'bnNav' ). '<span class="fa fa-chevron-left"></span>'); ?>

...


This puts a chevron pointing right and left linked to the back and next posts.

I want the text of the link to show as well as the chevron but not sure how to adjust my code.

Answer

Function _x() is for translation in Wordpress waiting as parameters:

$text (string) (Required) Text to translate.

$context (string)(Required) Context information for the translators.

$domain (string) (Optional) Text domain. Unique identifier for retrieving translated strings. Default value: 'default'

In order to make your text appear just fill the first parameter to set the text you want to show, you will be able to translate it afterwards aswell if you want to. As an example:

<nav role="navigation" id="<?php echo esc_attr( $nav_id ); ?>" class="<?php echo $nav_class; ?>">

    <?php if ( is_single() ) : // navigation links for single posts ?>

        <?php next_post_link( '<div class="nav-next">%link</div>', '<span class="fa fa-chevron-right"></span>' . _x( get_previous_post()->post_title;, 'Previous post link', 'bnNav' ) ); ?>
        <?php previous_post_link( '<div class="nav-previous">%link</div>', _x( get_next_post()->post_title;, 'Next post link', 'bnNav' ). '<span class="fa fa-chevron-left"></span>'); ?> 

For more information check the official reference for _x() and next_post_link(). I you want to get the name of the posts you are linking to, you can do so using get_next_post() and get_previous_post() functions.

Hope this helps you.

Comments