WordPress slug 用於訪問 WordPress 上的頁面和文章。例如,如果我有一個標題為 “你好” 的文章,它的標籤就是”/hello”。WordPress 這樣做是為了通過人類可讀的 URL 來幫助搜尋引擎優化。在使用 WordPress 構建網站時,這一概念非常重要,因為您可能希望使用正確的 slug 連結到頁面。
請注意,本指南假定您懂一些 PHP,並且正在使用主題或外掛開發自定義 WordPress 功能。
在這篇短文中,我們將介紹幾種在 WordPress 中使用 PHP 獲取頁面 slug 的方法。
在 WordPress 中使用 get_post_field 獲取頁面標籤
在 WordPress 後臺,slug 實際上稱為 “post_name”。可以使用 get_post_field()
函式訪問這個變數。這是在 WordPress 中獲取 slug 的最佳方法,因為它可以在主查詢或迴圈中使用,以獲取多個 WordPress slug。
<?php
// Get the current post or page's slug
$slug = get_post_field( 'post_name', get_post() );
echo $slug;
// Get slug for a post or page by ID
$post_id = 1;
echo get_post_field( 'post_name', $post_id );
<?php
// Get the current post or page's slug
$slug = get_post_field( 'post_name', get_post() );
echo $slug;
// Get slug for a post or page by ID
$post_id = 1;
echo get_post_field( 'post_name', $post_id );
<?php // Get the current post or page's slug $slug = get_post_field( 'post_name', get_post() ); echo $slug; // Get slug for a post or page by ID $post_id = 1; echo get_post_field( 'post_name', $post_id );
在上面的示例中,我展示瞭如何在 WordPress 中獲取當前頁面的標題。此外,我還新增了一個示例,允許你通過文章 ID 獲取任何 WordPress 頁面的標籤。
在 WordPress 中使用全域性 $post 獲取當前頁面 Slug
WordPress 中名為 $post 的全域性物件包含當前文章的當前文章物件。當你想獲取當前頁面或文章的標題時,這個方法非常有用。
<?php
global $post;
$slug = $post->post_name;
<?php
global $post;
$slug = $post->post_name;
<?php global $post; $slug = $post->post_name;
現在你對 WordPress 有了一些瞭解!
希望本指南對你有所幫助,如果你有關於 WordPress 開發的問題,請在下面的評論中告訴我。
評論留言