Reputation: 51
In a WordPress header.php file, is there a way to reduce this :
<?php if (is_page('about')): ?>
<script type="text/javascript">var page = "about";</script>
<?php endif ?>
<?php if (is_page('contact')): ?>
<script type="text/javascript">var page = "contact";</script>
<?php endif ?>
<?php if (is_page('gallery')): ?>
<script type="text/javascript">var page = "gallery";</script>
<?php endif ?>
to
<script type="text/javascript">
var page = "<?php echo get_current_page() ?>";
</script>
Upvotes: 2
Views: 21387
Reputation: 187
'get_page' was deprecated, updated to:
<script type="text/javascript">
<?php $pageDetails = get_post(); ?>
var page_title = <?php echo json_encode( $pageDetails->post_title ); ?>;
var page_slug = <?php echo json_encode( $pageDetails->post_name ); ?>;
var page_id = <?php echo json_encode( $pageDetails->ID ); ?>;
</script>
Upvotes: 0
Reputation: 10341
OK, the slight rub here is that the is_page()
function will return TRUE if the contained string is the Post Title OR the Post Slug (WordPress Codex). So I will offer both solutions and you can pick which one works best for you.
<script type="text/javascript">
<?php $pageDetails = get_page(); ?>
var page_title = "<?php echo str_replace( '"' , '\"' , $pageDetails->post_title ); ?>";
var page_slug = "<?php echo str_replace( '"' , '\"' , $pageDetails->post_name ); ?>";
</script>
I included the str_replace()
bit to ensure that any page names which include quotation marks will not break your Javascript.
And, adjusted as per comments by David M, using JSON to make things a little safer...
<script type="text/javascript">
<?php $pageDetails = get_page(); ?>
var page_title = <?php echo json_encode( $pageDetails->post_title ); ?>;
var page_slug = <?php echo json_encode( $pageDetails->post_name ); ?>;
</script>
Upvotes: 6