PHP를 사용하여 WordPress에서 페이지 제목 설정
저는 이 질문이 수천 번 제기되었다는 것을 알고 있지만, 저는 이러한 해결책을 여러 번 시도해 보았지만 아무런 성과가 없었습니다.
시도된 솔루션 등 (템플릿 페이지에 추가)
add_filter('the_title','callback_to_set_the_title');
add_filter('wp_title', 'callback_to_set_the_title');
global $title;
$title = 'My Custom Title';
add_filter( 'pre_get_document_title', 'callback_to_set_the_title' );
add_filter( 'document_title_parts', 'callback_to_set_the_title' );
작업 목록 페이지의 커스텀템플릿을 가지고 있는 시나리오입니다.이 페이지에는 다시 쓰는 URL이 있습니다.domain.com/about/careers/search/job?slug=whatever로.domain.com/about/careers/search/job/whatever- slug는 Redis에서 제가 사용하고 싶은 직함을 포함한 구인 리스트의 모든 정보를 포함하는 엔트리를 취득하는 데 사용됩니다.
URL을 다시 쓰는 방법은 다음과 같습니다(functions.php에서).
function job_listing_url_rewrite() {
global $wp_rewrite;
add_rewrite_tag('%slug%', '([^&]+)');
add_rewrite_rule('^about/careers/search/job/([a-zA-Z0-9-_]+)/?', 'index.php?page_id=6633&slug=$matches[1]', 'top');
$wp_rewrite->flush_rules(true);
}
add_action('init', 'job_listing_url_rewrite', 10, 0);
제 템플릿으로 조사를 좀 해봤어요.제 템플릿은 get_header()를 호출하여 헤드와 같은 HTML 태그를 인쇄합니다.
제목을 대체하기 위해 해당 함수를 호출하기 직전에 출력 버퍼링을 시작하고 나중에 가져옵니다.
그 후 제목을 preg_replace()로 쉽게 바꿀 수 있습니다.
ob_start();
get_header();
$header = ob_get_clean();
$header = preg_replace('#<title>(.*?)<\/title>#', '<title>TEST</title>', $header);
echo $header;
템플릿에서 wp_title을 변경하는 로직이 너무 늦게 실행되고 있는 것 같습니다.
대부분의 경우,wp_title는 헤더 파일에서 호출됩니다.이 파일은 사용자의 논리로 템플릿에 액세스하기 전에 처리됩니다.
다음 항목을 에 추가하는 경우functions.phpWordPress가 원하는 대로 제목을 설정합니다.
<?php
// functions.php
function change_title_if_job_posting($query) {
$slug = $query->query->get('slug');
// The URL is a match, and your function above set the value of $slug on the query
if ('' !== $slug) {
/**
* Use the value of $slug here and reimplement whatever logic is
* currently in your template to get the data from Redis.
*
* For this example, we'll pretend it is set to var $data. :)
*/
$data = 'whatever-the-result-of-the-redis-req-and-subsequent-processing-is';
/**
* Changes the contents of the <title></title> tag.
*
* Break this out from a closure to it's own function
* if you want to also alter the get_the_title() function
* without duplicating logic!
*/
add_filter('wp_title', function($title) use ($data) {
return $data;
});
}
}
// This is the crux of it – we want to try hooking our function to the wp_title
// filter as soon as your `slug` variable is set to the WP_Query; not all the way down in the template.
add_action('parse_query', 'change_title_if_job_posting');
이렇게 하면 주(Main)가 필터에 기능을 추가할 수 있습니다.WP_Query에는 「」라고 하는 변수가 설정되어 있습니다.slug이는 위에서 설명한 논리와 일치해야 합니다.
이미 사용하신 것으로 알고 있습니다.wp_title필터는 다음과 같이 해 주세요.
function job_listing_title_override ($title, $sep){
if (is_page_template('templates/job-listing.php')) {
$title = 'Job Listing Page '.$sep.' '. get_bloginfo( 'name', 'display' );
}
return $title;
}
add_filter( 'wp_title', 'job_listing_title_override', 10, 2 );
저도 같은 문제를 겪고 있어요.
wp 소스 코드 디버깅 후.더 좋은 해결책을 찾았어요.wp_get_document_title() 코멘트에 따라 wp 4.4.0 또는 abouve에서 이러한 필터를 사용할 수 있습니다.
/** Replace document title **/
function product_page_replace_title( $empty ) {
// New page title.
return 'New Title';
}
add_filter( 'pre_get_document_title', 'product_page_replace_title' );
add_filter( 'document_title', 'mod_browser_tab_title');
function mod_browser_tab_title( $title )
{
$title = 'Custom title';
return $title;
}
질문이나 코멘트로부터, 커스텀 투고 타입이 아니고, 커스텀 페이지 템플릿(아마도 자테마나 page.php 베이스)을 사용하고 있는 것 같습니다.
마찬가지로 WordPress 데이터베이스가 아닌 사용자 지정 페이지를 사용하여 요청된 콘텐츠(제목 생성, Google 전용 메타 태그 포함)를 표시합니다(예: http://travelchimps.com/country/france(?cc=프랑스 제목 "France: travel advisory") 및 travelchimps.com/country/cuba/health(?cc=fress&spg= "cuba travel info:").건강')
질문 중에 뭔가 부족한 점이 있을 수 있지만 커스텀 페이지 템플릿을 사용하면 페이지 제목에 필터/WordPress 기능이 필요하지 않습니다.직접 변수를 사용할 수 있습니다.작업 목록 제목의 의미 있는 인덱스 페이지가 필요한 경우 Redis에서 직접 생성할 수도 있습니다.
파일 기능php:
// Allow WordPress to store querystring attributes for use in our pages
function my_query_vars_filter($vars) {
# Jobs
$vars[] .= 'slug';
# More variables
}
add_filter('query_vars', 'my_query_vars_filter');
커스텀 페이지 템플릿:
<?php /* Template Name: JobQryPage*/
// *** Get data (I don't know Redis) ***
$redisKey = get_query_var('slug'); // Validate as reqd
// Use $redisKey to select $jobInfo from Redis
$PAGE_TITLE = $jobInfo['title']; // Or whatever
// Maybe some meta tag stuff
// Code copied from page.php ....
// Maybe replace "get_header();" with modified header.php code
...
// ** IN THE HTML FOR THE TITLE: CHANGE say "the_title();" to "echo $PAGE_TITLE;" **
// e.g. ?>
<h2 class="post-title"><?php echo $PAGE_TITLE; ?></h2>
...
<div class="post-content">
<?php // ** delete "< ?php the_content(); ? > or other code used to display page editor content
// and replace with your code to render your Redis $jobInfo ** ?>
</div>
<!-- remainder of page.php code -->
사용자 정의 페이지 템플릿의 단점은 "테마 고유"하지만 새 테마의 페이지를 사용하여 새(같은 이름 템플릿)을 작성하는 것은 간단한 문제입니다.php를 기반으로 이전 템플릿에서 코드를 복사합니다.
나도 아이디보다는 이름을 쓰는 게 더 좋아.그래서 페이지 에디터를 사용하여 "CountryQryPage"를 템플릿으로 선택한 빈 페이지(나라의 제목과 슬래그)를 저장했습니다.또한 사이트 기능 플러그인에 다음과 같이 되어 있습니다.
function tc_rewrite_rules($rules) {
global $wp_rewrite;
$tc_rule = array(
'country/(.+)/?' => 'index.php?pagename=' . 'country' . '&cc=$matches[1]'
);
return array_merge($tc_rule, $rules);
}
add_filter('page_rewrite_rules', 'tc_rewrite_rules');
언급URL : https://stackoverflow.com/questions/51309154/set-page-title-in-wordpress-with-php
'programing' 카테고리의 다른 글
| 리액트 라우터에서 수동으로 링크를 호출하는 방법 (0) | 2023.03.16 |
|---|---|
| JSON 개체를 TypeScript 클래스에 캐스트하려면 어떻게 해야 합니까? (0) | 2023.03.16 |
| AngularJs ng트리거 onblur 변경 (0) | 2023.03.16 |
| MongoDB에 있는 모든 문서의 필드 이름을 변경하려면 어떻게 해야 합니까? (0) | 2023.03.16 |
| ASP.NET MVC 파라미터로서 JSON 객체를 View에서 컨트롤러로 전달하는 방법 (0) | 2023.03.16 |