development

WordPress에서 현재 페이지 이름을 얻는 방법은 무엇입니까?

big-blog 2020. 6. 5. 08:06
반응형

WordPress에서 현재 페이지 이름을 얻는 방법은 무엇입니까?


WordPress 테마에서 현재 페이지 이름을 검색하는 데 사용할 수있는 PHP 코드는 무엇입니까?

내가 지금까지 (본 모든 솔루션 the_title(), get_page()->post_name, get_post(), 등) 후 항목을 포함하는 페이지에 대한 작업을하지 않습니다. 그들은 모두 최신 블로그 항목의 이름을 반환합니다.

다른 방법으로 말하면, "My News"라는 이름으로 WordPress에 페이지가 생성되었다고 가정하십시오. 이 페이지는 "게시물 페이지"로 설정됩니다. 페이지에 몇 개의 게시물을 추가하십시오. 이제 최신 게시물 이름 대신 "my-news"문자열을 검색하기 위해 어떤 API를 사용할 수 있습니까?

편집하다:

작동하는 것처럼 보이는 다음 변수를 찾았습니다.

$wp_query->queried_object->post_name

이것은 실제로 페이지 이름 (슬러그)의 URL 친화적 인 버전이며, 내가 찾던 것입니다. 기본 템플릿 (20 개)으로 테스트했습니다. 아래의 두 변수가 왜 내 사이트에서 작동하지 않는지 잘 모르겠습니다. print_r()주셔서 감사합니다 .

자,이 정보가 왜 그렇게 깊이 숨겨져 있습니까?


WP 전역 변수 $pagename를 사용할 수 있어야합니다. 방금 지정한 것과 동일한 설정으로 시도했습니다.

$pagename는 함수 내에서 wp-includes / theme.php 파일에 정의되어 있으며 get_page_template()페이지 테마 파일이 구문 분석되기 전에 호출되므로 페이지의 템플리트 내부에서 언제든지 사용할 수 있습니다.

편집하다:

  • 문서화 된 것으로 보이지는 않지만 $pagenamevar은 영구 링크를 사용하는 경우에만 설정됩니다. 나는 이것을 사용하지 않으면 WP가 페이지 슬러그가 필요하지 않으므로 설정하지 않기 때문입니다.

  • $pagename 페이지를 정적 프론트 페이지로 사용하는 경우에는 설정되지 않습니다.

  • 이것은 /wp-includes/theme.php의 코드이며, $pagename설정할 수 없을 때 지적한 솔루션을 사용합니다 .

    $pagename = get_query_var('pagename');  
    if ( !$pagename && $id > 0 ) {  
        // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object  
        $post = $wp_query->get_queried_object();  
        $pagename = $post->post_name;  
    }
    

페이지의 슬러그 이름을 얻는 방법

$slug = basename(get_permalink());

루프 전에 페이지 제목을 가져와야합니다.

$page_title = $wp_query->post->post_title;

참조 확인 : http://codex.wordpress.org/Function_Reference/WP_Query#Properties를 .

print_r($wp_query)

루프 전에 $ wp_query 객체의 모든 값을 봅니다.


<?php wp_title(''); ?>

이것은 올바르게 이해하면 게시물 항목이있는 페이지에서 페이지 이름을 얻고 싶습니까?


전역 변수 $ post를 사용하여 현재 페이지, 게시물 또는 사용자 정의 게시물 유형을 얻을 수 있습니다.

echo $post->post_title

참고 : 함수 나 클래스 global $post;에서는 $ post를 사용하기 전에 지정해야합니다 .

페이지에 루프가있는 경우 wp_reset_postdata();$ post를 표시되는 기본 항목 (페이지)으로 다시 설정하도록 각 루프를 종료해야합니다 .

'post_title'변수는 메뉴 항목 및 미디어 첨부 파일을 포함한 모든 사용자 정의 루프 / 쿼리에도 사용할 수 있습니다. WordPress의 모든 내용은 '포스트'입니다.


당신이 당신의 functions.php 파일 내에서 현재 페이지에 액세스하기 위해 찾고 있다면 (그래서, 전에 루프 전에 $post전에 채워집니다 $wp_query정말 선택의 여지가 있지만, 서버 변수 자체에 액세스 할 수 ... 등, 초기화) 및 쿼리 문자열에서 요청 된 페이지를 추출하십시오.

$page_slug = trim( $_SERVER["REQUEST_URI"] , '/' )

이 솔루션은 "멍청한"솔루션입니다. 예를 들어 슬러그 'coming-soon'이있는 페이지도 p=6입니다. 그리고 permalink 설정이 pagename(어쨌든 있어야합니다!)로 설정되어 있다고 가정합니다 .

그러나 통제 된 시나리오가있는 경우 유용한 작은 방법이 될 수 있습니다. 로그인하지 않은 방문자를 "출시 예정"페이지로 리디렉션하려는 상황에서이를 사용하고 있습니다. 그러나 나는 그것들을 두려운 "리디렉션 루프"에 넣지 않도록해야하므로이 규칙에서 "출시 예정"페이지를 제외시켜야합니다.

global $pagenow;
if (
        ! is_admin() &&
        'wp-login.php' != $pagenow &&
        'coming-soon' != trim( $_SERVER["REQUEST_URI"] , '/' ) &&
        ! is_user_logged_in()
){
   wp_safe_redirect( 'coming-soon' );
}

Roots starter 테마는 현재 페이지 제목을 얻을 수있는 환상적인 기능을 가지고 있으며 모든 해킹 가능하며 모든베이스를 다루며 wp_title 후크와 함께 쉽게 사용할 수 있다고 생각합니다

https://github.com/roots/roots/blob/6.5.0/lib/titles.php .

/**
 * Page titles
 */
function roots_title() {
  if (is_home()) {
    if (get_option('page_for_posts', true)) {
      echo get_the_title(get_option('page_for_posts', true));
    } else {
      _e('Latest Posts', 'roots');
    }
  } elseif (is_archive()) {
    $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
    if ($term) {
      echo $term->name;
    } elseif (is_post_type_archive()) {
      echo get_queried_object()->labels->name;
    } elseif (is_day()) {
      printf(__('Daily Archives: %s', 'roots'), get_the_date());
    } elseif (is_month()) {
      printf(__('Monthly Archives: %s', 'roots'), get_the_date('F Y'));
    } elseif (is_year()) {
      printf(__('Yearly Archives: %s', 'roots'), get_the_date('Y'));
    } elseif (is_author()) {
      $author = get_queried_object();
      printf(__('Author Archives: %s', 'roots'), $author->display_name);
    } else {
      single_cat_title();
    }
  } elseif (is_search()) {
    printf(__('Search Results for %s', 'roots'), get_search_query());
  } elseif (is_404()) {
    _e('Not Found', 'roots');
  } else {
    the_title();
  }
}

이 시도:

$pagename = get_query_var('pagename');

더 간단한 해결책을 생각해 냈습니다.

wp_title ()에서 리턴 된 페이지 이름 값을 가져 오십시오 (비어있는 경우 홈페이지 이름을 인쇄하십시오). 그렇지 않으면 wp_title 값을 반향하십시오.

<?php $title = wp_title('',false); ?>

Remember to remove the separation with first arg and then set display to false to use as a input to the variable. then just bung the code between your heading etc. tags.

<?php if ( $title == "" ) : echo "Home"; else : echo $title; endif; ?>

Worked a treat for me and ensuring that the first is declared in the section where you wish to extract the $title, this can be tuned to return different variables.

sean@loft6.co.uk


We just need to use the "post" global variable.

global $post;
echo $post->post_title;

This will echo the current page/post title.

Hope this help!!!!



    $title = get_the_title($post); 
    $parent_title = get_the_title($post->post_parent);

    echo $title;
    echo $parent_title;

Hope this will help !! ;)


I know this is old, but I came across this and what seems to be the easiest is using this.

<?php single_post_title(); ?>

Show title before the loop starts:

$page_title = $wp_query->post->post_title;

Thank you


Within Loop

<pre>
if ( have_posts() ) : while ( have_posts() ) : the_post();
/******************************************/
echo get_the_title();
/******************************************/
endwhile; endif;
</pre>

This will show you the current page title. For refrence http://codex.wordpress.org/Function_Reference/get_the_title


One option, if you're looking for the actual queried page, rather than the page ID or slug is to intercept the query:

add_action('parse_request', 'show_query', 10, 1);

Within your function, you have access to the $wp object and you can get either the pagename or the post name with:

function show_query($wp){
     if ( ! is_admin() ){ // heck we don't need the admin pages
         echo $wp->query_vars['pagename'];
         echo $wp->query_vars['name'];
     }
}

If, on the other hand, you really need the post data, the first place to get it (and arguably in this context, the best) is:

add_action('wp', 'show_page_name', 10, 1);

function show_page_name($wp){
     if ( ! is_admin() ){
        global $post;
        echo $post->ID, " : ", $post->post_name;
     }
}

Finally, I realize this probably wasn't the OP's question, but if you're looking for the Admin page name, use the global $pagenow.


Here's my version:

$title =ucwords(str_replace('-', ' ', get_query_var('pagename')));

get_query_var('pagename') was just giving me the page slug. So the above replaces all the dashes, and makes the first letter of each word uppercase - so it can actually be used as a title.


I've found now in Wordpress Codec this function:

get queried http://codex.wordpress.org/Function_Reference/wp_list_pages

which is a wrapper for $wp_query->get_queried_object. This post put me in the right direction but it seems that it needs this update.


This also works if you are in the functions.php. It is not the best approach since you have to use the global array but it works.

1- First, we need to add a filter. There must exist a better filter to use than the template_include but I don't know all of them. Please point me to the right one.

add_filter( 'template_include', 'var_template_include', 1000 );
function var_template_include( $template ){
    global $wp_query;
    $GLOBALS['current_page'] = $wp_query->get_queried_object()->post_name;
    return $template;
}

2- Avoid using the variable directly

function get_current_page( $echo =  false ) {
    if( !isset( $GLOBALS['current_page'] ) )
        return false;
    return $GLOBALS['current_page'];
}

3- Now you can use the function get_current_page() in any other part of the functions.php.


This is what I ended up using, as of 2018:

<section id="top-<?=(is_front_page() ? 'home' : basename(get_permalink()));?>">

참고URL : https://stackoverflow.com/questions/4837006/how-to-get-the-current-page-name-in-wordpress

반응형