Return a numerical function value in Customizer controls

I'm trying to add some controls to the WordPress Customizer feature, but I'm having trouble pulling the numerical value from the control to use in the theme. The section appears in the Customizer tab, and I can change the input, but the controls have no effect on the theme.

I've looked up tutorials that use the get_theme_mod and inline styles to set attributes for divs, but I haven't been able to figure out exactly how to make the control id just return the input of a custom numerical value.

$wp_customize-add_section( 
     "news_portal_grid_section", 
     array(
    'title'     = esc_html__( 'Grid Style', 'news-portal-child' ),
    'panel'     = 'news_portal_grid_settings_panel',
    'priority'  = 25,
    )       
);   

$wp_customize-add_setting( 
     'np_posts_per_page', 
     array(          
    'default'           = '6',
    'sanitize_callback' = 'sanitize_key',
    )       
);  
$wp_customize-add_control(new WP_Customize_Control ($wp_customize,
    'np_posts_per_page',
     array(
            'type'     = 'text',
            'section'   = 'news_portal_grid_section',
            'settings'   = 'np_posts_per_page',
            'priority' = 2,
            'label' = __( 'Grid Posts' ),
            'description' = __( 'This sets the number of posts to display.  This must be numeric.' ),
            'validate' = 'numeric',
            'default'  = '5',
            'input_attrs' = array(
                'min' = 0,
                'max' = 50,
                'step' = 1,
            ),

   )) );

I know there should be a function/action hook here somewhere, but the WordPress API is a little vague on how exactly to implement this. I need the number output of np_post_num() to return as a simple integer or string that can then be declared in $option_pg_number= _________.

function np_post_num(){
echo get_theme_mod('np_posts_per_page', '5'); 
}
add_action ('wp_head', 'np_post_num'); 

Topic theme-customizer get-theme-mod functions php hooks Wordpress

Category Web


The solution for me ended up being to simply remove the np_post_num() add_action hook altogether, and instead declare get_theme_mod() as the desired variable $option_pg_number. This allowed use of the returned number variable in a separate loop function controlled by $option_pg_number, instead of just printing the returned number value of 'np_posts_per_page' on the page.

$option_pg_number = get_theme_mod('np_posts_per_page', '5');

I think this could have been cleared up a lot faster if the WordPress Codex included more documentation on the usage of the various built in features. The codex focuses on setting up the settings and controls, but doesn't offer much explanation on how to implement the controls on pages.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.