programing

Wordpress Admin에서 게시 ID를 가져오는 방법

codeshow 2023. 3. 8. 21:37
반응형

Wordpress Admin에서 게시 ID를 가져오는 방법

Wordpress 플러그인을 개발 중인데 현재 Post ID를 가져와야 합니다.
[ Write Post / Write Page ]편집화면(루프 외)에 표시됩니다.

javascript 파일에 데이터를 전달하고 싶기 때문에 "admin_print_scripts" 훅 전에 해야 합니다.

사용할 수 없습니다.

$id = $_GET['post'];

새 게시물 또는 페이지를 추가할 때 URL에 이 변수가 포함되지 않기 때문입니다.

지금까지 다음 옵션을 시도해 봤지만 모두 효과가 없었습니다.

A) ID 0이 반환됩니다.

function myplugin_setup() {
    global $wp_query;
    $id = $wp_query->get_queried_object_id();
    var_dump($id);
}

add_action('admin_init', 'myplugin_setup' );  

B) 이것은 null의 ID를 반환합니다.

function myplugin_setup() {
    global $wp_query;
    $id = $wp_query->post->ID;
    var_dump($id);
}

add_action('admin_init', 'myplugin_setup' );

C) 이 명령어는 null의 ID도 반환합니다.

function myplugin_setup() {
    global $post;
    $id = $post->ID;
    var_dump($id);
}

add_action('admin_init', 'myplugin_setup' );

WordPress 쿼리 뒤에 글로벌 $post를 호출해야 합니다.init 또는 admin_init에 액션을 추가하면 쿼리가 준비되지 않아 글로벌 $post 변수에서 아무것도 얻을 수 없습니다.

http://codex.wordpress.org/Plugin_API/Action_Reference에서 액션 레퍼런스를 확인하고 자신에게 맞는 것을 선택하는 것이 좋습니다.

예를 들어 다음과 같이 했습니다.

add_action( 'admin_head', 'check_page_template' );
function check_page_template() {
    global $post;
    if ( 'page-homepage.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
        // The current page has the foobar template assigned
        // do something

    }
}

그리고 나는 WP 관리자로부터 페이지 ID를 얻을 수 있었다.

용도:

global $post

기능을 시작할 때 사용할 수 있습니다.그러면 $post->에 액세스 할 수 있습니다.현재 게시물의 ID를 가져오는 ID입니다.이것은 신규 및 기존 투고에 적용됩니다.

문제는 admin_init 훅을 사용하고 있다는 것입니다.Action Reference(http://codex.wordpress.org/Plugin_API/Action_Reference)를 살펴보면 이 훅은 실제로 게시물을 쿼리하기 전에 호출된다는 것을 알 수 있습니다.그래서 사용하는 변수가 아직 채워지지 않았습니다.

이후의 액션(일부 is_admin() 체크)을 사용하거나 admin init 훅을 사용하여 나중에 훅에 액션을 추가할 수 있습니다.이러한 액션도 admin에게만 사용됩니다.

admin_init 액션은 사용자가 관리 영역에 액세스할 때 다른 후크보다 먼저 트리거됩니다.새 게시물이 ID를 얻기 전에 트리거됩니다.

새로운 투고 ID를 취득하려면 , 투고 또는 페이지가 작성 또는 갱신될 때마다 트리거 되는 액션 「save_post」를 사용합니다(http://codex.wordpress.org/Plugin_API/Action_Reference/save_post)).

먼저 'admin_enqueue_scripts'를 사용하여 스크립트를 포함시킨 후 'save_post'를 사용하여 새 게시 ID를 얻을 수 있습니다.'admin_print_post'는 'save_post' 뒤에 트리거되며 wp_localize_script(https://codex.wordpress.org/Function_Reference/wp_localize_script), 또는 기타 메서드를 사용하여 새로운 게시 ID를 javascript에 전달할 수 있습니다.

비슷한 게 필요했는데 수업시간에 쓰였어요.

class Foo {
    // this will hold the id of the new post
    private $postId = null;

    public function __construct()
    {
        // the actions are triggered in this order
        add_action('admin_enqueue_scripts', array($this, 'EnqueueScripts'));
        add_action('save_post', array($this, 'SavePost'));
        add_action('admin_print_scripts', array($this, 'LocalizeScripts'));
    }

    // enqueue your scripts and set the last parameter($in_footer) to true
    public function EnqueueScripts()
    {
        wp_enqueue_script('myJs', 'js/my.js', array('jquery'), false, true); 
    }

    // use wp_localize_script to pass to your script the post id
    public function LocalizeScripts()
    {
        wp_localize_script('myJs', 'myJsObject', array('postId'=>$this->GetPostId()));
    }

    // if $post_id is different from global post id you are in the write/create post page, else you are saving an existing post
    public function SavePost($post_id)
    {
        if($post_id != $this->GetPostId())
        {
            $this->SetPostId($post_id);
        }
    }

    private function GetPostId()
    {
        if (!$this->postId) {
            global $post;
            if($post)
            {
                $this->SetPostId($post->ID);
            }
        }

        return $this->postId;
    }

    private function SetPostId($postId)
    {
        $this->postId = $postId;
    }
}

이제 Javascript에서 다음을 사용할 수 있습니다.

myJsObject.postId

올바른 문의 후크 또는 Wordpress 관리 라이프 사이클의 많은 항목 중 하나가 궁금하신 분은 admin_head를 참조하십시오.

다음과 같습니다.

function myplugin_setup() {
    global $post;
    $id = $post->ID;
    var_dump($id);
}

add_action('admin_head', 'myplugin_setup' );

새로운 투고/페이지라면 아직 DB에 게시/추가되지 않았기 때문에 ID가 존재하지 않는다고 생각합니다.글이나 , 은 글이나 를 편집하려고 할 때, 글이나 페이지를 편집하다, , 라고 하면 될 것 같아요.$id = $_GET['post'];

$post_id = null;
if(isset($_REQUEST['post']) || isset($_REQUEST['psot_ID'])){
    $post_id = empty($_REQUEST['post_ID']) ? $_REQUEST['post'] : $_REQUEST['post_ID'];  
}

관리 패널에서 ID를 얻는 데 도움이 될 것 같습니다.

다음과 같이 동작합니다.

$id = get_the_ID();

언급URL : https://stackoverflow.com/questions/8463126/how-to-get-post-id-in-wordpress-admin

반응형