harumemo

メモ書きです。

カスタム投稿一覧画面に「複製」リンクを追加する方法

// 投稿一覧画面の表示タイミングにインターラプトする。
add_action( 'admin_init', 'mytheme_admin_init' );
function mytheme_admin_init() {
    add_filter( 'post_row_actions', 'mytheme_post_row_actions', 10, 2 );
}

// 「複製」リンクを表示する。
function mytheme_post_row_actions( $actions, $post ) {
    if(get_post_type() === 'event') {
        if (array_key_exists('copy_to_template', $actions)) { unset($actions['copy_to_template']); } // tinymcetemplateのエントリーを削除する。
        $actions['duplicate'] = '<a href="post-new.php?post_type=event&origin=' . $post->ID . '">複製</a>';
    }
    return $actions;
}

// 現行は何もしない。
add_filter( 'admin_head-post-new.php', 'duplicate_event_admin_head' );
function duplicate_event_admin_head() {
    // 新規追加画面を開いたときに、何か処理がしたければ記載する。
}

// 画面表示が終わった後、jQueryを使って空欄にソースデータをコピーする。
add_filter( 'admin_footer-post-new.php', 'duplicate_event_admin_footer' );
function duplicate_event_admin_footer() {
    global $hook_suffix;
    if ( 'post-new.php' === $hook_suffix ) {
        if(get_post_type() === 'event') {
            if ( isset( $_GET['origin'] ) && intval( $_GET['origin'] ) ) {
                $origin = get_post( intval( $_GET['origin'] ) );
                $secondary_title   = get_secondary_title($origin->ID);
                $event_term        = get_the_terms($origin->ID,'event');
                
                $template = array(
                    'post_title' => $origin->post_title,
                    'secondary_title' => $secondary_title,
                    'post_content' => wpautop( $origin->post_content ),
                    'event_term' => '#in-event-' . $event_term[0] -> term_id
                );
                
                ?>
                <script type="text/javascript">
                var origin = <?php echo json_encode( $template); ?>;
                jQuery( '#title').val(origin.post_title);
                <?php if($secondary_title) { echo "jQuery( '#secondary-title-input').val(origin.secondary_title);\n"; } ?>
                jQuery( '#acf-xxx-xxx-xxx input[type=hidden]').val(origin.xxx_xxx_xxx);
                jQuery( origin.event_term ).attr("checked", true);
                </script>
                <?php
            }
        }
    }
}