In the loop.php or in the loop code you will need make sure the code is in the php tags.
To wrap a code call in php tags <?php my_function(); ?>
If you are returning strings (url’s)
<!-- This is html code and comment outside the php tags -->
<div>
<?php /* This is a php comment and code lines inside php tags */ ?>
<?php echo my_function('link1'); ?>
<?php
/* This is also php comment and code lines inside php tags */
if($whichlink) {
echo my_function($whichlink);
}
?>
<!-- Back to html code -->
</div>
<!-- This is mixed conditional code block php, html, php, html, php, html -->
<?php if($whichlink) : ?>
<div>
<?php echo my_function($whichlink); ?>
</div>
<?php endif; ?>
<!-- All Done -->
If you want to add the script code and loop code to pastebin and add the two file links, you might get a more detailed answer, it might be better to use a template part.
Study the structure and code in the default themes loop for more examples.
HTH
David