POST 의 썸네일을 각각 불러와야 하는데 하나만 불러와지는 이슈

안녕하세요, A 페이지(아래 A페이지 전체 코드)에 워드프레스 POST 를 3개 가져와서 출력했습니다.

각각의 POST 를 클릭하면, B페이지로 이동하고 해당 페이지의 sendURL 파라미터로 각각의 썸네일 주소를 가져오는 것을 목표로 합니다.

그런데 3개의 POST 모두가 클릭 시 A 페이지에서 출력한 3개의 POST 중 첫 번째 POST의 썸네일 주소만 가져오고 2번째, 3번째 POST 썸네일 주소는 가져오지 못합니다.

썸네일을 가져오는 Function 이 1회만 동작하는 것 같은데... 제가 무엇을 잘 못 썼을까요? ㅠㅠ 고민하다가 글을 남겨봅니다.

<?php
define('WP_USE_THEMES', false);
require($_SERVER['DOCUMENT_ROOT'] . "/wp-load.php");
?>

<!--썸네일 주소 함수 / 멀티 썸네일이 가능하도록 "multi-post-thumbnails" 플러그인 활용
https://github.com/voceconnect/multi-post-thumbnails/wiki/Functions-and-Template-Tags-->

<?php 
    function myURL(){
    if (class_exists('MultiPostThumbnails')) {
        $url = MultiPostThumbnails::get_post_thumbnail_url(
            get_post_type(),
            'secondary-image'
            );
        echo $url;
        }
    }
?>

<!--블로그 POST 가져오기-->

<?php 
$query1 = new WP_Query('showposts=6&cat=blogs&category_name=event&offset=0'); 
if ($query1->have_posts()) : 
while ($query1->have_posts()) : $query1->the_post(); 
?>

    <li>

<!--불러온 POST 클릭 시 페이지 이동하면서, URL 에 썸네일 주소를 파라미터로 삽입하는 JS 함수 불러오기-->
        <a href="javascript:void(0);" onclick="sendURL();return false;">
            <div class="img-area">
                <div class="pc"><?php the_post_thumbnail('Thumbnail'); ?></div>
                <div class="m"><?php the_post_thumbnail('Thumbnail'); ?></div>
            </div>
                <div class="txt-area">
                    <div class="tit">
                        <?php the_title(); ?>
                    </div>
                    <div class="txt">
                        <?php echo get_secondary_title(); ?>
                    </div>

<!--썸네일 주소 출력하기 JS에서 읽을 수 있도록 텍스트로 display:none 출력-->
                    <div id='myURL2' style="display:none;"><?php myURL();?>
                    </div>                    
                </div>
        </a>
    </li>



<?php
endwhile; endif; wp_reset_postdata(); 
?>  


<!--생성된 썸네일 주소를 파리미터로 삽입하여 이동하는 JS-->
<script>
function sendURL(){
let myURL3 = document.getElementById('myURL2').textContent;
let url = `event_result.php?sendURL=` + myURL3;
window.location.href = url;
}
</script>

 

//참고용: 멀티 썸네일 플러그인 function
//출처 https://github.com/voceconnect/multi-post-thumbnails/wiki/Functions-and-Template-Tags
get_post_thumbnail_url()
Function signature:

MultiPostThumbnails::get_post_thumbnail_url(
    $post_type,
    $id,
    $post_id = 0,
    $size = null
)
Get the URL of the thumbnail.

$post_type required: The post type of the post the thumbnail is set on.
$id required: The id used to register the thumbnail.
$post_id optional: The post ID of the post the thumbnail is set on. Defaults to the post ID of the currently queried object.
$size optional: The size to use. Defaults to the original size.

 

좋은 정보와 인맥을 동시에, 워드프레스 사용자 단톡방 참여하기
좋은 정보와 인맥을 동시에, 워드프레스 사용자 단톡방 참여하기
  • 안녕하세요~^^

    올려주신 코드 중

    아래의 코드는 워드프레스 글(Post)의 개수만큼 생성됩니다.

    <a href="javascript:void(0);" onclick="sendURL();return false;">
    	...
    </a>

     

    또한 <div> 태그에 같은 id를 중복해서 사용하실 경우,

    자바스크립트 코드로 id로 구분해서 값을 가져올 경우 정상적으로 동작하지 않습니다.

    id 선택자는 중복되어선 안 됩니다.

    <div id='myURL2' style="display:none;"><?php myURL();?>

     

    링크 클릭 시 최종적으로 URL 형태가 어떻게 되어야 하는지 알려주시면

    도움 드릴 방법을 찾아보겠습니다.

    고맙습니다.

  • @스레드봇 네 ^^ 

    먼저 본문에서 제가 빼먹은 부분이 있습니다. 죄송합니다 ^^;; 본문의 코드는 event.php 코드이며 이를 event.html 에서 include 해서 사용합니다. 이 부분을 빼먹었습니다.

    URL은 

    A 페이지에서는 a.com/event.html

    <a href="javascript:void(0);" onclick="sendURL();return false;"> 중략 </a> 으로 감싸져있는 각각의 POST  썸네일을 클릭하면

    B 페이지에서는 a.com/event_result.php?sendURL="썸네일URL" 의 형태가 됩니다. 다만, 현재는 썸네일URL이 클릭한 POST에 연동되지 않고, 하나의 POST 썸네일URL만 출력되고 있습니다.

  • 특정 글(Post) 클릭 시 해당 썸네일 이미지 주소만 가져오게 하면 되는지요?

    올려주신 코드 중 기존 아래의 코드를

    <a href="javascript:void(0);" onclick="sendURL();return false;">

    아래의 코드로 교체해보세요.

    <a href="javascript:void(0);" onclick="sendURL(this);return false;">

     

    아래의 코드를 찾아서

    <div id='myURL2' style="display:none;">

    아래의 코드로 교체해보세요.

    <div class="post-thumbnail-url" style="display: none;">

     

    아래의 코드도 찾아서

    <script>
    function sendURL(){
    let myURL3 = document.getElementById('myURL2').textContent;
    let url = `event_result.php?sendURL=` + myURL3;
    window.location.href = url;
    }
    </script>

    아래의 코드로 교체해서 확인해보시겠어요?

    <script>
    function sendURL(obj){
    let post_url = obj.querySelector('.post-thumbnail-url').textContent;
    let url = 'event_result.php?sendURL=' + post_url;
    window.location.href = url;
    }
    </script>

    고맙습니다.

  • @스레드봇 님, 테스트 중에 php function, JS function 을 주석 처리하고 아래와 같이 직접 페이지에 출력을 하면 정상적으로 각각의 썸네일 이미지 주소를 가져올 수 있습니다. 문제는 자바스크립트 코드인걸까요? (이 질문은 위 해결책을 주시기 바로 직전 남긴 글입니다. 위 해결책 적용해보고 다시 회신드리겠습니다 :)

    <div class='myURL2' style="">
       <?php echo MultiPostThumbnails::get_post_thumbnail_url(get_post_type(),
         'secondary-image');?></div>    

     

  • @스레드봇 님! 잘 됩니다. 아래처럼 %20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20 가 추가되는데 이 부분은 어떻게 하면 지울 수 있을까요? 

    (해결했습니다) 왠지 블랭크 때문에 발생하는 것 같아 div 와 php 코드 사이의 빈 공간을 삭제했습니다 :)

    큰 도움 되었습니다 감사합니다!

    sendURL=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://썸네일주소

     

워드프레스 에러 기술지원 서비스 전문가에게 맡기세요