Function and usage of get_pagenum_link() in wordpress

Question

Answers ( 1 )

    0
    2024-01-07T13:54:19+00:00

    The get_pagenum_link() function in WordPress is used to retrieve the link URL for a specific page number. This function is particularly useful in scenarios where you need to create pagination links on your website.

    Function Prototype

    get_pagenum_link( int $pagenum = 1, bool $escape = true ): string
    

    Parameters

    1. $pagenum (int, optional): This parameter specifies the page number for which the link is to be generated. It's an integer value. The default value is 1, which means if you don't specify this parameter, the function will return the link for the first page.

    2. $escape (bool, optional): This parameter determines whether the URL should be escaped for display or not. If set to true, the URL is escaped using the esc_url() function, which is the recommended way to ensure the URL is safe for display. If set to false, the URL is prepared with sanitize_url(). The default value is true.

    Return Value

    • Type: string
    • The function returns the link URL for the given page number.

    Sample Usage

    Let's look at some examples of how to use get_pagenum_link():

    Example 1: Basic Usage

    // Get the link for page number 2
    $page2_link = get_pagenum_link(2);
    

    In this example, the function will generate the link for page number 2.

    Example 2: Non-Escaped URL

    // Get the non-escaped link for page number 3
    $page3_link = get_pagenum_link(3, false);
    

    Here, the function generates a link for page number 3 without escaping the URL.

    Practical Application

    This function is typically used when creating custom pagination for list pages, like post archives or search results. It allows developers to easily generate URLs for different pages without manually constructing the query strings. This is especially helpful in maintaining clean and SEO-friendly URLs for paginated content.

Leave an answer