Mengambil Data di Front-End
Karena seluruh opsi MadOptions disimpan dalam satu baris array di tabel wp_options, pengambilan data sangat efisien dan ramah terhadap cache WordPress.
option” class=”mkdocs-anchor” aria-hidden=”true”># Mengambil Data Menggunakan get_option()
PHP
// Ambil seluruh array data panel berdasarkan option_name
$opts = get_option( 'my_theme_data', array() );
// 1. Membaca Field Standar (text, textarea, color, image)
$logo_url = isset( $opts['logo_url'] ) ? $opts['logo_url'] : '';
$brand_color = isset( $opts['brand_color'] ) ? $opts['brand_color'] : '#030813';
$tagline = isset( $opts['site_tagline'] )? $opts['site_tagline'] : '';
// 2. Membaca Field Switch
$show_cta = isset( $opts['show_cta'] ) ? $opts['show_cta'] : '1';
if ( $show_cta === '1' ) {
// Tampilkan tombol CTA
}
// 3. Membaca Field Select
$layout = isset( $opts['layout_style'] ) ? $opts['layout_style'] : 'boxed';
// 4. Membaca Field Typography (Sub-Array)
$typo = isset( $opts['typo_heading'] ) ? $opts['typo_heading'] : array();
$font_family = isset( $typo['family'] ) ? $typo['family'] : '';
$font_size = isset( $typo['size'] ) ? $typo['size'] : '2rem';
$line_height = isset( $typo['line_height'] ) ? $typo['line_height'] : '1.2';
$font_weight = isset( $typo['weight'] ) ? $typo['weight'] : '700';
$font_color = isset( $typo['color'] ) ? $typo['color'] : '#0e0f0f';
Contoh Injeksi CSS Inline
Data yang diambil dapat dengan mudah diinjeksikan sebagai variabel CSS atau style tag di <head>:
PHP
add_action( 'wp_head', 'my_custom_theme_options_css' );
function my_custom_theme_options_css() {
$opts = get_option( 'my_theme_data', array() );
$color = isset( $opts['brand_color'] ) ? $opts['brand_color'] : '#1e3a8a';
?>
<style id="my-theme-custom-css">
:root {
--brand-color: <?php echo esc_attr( $color ); ?>;
}
</style>
<?php
}
Best Practice: Helper Function Global
Disarankan untuk membuat satu fungsi pembantu (helper function) di tema Anda agar kode di template part lebih bersih dan ringkas:
PHP
function my_get_option( $key, $default = '' ) {
static $opts = null;
// Cache static agar query get_option hanya dipanggil sekali per request
if ( null === $opts ) {
$opts = get_option( 'my_theme_data', array() );
}
return isset( $opts[ $key ] ) ? $opts[ $key ] : $default;
}
// Contoh pemakaian di template:
$logo = my_get_option( 'logo_url' );
$bg = my_get_option( 'brand_color', '#ffffff' );