Function and usage of get_archives_link() in wordpress

Question

Answers ( 1 )

    0
    2024-01-06T12:57:31+00:00

    The get_archives_link() function in WordPress is a versatile tool used for creating archive links in various formats. This function is particularly useful for developers looking to add archive links to their WordPress themes or plugins. Here's a detailed explanation of the function and its usage:

    Function:

    • Purpose: Retrieves archive link content based on predefined or custom code.

    Description:

    • This function supports four different formats: link, option, html, and custom.
    • link Format: Uses the <link> HTML element, suitable for the head element of a webpage. The before and after parameters are not applicable here. The text parameter is used to describe the link.
    • option Format: Utilizes the <option> HTML element, appropriate for use within a <select> element. The URL is set as the value, and before and after parameters are placed around the text description.
    • html Format: This is the default format. It uses the <li> HTML element, making it suitable for list elements (<ol> or <ul>). The before parameter appears before the link, and the after parameter follows the closing link tag.
    • Custom Format: Allows for a custom arrangement, where the before parameter is placed before the link (<a> HTML element), and the after parameter follows the closing link tag. If the format is not one of the above three (link, option, html), this custom format is assumed.

    Parameters:

    • $url (string, required): URL to the archive.
    • $text (string, required): Text description of the archive.
    • $format (string, optional): Can be 'link', 'option', 'html', or custom. The default is 'html'.
    • $before (string, optional): Content to prepend to the description. Default is an empty string.
    • $after (string, optional): Content to append to the description. Default is an empty string.
    • $selected (bool, optional): Set to true if the current page is the selected archive page. Default is false.

    Return:

    • Returns a string containing the HTML link content for the archive.

    Sample Usage:

    <?php
    // Example of using get_archives_link with HTML format
    echo get_archives_link('http://example.com/archive/', 'Archive Title', 'html', '<span class="pre-link">', '</span>');
    
    // Example of using get_archives_link with OPTION format in a dropdown
    echo '<select>';
    echo get_archives_link('http://example.com/archive/', 'Archive Title', 'option', '', '', true);
    echo '</select>';
    ?>
    

    In these examples, the function is used to generate an HTML list item and an option within a select dropdown, respectively, linking to an archive page. The before, after, and selected parameters are adjusted as per the requirement of the format.

Leave an answer