2014-09-03 3 views
1

내가하고 싶은 것은 page_ids를 page_slugs 목록에서 가져 와서 변수에 문자열로 저장하여 다른 기능에서 "echo"/ "call"할 수있는 Wordpress 함수를 만드는 것입니다.WordPress의 page_slugs 목록에서 page_ids를 가져 와서 문자열로 저장하는 방법은 무엇입니까?

$the_page_slug = 'test'; 
global $wpdb; 
$page_id_from_slug = '\'' . $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name ='".$the_page_slug."'") . '\''; 

echo $page_id_from_slug; 

result is ok: '12' 

을이 기능은

function id_from_slug($the_page_slug){ 
global $wpdb; 
$page_id_from_slug = '\'' . $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name ='".$the_page_slug."'") . '\''; 
return $page_id_from_slug; 
} 
echo id_from_slug('test'); 

result is ok: '12' 

문제는 내가이 작업을 얻을 질수 너무 작동 : 지금까지

, 나는이와 page_slug에서 하나의 페이지 ID를 얻을 수 있습니다 page_slugs의 배열.

내 데이터가이 같다 :

'12', '16', '54', '76', '

$the_page_slugs = array('test', 'test-nr4', 'test-9', 'sample4', 'sample-nr12'); 

에코 출력 (page_ids) 이렇게 나와야 123'

어떤 아이디어가 있습니까?

답변

0

다음과 같이 시도해보십시오.

global $wpdb; 

$the_page_slugs = array('test', 'test-nr4', 'test-9', 'sample4', 'sample-nr12'); 
$page_id_from_slug = '\'' . $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name in '" . implode("','",$the_page_slugs) . "'") . '\''; 

echo $page_id_from_slug; 
+0

감사합니다. 훌륭한 출발점이었습니다. 주된 문제점은 get_var가 오직 하나의 결과를 가져온다는 것입니다. 당신이 IN 브라켓을 놓친 길에); – EdHanson

0

변화에 당신의 SQL :이 데이터베이스에서받은 후 print_r에 성공 기록의 배열을해야합니다

"SELECT ID FROM $wpdb->posts WHERE post_name in (".implode(",",$the_page_slugs)."))"; 

.

+0

나쁘지는 않지만, 정말로 나를 위해 일하지는 않았지만 내가 놓친 것에 "힌트"를 주었다. 감사 – EdHanson

1

내 솔루션은 여기에 있습니다. 제대로 작동합니다. 어떻게 필요합니까? 코드를보고 변경/추가 된 내용을 확인하십시오.

IN() 및 IMPLODE() 힌트는 실제로 필요한 것이고 "get_vars"("get_results" 그것을 조정했다. 여기

는 ..., 도움을

 // code to get page_ids from page_slugs 
     // the list of page_slugs 
$the_page_slugs = array('test', 'test-re', '1234', 'test-56', 'sample34', 'me3-uc', '1-12987-db', 'thy-m2o-1873'); 
     // set global, just in case ;) 
global $wpdb; 
     // query to get the page_ids 
$sql = "SELECT ID FROM wp_posts WHERE post_name IN('" . implode("', '", $the_page_slugs) . "') AND post_status = 'publish'"; 
     //this calls the query 
$get_page_ids = $wpdb->get_results($wpdb->prepare($sql)); 
     //prepare new var 
$the_page_ids =''; 
     //loop thru results to create var 
foreach($get_page_ids as $get_page_ids_result){ 
     //formate results, need it comma separated 
    $the_page_ids .= ('' == $the_page_ids) ? '':', '; 
     //fill it 
    $the_page_ids .= $get_page_ids_result->ID; 
    } 
echo "check if result is what we need<br/>"; 
echo $the_page_ids; 
     //perfekt result, looks like: 325, 323, 324, 327, 328, 329, 334, 335 

감사가 향상 될 수 있는지에 대한 내 코드입니다.

관련 문제