Conditional Tags

From 워드프레스(WORDPRESS) 한국어 위키

Jump to: navigation, search

Contents

Introduction

워드프레스의 조건 태그(Conditional Tags)는 템플릿 파일에서 사용 할 수 있으며, 해당 페이지가 어떤 조건에서 출력되는지를 판단하여 그 조건에 맞는 내용을 구별해서 다르게 출력 해 줄 수 있게 해 줍니다. 예를들어, 블로그의 메인(처음) 페이지에서는 글 내용 전체를 표시하지 않고 요약문 만을 표시하고 싶은 경우가 있을 수 있겠죠. 이 경우 is_home() 이라는 조건 태그를 사용하면 원하는 형태로 쉽게 표현 할 수 있게됩니다.

우선은, 이 조건 태그들이 워드프레스의 탬플릿 계층구조 와 밀접한 관계에 있음을 알아두셔야 합니다.

The Conditions For...

모든 조건 태그들은 제시된 조건에 맞는 페이지인지를 확인하여 TRUE 또는 FALSE 값을 반환하게 됩니다. 각 조건 태그들이 어떤 상황에서 TRUE값을 반환하게 되는지는 아래에 잘 설명되어 있습니다. 또한 각 태그들에 어떠한 설정값을 사용 할 수 있는지도 살펴보시기 바랍니다.

The Main Page

is_home() 
메인 페이지가 출력될 때. 처음 페이지에서 이전 글 링크를 눌러 출력되는(paged) 페이지 일때도 적용됩니다.

A Single Post Page

is_single() 
개별 글이 출력 될 때.
is_single('17') 
ID가 17인 글이 개별적으로 출력 될 때.
is_single('Beef Stew') 
'Beef Stew'라는 제목을 가진 글이 개별적으로 출력 될 때.
is_single('beef-stew') 
post slug 가 'beef-stew'인 글이 개별적으로 출력 될 때.

Any Page Containing Posts

comments_open()
워드프레스 루프에서 해당 글이 댓글 달기를 허용 할 때.
pings_open()
워드프레스 루프에서 해당 글이 Ping(또는 트랙백)을 허용 할 때.

A PAGE Page

이 부분은 일반적으로 말하는 웹 페이지가 아닌, 워드프레스의 페이지 에 해당됩니다.

is_page() 
어떠한 페이지 가 출력 될 때.
is_page('42') 
ID가 42인 페이지 가 출력 될 때.
is_page('About Me') 
제목이 "About Me" 인 페이지 가 출력 될 때.
is_page('about-me') 
post slug 가 "about-me" 인 페이지 가 출력 될 때.

아쉽게도 아직까지는 is_subpage() 라는 조건 태그는 존재하지 않습니다.

if(get_the_title($post->post_parent) != the_title(' ' , ' ',false)) { echo "This is a subpage"; } 
상위 페이지의 제목이 현재 페이지의 제목과 같은지를 확인하여(상위 페이지가 없을 경우 상위 페이지를 자신으로 인식) 다르다면 자신이 어떤 페이지의 하위 페이지(subpage)임을 확인하는 코드입니다.

A Category Page

is_category() 
카테고리 목록이 출력 될 때.
is_category('6') 
ID가 6인 카테고리의 목록이 출력 될 때.
is_category('Cheeses') 
"Cheeses" 라는 이름을 가진 카테고리의 목록이 출력 될 때.
is_category('cheeses') 
Category Slug 가 "cheeses"인 카테고리의 목록이 출력 될 때.
in_category('5') 
현재 출력되는 글이 ID 가 5 인 카테고리에 속해 있을 때.자세히

is_archive() 태그와 카테고리 템플릿 페이지도 참고해 보세요.

An Author Page

is_author() 
글 작성자에 따른 글들이 출력 될 때.
is_author('1337') 
글 작성자 ID 가 1337 인 글들이 출력 될 때.
is_author('Elite Hacker') 
별명(Nickname)이 "Elite Hacker"인 작성자의 글들이 출력 될 때.
is_author('elite-hacker') 
Nicename 이 "elite-hacker"작성자의 글들이 출력 될 때.

is_archive() 태그와 작성자 템플릿 페이지도 참고해 보세요.

A Date Page

is_date() 
모든 날짜에 관련된 형태로 글들이 출력 될 때 (예. 월별, 일별, 연별, 시간별...).
is_year() 
연별(yearly) 목록이 출력 될 때.
is_month() 
월별(monthly) 목록이 출력 될 때.
is_day() 
일별(daily) 목록이 출력 될 때.
is_time() 
시간별(hourly), 분별(minutely, 또는 초별(secondly) 목록이 출력 될 때.

is_archive() 태그도 참고해 보세요.

Any Archive Page

is_archive() 
모든 형태의 목록 글들이 출력 될 때. 카테고리, 작성자, 날짜별 목록들이 모두 이에 해당됩니다.(is_category, is_author, is_date, is_year, is_month, is_day, is_time ...)

A Search Result Page

is_search() 
블로그 내에서의 검색 결과가 출력 될 때.

A 404 Not Found Page

is_404() 
"HTTP 404: Not Found"(페이지를 찾을 수 없습니다) 에러가 발생 했을 때.

A Paged Page

is_paged() 
해당 목록이나 메인 페이지, 검색 결과 등의 페이지에서 이전 글(또는 결과) 링크를 눌러 페이지화된(paged) 페이지를 출력 할 때. 이는 한 글(또는 페이지)가 <!--nextpage--> 라는 QuickTag 에 의해 나누어졌을 때 와는 무관합니다.

An Attachment

is_attachment() 
첨부된 파일을 따로 출력해 주는 경우. 첨부 파일은 글 작성자가 업로드 환경에서 이미지나 다른 형태의 파일을 업로드 했을 때 템플릿 파일(attachment.php), 일반 페이지 또는 글 형태로 출력 되기도 합니다. 자세한 내용은 이미지 또는 첨부파일 활용 페이지를 참고하세요.

A Syndication

is_feed() 
요청된 페이지가 Syndication 즉, 피드(feed) 일 때. 이 태그는 일반적인 사용자보다는 워드프레스 자체기능 또는 플러그인에 사용되는 경우가 많습니다.

A Trackback

is_trackback() 
요청된 내용이 상대방으로 부터의 트랙백(trackback) 일 때. 이 태그는 일반적인 사용자보다는 워드프레스 자체기능 또는 플러그인에 사용되는 경우가 많습니다.

Working Examples

아래는 실제로 사용되는 예제들 입니다.

Single Post

아래는 개별 글에서 is_single()을 이용하여 특정 내용을 출력 해 주는 예 입니다 :

if (is_single())
{
     echo 'This is just one of many fabulous entries in the ' . single_cat_title() . ' category!';
}

Date-Based Differences

방문객이 블로그에서 날짜별 목록을 확인 할 때 올해에 작성된 글과 그 이전에 작성된 글의 색을 다르게 지정하는 방법을 예로 들어보겠습니다 :

<?php
// this starts The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2 id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">
<?php the_title(); ?></a></h2>
<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

<?php
// are we showing a date-based archive?
if (is_date())
{
     if (date('Y') != get_the_date('Y'))
     {
          // this post was written in a previous year
          // so let's style the content using the "oldentry" class
          echo '<div class="oldentry">';
     } else {
          echo '<div class="entry">';
     }
} else {
     echo '<div class="entry">';
}
the_content('Read the rest of this entry »'); 
?>
</div>

Variable Sidebar Content

여러가지 조건에 따라 사이드바에 출력되는 내용을 다르게 하는 방법을 예로 들어 보겠습니다.

<!-- begin sidebar -->
<div id="sidebar">
<?php
// let's generate info appropriate to the page being displayed
if (is_home()) {
        // we're on the home page, so let's show a list of all top-level categories
        echo "<ul>";
        wp_list_cats('optionall=0&sort_column=name&list=1&children=0');
        echo "</ul>";
} elseif (is_category()) {
        // we're looking at a single category view, so let's show _all_ the categories
         echo "<ul>";
        wp_list_cats('optionall=1&sort_column=name&list=1&children=1&hierarchical=1');
        echo "</ul>";
} elseif (is_single()) {
        // we're looking at a single page, so let's not show anything in the sidebar
} elseif (is_page()) {
        // we're looking at a static page.  Which one?
        if (is_page('About')) {
             // our about page.
             echo "<p>This is my about page!</p>";
        } elseif (is_page('Colophon')) {
             echo "<p>This is my colophon page, running on WordPress " . bloginfo('version') . "</p>";
        } else {
              // catch-all for other pages
              echo "<p>Vote for Pedro!</p>";
        }
} else {
        // catch-all for everything else (archives, searches, 404s, etc)
        echo "<p>Pedro offers you his protection.</p>";
} // That's all, folks!
?>
<form id="searchform" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div>
<input type="text" name="s" id="s" size="15" />
<input type="submit" value="<?php _e('Search'); ?>" />
</div>
</form>

</div>
<!-- end sidebar -->

Helpful 404 page

방문객이 요청한 페이지가 존재하지 않아 "404 error page"를 출력 될 때, 보통 방문객 들에게 아무 도움이 되지 않는 무의미한 내용만이 보여지곤 합니다. 이 태그를 이용해서 방문객이 찾는 내용을 좀 더 쉽게 찾을 수 있도록 도와주는 내용들을 출력 해 줄 수 있습니다. 아래의 예제는 404 에러가 발생했을 경우 어떤 페이지를 요청했었는지를 관리자 메일로 발송하여 관리자가 그에 대처 할 수 있도록 해 주는 내용을 표현한 것입니다.

<p>You 
<?php
#some variables for the script to use
#if you have some reason to change these, do.  but wordpress can handle it
$adminemail = get_bloginfo('admin_email'); #the administrator email address, according to wordpress
$website = get_bloginfo('url'); #gets your blog's url from wordpress
$websitename = get_bloginfo('name'); #sets the blog's name, according to wordpress

  if (!isset($_SERVER['HTTP_REFERER'])) {
    #politely blames the user for all the problems they caused
        echo "tried going to "; #starts assembling an output paragraph
	$casemessage = "All is not lost!";
  } elseif (isset($_SERVER['HTTP_REFERER'])) {
    #this will help the user find what they want, and email me of a bad link
	echo "clicked a link to"; #now the message says You clicked a link to...
        #setup a message to be sent to me
	$failuremess = "A user tried to go to $website"
        .$_SERVER['REQUEST_URI']." and received a 404 (page not found) error. ";
	$failuremess .= "It wasn't their fault, so try fixing it.  
        They came from ".$_SERVER['HTTP_REFERER'];
	mail($adminemail, "Bad Link To ".$_SERVER['REQUEST_URI'],
        $failuremess, "From: $websitename <noreply@$website>"); #email you about problem
	$casemessage = "An administrator has been emailed 
        about this problem, too.";#set a friendly message
  }
  echo " ".$website.$_SERVER['REQUEST_URI']; ?> 
and it doesn't exist. <?php echo $casemessage; ?>  You can click back 
and try again or search for what you're looking for:
  <?php include(TEMPLATEPATH . "/searchform.php"); ?>
</p>

Dynamic Menu Highlighting

The Dynamic Menu Highlighting article discusses how to use the conditional tags to enable highlighting of the current page in a menu.

Go to Template Tag index

Personal tools