Вызов функции из functions.php возвращает нежелательное значение - PullRequest
1 голос
/ 20 июля 2011

Когда я вызываю функцию подсчета комментариев ниже из моего файла functions.php, я получаю «0», даже если в посте есть комментарии.Когда я вызываю функцию из другого шаблона страницы (<?php echo fb_comment_count(); ?>), отображается правильный номер комментария.

Я попытался отладить, чтобы проверить значение $ post внутри функции fb_comment_count, и он генерирует следующее:

id = 818 id = 818 id = 818 id = 818 id = 818 id = 818 id = 818 id = 818

Это неверно, поскольку каждый из этих идентификаторов должен быть разным для каждой страницы вложения, на которой находится изображение.818 - это идентификатор всей страницы галереи.Я полагаю, именно поэтому я продолжаю получать «0» для количества комментариев, так как сама страница галереи (id 818) не имеет комментариев.

Чтобы дать лучшее представление о том, что я пытаюсь сделать, вотшаблон для страницы галереи.Каждое из этих изображений связано с соответствующими страницами вложений.Белое поле с номером внутри - это количество комментариев.

gallery

Если кто-нибудь может помочь мне выяснить, как получить правильное количество комментариев для каждого из изображений в галерее,Я был бы очень благодарен.Спасибо.

Вот функция fb_comment_count.

// FB Comment Count (by Zack Austin)
function fb_comment_count($link = 'link') {
  global $post;
  $url = 'https://graph.facebook.com/';
  $posturl = get_permalink($post->ID);
  $url .= $posturl;

  $filecontent = wp_remote_retrieve_body(wp_remote_get($url, array('sslverify'=>false)));
  $json = json_decode($filecontent);
  $count = $json->comments;
  if ($count == 0 || !isset($count)) {
    $count = 0;
  }

  $comments = $count;
  if ($count == 1) {
    $comments .= '';
  }
  elseif ($count == 0) {
    $comments = '0';
  }
  elseif ($count > 1) {
    $comments .= '';
  }
  if ($link == 'nolink') {
    return $comments;
  }
  else {
    return '<a href="'.$posturl.'#comments" title="Comments for '.$post->post_title.'">'.$comments.'</a>';
  }
}

А вот пользовательский код галереи, где я вызываю функцию fb_comment_count выше (примерно 22 строки снизу).Код ниже и код выше находятся в моем файле functions.php.

// Custom Gallery
add_filter( 'post_gallery', 'my_post_gallery', 10, 2 );
function my_post_gallery( $output, $attr) {
    global $post, $wp_locale;

    static $instance = 0;
    $instance++;

    // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
    if ( isset( $attr['orderby'] ) ) {
        $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
        if ( !$attr['orderby'] )
            unset( $attr['orderby'] );
    }

    extract(shortcode_atts(array(
        'order'      => 'ASC',
        'orderby'    => 'menu_order ID',
        'id'         => $post->ID,
        'itemtag'    => 'dl',
        'icontag'    => 'dt',
        'captiontag' => 'dd',
        'columns'    => 3,
        'size'       => 'thumbnail',
        'include'    => '',
        'exclude'    => ''
    ), $attr));

    $id = intval($id);
    if ( 'RAND' == $order )
        $orderby = 'none';

    if ( !empty($include) ) {
        $include = preg_replace( '/[^0-9,]+/', '', $include );
        $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

        $attachments = array();
        foreach ( $_attachments as $key => $val ) {
            $attachments[$val->ID] = $_attachments[$key];
        }
    } elseif ( !empty($exclude) ) {
        $exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
        $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    } else {
        $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    }

    if ( empty($attachments) )
        return '';

    if ( is_feed() ) {
        $output = "\n";
        foreach ( $attachments as $att_id => $attachment )
            $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
        return $output;
    }

    $itemtag = tag_escape($itemtag);
    $captiontag = tag_escape($captiontag);
    $columns = intval($columns);
    $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
    $float = is_rtl() ? 'right' : 'left';

    $selector = "gallery-{$instance}";

    $output = apply_filters('gallery_style', "
        <style type='text/css'>
            #{$selector} {
                margin: auto;
            }
            #{$selector} .gallery-item {
                float: {$float};
                margin-top: 10px;
                text-align: center;
                width: {$itemwidth}%;           }
            #{$selector} img {
                border: 2px solid #cfcfcf;
            }
            #{$selector} .gallery-caption {
                margin-left: 0;
            }
        </style>
        <!-- see gallery_shortcode() in wp-includes/media.php -->
        <div id='$selector' class='gallery galleryid-{$id}'>");

    $i = 0;
    foreach ( $attachments as $id => $attachment ) {
        $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);

        $output .= "<{$itemtag} class='gallery-item'>";
        $output .= "<span class='photos-comment-number-wrap'><span class='comment-number'>". fb_comment_count() ."</span></span>";
        $output .= "
            <{$icontag} class='gallery-icon'>
                $link
            </{$icontag}>";
        if ( $captiontag && trim($attachment->post_excerpt) ) {
            $output .= "
                <{$captiontag} class='gallery-caption'>
                " . wptexturize($attachment->post_excerpt) . "
                </{$captiontag}>";
        }
        $output .= "</{$itemtag}>";
        if ( $columns > 0 && ++$i % $columns == 0 )
            $output .= '<br style="clear: both" />';
    }

    $output .= "
            <br style='clear: both;' />
        </div>\n";

    return $output;
}

Обновление:

// FB Comment Count (by Zack Austin)
function fb_comment_count($link = 'link', $post) {
  $url = 'https://graph.facebook.com/';
  $posturl = get_permalink($post->ID);
  $url .= $posturl;

  $filecontent = wp_remote_retrieve_body(wp_remote_get($url, array('sslverify'=>false)));
  $json = json_decode($filecontent);
  $count = $json->comments;
  if ($count == 0 || !isset($count)) {
    $count = 0;
  }

  $comments = $count;
  if ($count == 1) {
    $comments .= '';
  }
  elseif ($count == 0) {
    $comments = '0';
  }
  elseif ($count > 1) {
    $comments .= '';
  }
  if ($link == 'nolink') {
    return $comments;
  }
  else {
    return '<a href="'.$posturl.'#comments" title="Comments for '.$post->post_title.'">'.$comments.'</a>';
  }
}

// Custom Gallery
add_filter( 'post_gallery', 'my_post_gallery', 10, 2 );
function my_post_gallery( $output, $attr) {
    global $post, $wp_locale;

    static $instance = 0;
    $instance++;

    // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
    if ( isset( $attr['orderby'] ) ) {
        $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
        if ( !$attr['orderby'] )
            unset( $attr['orderby'] );
    }

    extract(shortcode_atts(array(
        'order'      => 'ASC',
        'orderby'    => 'menu_order ID',
        'id'         => $post->ID,
        'itemtag'    => 'dl',
        'icontag'    => 'dt',
        'captiontag' => 'dd',
        'columns'    => 3,
        'size'       => 'thumbnail',
        'include'    => '',
        'exclude'    => ''
    ), $attr));

    $id = intval($id);
    if ( 'RAND' == $order )
        $orderby = 'none';

    if ( !empty($include) ) {
        $include = preg_replace( '/[^0-9,]+/', '', $include );
        $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

        $attachments = array();
        foreach ( $_attachments as $key => $val ) {
            $attachments[$val->ID] = $_attachments[$key];
        }
    } elseif ( !empty($exclude) ) {
        $exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
        $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    } else {
        $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    }

    if ( empty($attachments) )
        return '';

    if ( is_feed() ) {
        $output = "\n";
        foreach ( $attachments as $att_id => $attachment )
            $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
        return $output;
    }

    $itemtag = tag_escape($itemtag);
    $captiontag = tag_escape($captiontag);
    $columns = intval($columns);
    $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
    $float = is_rtl() ? 'right' : 'left';

    $selector = "gallery-{$instance}";

    $output = apply_filters('gallery_style', "
        <style type='text/css'>
            #{$selector} {
                margin: auto;
            }
            #{$selector} .gallery-item {
                float: {$float};
                margin-top: 10px;
                text-align: center;
                width: {$itemwidth}%;           }
            #{$selector} img {
                border: 2px solid #cfcfcf;
            }
            #{$selector} .gallery-caption {
                margin-left: 0;
            }
        </style>
        <!-- see gallery_shortcode() in wp-includes/media.php -->
        <div id='$selector' class='gallery galleryid-{$id}'>");

    $i = 0;
    foreach ( $attachments as $att_id => $attachment ) {
        $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);

        $output .= "<{$itemtag} class='gallery-item'>";
        $output .= "<span class='photos-comment-number-wrap'><span class='comment-number'>". fb_comment_count('link', $attachment) ."</span></span>";
        $output .= "
            <{$icontag} class='gallery-icon'>
                $link
            </{$icontag}>";
        $output .= "</{$itemtag}>";
        if ( $columns > 0 && ++$i % $columns == 0 )
            $output .= '<br style="clear: both" />';
    }

    $output .= "
            <br style='clear: both;' />
        </div>\n";

    return $output;
}

Ответы [ 2 ]

0 голосов
/ 21 июля 2011

Вы можете сделать функцию fb_comment_count вызовом необязательной переменной, здесь я назову ее $ id, которая будет содержать идентификатор вложения (необязательно, чтобы не нарушать функцию в других областях сайта). Затем с этим идентификатором мы можем получить URL страницы вложения с помощью get_attachment_link, на этой странице мы найдем комментарии для вложения. Код должен быть примерно таким:

<?php
// FB Comment Count (by Zack Austin)
// Changes by Bruno Cantuaria (bruno@cantuaria.net.br)
function fb_comment_count($link = 'link', $id = 0) {
    global $post;

    $url = 'https://graph.facebook.com/';
    if ($id > 0)
        $posturl = get_attachment_link($id);
    else
        $posturl = get_permalink($post->ID);
    $url .= $posturl;

    $filecontent = wp_remote_retrieve_body(wp_remote_get($url, array('sslverify'=>false)));
    $json = json_decode($filecontent);
    $count = $json->comments;
    if ($count == 0 || !isset($count)) {
    $count = 0;
    }

    $comments = $count;
    if ($count == 1) {
    $comments .= '';
    }
    elseif ($count == 0) {
    $comments = '0';
    }
    elseif ($count > 1) {
    $comments .= '';
    }
    if ($link == 'nolink') {
    return $comments;
    }
    else {
    return '<a href="'.$posturl.'#comments" title="Comments for '.$post->post_title.'">'.$comments.'</a>';
    }
}

// Custom Gallery
add_filter( 'post_gallery', 'my_post_gallery', 10, 2 );
function my_post_gallery( $output, $attr) {
    global $post, $wp_locale;

    static $instance = 0;
    $instance++;

    // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
    if ( isset( $attr['orderby'] ) ) {
        $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
        if ( !$attr['orderby'] )
            unset( $attr['orderby'] );
    }

    extract(shortcode_atts(array(
        'order'      => 'ASC',
        'orderby'    => 'menu_order ID',
        'id'         => $post->ID,
        'itemtag'    => 'dl',
        'icontag'    => 'dt',
        'captiontag' => 'dd',
        'columns'    => 3,
        'size'       => 'thumbnail',
        'include'    => '',
        'exclude'    => ''
    ), $attr));

    $id = intval($id);
    if ( 'RAND' == $order )
        $orderby = 'none';

    if ( !empty($include) ) {
        $include = preg_replace( '/[^0-9,]+/', '', $include );
        $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

        $attachments = array();
        foreach ( $_attachments as $key => $val ) {
            $attachments[$val->ID] = $_attachments[$key];
        }
    } elseif ( !empty($exclude) ) {
        $exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
        $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    } else {
        $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    }

    if ( empty($attachments) )
        return '';

    if ( is_feed() ) {
        $output = "\n";
        foreach ( $attachments as $att_id => $attachment )
            $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
        return $output;
    }

    $itemtag = tag_escape($itemtag);
    $captiontag = tag_escape($captiontag);
    $columns = intval($columns);
    $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
    $float = is_rtl() ? 'right' : 'left';

    $selector = "gallery-{$instance}";

    $output = apply_filters('gallery_style', "
        <style type='text/css'>
            #{$selector} {
                margin: auto;
            }
            #{$selector} .gallery-item {
                float: {$float};
                margin-top: 10px;
                text-align: center;
                width: {$itemwidth}%;           }
            #{$selector} img {
                border: 2px solid #cfcfcf;
            }
            #{$selector} .gallery-caption {
                margin-left: 0;
            }
        </style>
        <!-- see gallery_shortcode() in wp-includes/media.php -->
        <div id='$selector' class='gallery galleryid-{$id}'>");

    $i = 0;
    foreach ($attachments as $id => $attachment) {
        $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);

        $output .= "<{$itemtag} class='gallery-item'>";
        $output .= "<span class='photos-comment-number-wrap'><span class='comment-number'>". fb_comment_count('link', $id) ."</span></span>";
        $output .= "
            <{$icontag} class='gallery-icon'>
                $link
            </{$icontag}>";
        $output .= "</{$itemtag}>";
        if ( $columns > 0 && ++$i % $columns == 0 )
            $output .= '<br style="clear: both" />';
    }

    $output .= "
            <br style='clear: both;' />
        </div>\n";

    return $output;
}
?>
0 голосов
/ 21 июля 2011

Вы должны вызвать function fb_comment_count($link = 'link') { и передать объект поста atachemnt, чтобы он выглядел как function fb_comment_count($link = 'link', $post) {, а удалить global $post сразу после.

это должно быть вызваноиз цикла foreach, который генерирует галерею, просто здесь:

 foreach ( $attachments as $att_id => $attachment )
       fb_comment_count('link', $attachment);

Кроме того, вы действительно должны опубликовать вопрос WordPress на wordpress.stackexchange.com

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...