wp_redirect( string $location, int $status = 302, string $x_redirect_by = 'WordPress' )
ریدایرکت کردن (یا تغییر مسیر دادن) کاربر به صفحه و لینک جدید، یکی از چیزهاییست که در مواقع مختلف از جمله بحث سئو، به شدت مورد نیاز است!
در حالت ساده به کمک تابع header خود PHP میتوان کاربر را به صفحه دیگری ریدارکت کرد؛ اما استفاده از این تابع کمی پیچیده است. در ثانی، وردپرس برای اینکه بتواند قبل از ریدایرکت، فیلترهایی را بررسی کند، تابع wp_redirect را ایجاد کرده است تا با استفاده از آن ریدایرکت را انجام دهد. البته این تابع نیز از همان header استفاده میکند؛ با این تفاوت که قبل از ریدایرکت، مواردی را نیز انجام میدهد.
لازم به ذکر است که این تابع، به صورت خودکار دستورر exit را اجرا نمیکند و همواره باید بعد از آن، exit را نوشت:
wp_redirect( $url ); exit;
این انتقال نیز ممکن است توسط فیلترهایی که نوشته شده است اتفاق نیفتند! بنابراین بایستی به صورت زیر، exit را در صورت موفق بودن ریدایرکت نوشت:
if ( wp_redirect( $url ) ) { exit; }
ورودیها
- $location (از نوع string):
لینک مورد نظر جهت ریدایرکت شدن به آن - $status (از نوع int) (اختیاری، مقدار پیشفرض = 302):
کد وضعیت ریدایرکت یا HTTP response status! وضعیت 302 یعنی انتقال به صورت موقت است. - $x_redirect_by (از نوع string) (اختیاری، مقدار پیشفرض = ‘WordPress’)
اپلیکیشنی که این عمل ریدایرکت را انجام میدهد.
خروجی
(از نوع bool): در صورت موفق بودن ریدایرکت، true برمیگردد و در غیر اینصورت، false!
سورس تابع اصلی
فایل: wp-includes/pluggable.php
function wp_redirect( $location, $status = 302, $x_redirect_by = 'WordPress' ) { global $is_IIS; /** * Filters the redirect location. * * @since 2.1.0 * * @param string $location The path or URL to redirect to. * @param int $status The HTTP response status code to use. */ $location = apply_filters( 'wp_redirect', $location, $status ); /** * Filters the redirect HTTP response status code to use. * * @since 2.3.0 * * @param int $status The HTTP response status code to use. * @param string $location The path or URL to redirect to. */ $status = apply_filters( 'wp_redirect_status', $status, $location ); if ( ! $location ) { return false; } $location = wp_sanitize_redirect( $location ); if ( ! $is_IIS && PHP_SAPI != 'cgi-fcgi' ) { status_header( $status ); // This causes problems on IIS and some FastCGI setups } /** * Filters the X-Redirect-By header. * * Allows applications to identify themselves when they're doing a redirect. * * @since 5.1.0 * * @param string $x_redirect_by The application doing the redirect. * @param int $status Status code to use. * @param string $location The path to redirect to. */ $x_redirect_by = apply_filters( 'x_redirect_by', $x_redirect_by, $status, $location ); if ( is_string( $x_redirect_by ) ) { header( "X-Redirect-By: $x_redirect_by" ); } header( "Location: $location", true, $status ); return true; }
همانطور که در سورس نیز مشاهده میشود، هوک فیلترهای wp_redirect و wp_redirect_status، قبل از ریدایرکت توسط خود وردپرس ببررسی شدهاند.
نظرات ثبت شده بدون دیدگاه