$post
is never set on init
when I test this–
function topSub( $Trunckvalue = null ) {
global $post;
var_dump($post);
}
add_action( 'init', 'topSub' );
The earliest hook I can find (by experimentation, not a canonical statement) is wp
.
Aditionally, $post
is set on archive pages as well as “single” pages. On those archive pages it is set to the first post in the Loop.
The self-answer by @MayeenulIslam has a comment that …
//check if post is object otherwise you're not in singular post
That statement is false.
I do not expect the code, or the self-answer, to work as expected for both of those reasons. The solution, by my reading should be:
// Top Sub Heading (top_sub) FROM CUSTOM FIELD
function topSub( $Trunckvalue = null ) {
if (!is_singular()) return;
global $post;
$TopSub = get_post_meta( $post->ID, 'top_sub', $single=true );
$shortTopSub = trunck_string( $TopSub, $Trunckvalue, true );
if ( !$TopSub == NULL ) { ?>
<h3 class="top-sub"><?php echo $shortTopSub; ?></h3> <!-- .top-sub -->
<?php }
return $shortTopSub;
}
add_action( 'wp', 'topSub' ); // or a later hook depending on circumstances
I am also puzzled by this line:
if ( !$TopSub == NULL ) { ?>
You are checking whether $TopSub
is not NULL
but are actually using $shortTopSub
in the conditional. It seems to me that that should be rewritten:
if ( !empty($shortTopSub) ) { ?>
<h3 class="top-sub"><?php echo $shortTopSub; ?></h3> <!-- .top-sub -->
<?php }