javascript - 在首页上显示帖子中的小部件

标签 javascript php jquery wordpress shortcode

在我的每篇帖子中,我都在其中放置了一个商店帖子小部件。下面提供了 post widget 插件 php 的商店。有了这个插件,你只需在你的帖子 html 中放置一个简短的代码。 (商店小部件网站在生成小部件后为您提供此代码)

您可以放入帖子 html 中的示例短代码 - [show_shopthepost_widget id="2371382"]

小部件的外观 -

enter image description here

我想要发生的是让商店的帖子小部件出现在我的首页上的帖子标题和摘录下方。我尝试通过添加 echo do_shortcode() 来做到这一点。但这没有用。有人有解决办法吗?我很困惑,希望得到任何帮助。

*我将为每个帖子使用不同的小部件 ID,因为每个帖子都有不同的商店帖子小部件。

所以我的首页帖子预览看起来像这样 - enter image description here

这里是插件代码(我用于小部件的网站有许多其他购物小部件,例如精品店和产品目录,这就是为什么除了商店帖子小部件之外,您还会看到一些其他小部件,这就是我的内容)我正在工作)

<?php
/*
Plugin Name: rewardStyle Widget
Plugin URI: http://www.rewardstyle.com
Description: The rewardStyle plugin allows bloggers to use rewardStyle widgets on their WordPress blog
Author: rewardStyle
Author URI: http://www.rewardstyle.com
Version: 1.53
*/

require 'plugin-updates/plugin-update-checker.php';
$ExampleUpdateChecker = new PluginUpdateChecker_1_5(
    'http://www.rewardstyle.com/assets/info.json',
    __FILE__,
    'rewardstyle-widgets',
    1
);

/**
 * Add these to the KSES 'Allowed Post Tags' global
 * var. Keeps these tags from being removed in the
 * save/update process.
 */
$GLOBALS['allowedposttags']['iframe'] = array(
    'id'           => TRUE,
    'class'        => TRUE,
    'title'        => TRUE,
    'style'        => TRUE,
    'align'        => TRUE,
    'frameborder'  => TRUE,
    'height'       => TRUE,
    'longdesc'     => TRUE,
    'marginheight' => TRUE,
    'marginwidth'  => TRUE,
    'name'         => TRUE,
    'scrolling'    => TRUE,
    'src'          => TRUE,
    'width'        => TRUE
);
$GLOBALS['allowedposttags']['script'] = array(
    'id'    => TRUE,
    'class' => TRUE,
    'src'   => TRUE,
    'type'  => TRUE,
    'name'  => TRUE
);

/**
 * Add these to the Tiny MCE whitelist of acceptable Tags.
 * This keeps the values available when loading the page,
 * and when switching from Visual/Text Tabs
 */
function unfilter_iframe($initArray) {
  if (isset($initArray['extended_valid_elements'])) {
    $initArray['extended_valid_elements'] .= ",+iframe[id|class|title|style|align|frameborder|height|longdesc|marginheight|marginwidth|name|scrolling|src|width]";
  }
  else {
    $initArray['extended_valid_elements'] = "+iframe[id|class|title|style|align|frameborder|height|longdesc|marginheight|marginwidth|name|scrolling|src|width]";
  }
  return $initArray;
}
function unfilter_script($initArray) {
  if (isset($initArray['extended_valid_elements'])) {
    $initArray['extended_valid_elements'] .= ",+script[id|class|src|type|name]";
  }
  else {
    $initArray['extended_valid_elements'] = "+script[id|class|src|type|name]";
  }
  return $initArray;
}
add_filter('tiny_mce_before_init', 'unfilter_iframe');
add_filter('tiny_mce_before_init', 'unfilter_script');

// Add shortcode support to completely bypass the iframe filter
add_shortcode( 'show_rs_widget', 'rs_show_widget');
function rs_show_widget($atts, $content = null) {
    extract(shortcode_atts(array(
        'wid' => '',
        'blog' => '',
        'product_ids' => '',
        'rows' => '',
        'cols' => '',
        'brand' => '',
        'price' => '',
        'hover' => ''
    ), $atts));

$h = $rows * 120;
$w = ($cols * 110) + 50;

$magic_num = 0;
$how_tall = '120';
$prod_box = 'show';
if ($brand == 1) {
    $magic_num++;
}
if ($price == 1) {
    $magic_num++;
}
if ($hover == 1) {
    $magic_num = 0;
    $prod_box = 'hover-info';
}
if ($magic_num == 1) {
    $how_tall = '162';
} else if ($magic_num == 2) {
    $how_tall = '195';
}

$out = "<div style='width: ".$w."px; height: ".$how_tall."px; margin: 0px auto; background:white;'>
           <iframe frameborder='0' width='".$w."px' height='".$how_tall."px' scrolling='no' src='http://currentlyobsessed.me/api/v1/get_widget?wid=".$wid."&blog=".$blog."&product_ids=".$product_ids."&rows=".$rows."&cols=".$cols."&brand=".$brand."&price=".$price."&hover=".$hover."'></iframe>
        </div>";

return $out;
}

function ms_show_widget($atts) {
    extract(shortcode_atts(array(
        'id'       => '0',
        'image_id' => '0',
        'width'    => '0',
        'height'   => '0',
        'adblock'  => 'Disable your ad blocking software to view this content.',
        'enableJs' => 'JavaScript is currently disabled in this browser.  Reactivate it to view this content.'
    ), $atts));

    $out = '<div class="moneyspot-widget" data-widget-id="'.$id.'">
                <script type="text/javascript" language="javascript">
                    !function(d,s,id){
                        var e, p = /^http:/.test(d.location) ? \'http\' : \'https\';
                        if(!d.getElementById(id)) {
                            e     = d.createElement(s);
                            e.id  = id;
                            e.src = p + \'://widgets.rewardstyle.com/js/widget.js\';
                            d.body.appendChild(e);
                        }
                        if(typeof(window.__moneyspot) === \'object\') {
                            if(document.readyState === \'complete\') {
                                window.__moneyspot.init();
                            }
                        }
                    }(document, \'script\', \'moneyspot-script\');
                </script>
                <div class="rs-adblock">
                    <img src="//images.rewardstyle.com/img?v=2.11&ms='.$id.'&aspect" onerror="this.parentNode.innerHTML=\'Turn off your ad blocker to view content\'" />
                    <noscript>'.$enableJs.'</noscript>
                </div>
            </div>';

    return $out;
}
add_shortcode('show_ms_widget', 'ms_show_widget');

function ltk_show_widget($atts) {
    extract(shortcode_atts(array(
        'user_id'    => '0',
        'rows'       => '1',
        'cols'       => '6',
        'show_frame' => 'true',
        'padding'    => '0'
    ), $atts));

    $out = '<div class="ltkwidget-widget" data-rows="'.$rows.'" data-cols="'.$cols.'" data-show-frame="'.$show_frame.'" data-user-id="'.$user_id.'" data-padding="'.$padding.'">
                <script type="text/javascript" language="javascript">
                    !function(d,s,id){
                        var e, p = /^http:/.test(d.location) ? \'http\' : \'https\';
                        if(!d.getElementById(id)) {
                            e     = d.createElement(s);
                            e.id  = id;
                            e.src = p + \'://widgets.rewardstyle.com/js/ltkwidget.js\';
                            d.body.appendChild(e);
                        }
                    }(document, \'script\', \'ltkwidget-script\');
                    if(typeof(window.__ltkwidget) === \'object\'){
                        if (document.readyState === \'complete\') {
                            __ltkwidget.init();
                        }
                    }
                </script>
                <div class="rs-adblock">
                    <img src="//assets.rewardstyle.com/images/search/350.gif" onerror="this.parentNode.innerHTML=\''.$adblock.'\'" />
                    <noscript>'.$enableJs.'</noscript>
                </div>
            </div>';
    return $out;
}
add_shortcode('show_ltk_widget', 'ltk_show_widget');

function ltk_widget_version_two($atts) {
    extract(shortcode_atts(array(
        'app_id'     => '0',
        'user_id'    => '0',
        'rows'       => '1',
        'cols'       => '6',
        'show_frame' => 'true',
        'padding'    => '0'
    ), $atts));
    $out = '<div id="ltkwidget-version-two'.$app_id.'" data-appid="'.$app_id.'" class="ltkwidget-version-two">
                <script>var rsLTKLoadApp="0",rsLTKPassedAppID="'.$app_id.'";</script>
                <script type="text/javascript" src="//widgets-static.rewardstyle.com/widgets2_0/client/pub/ltkwidget/ltkwidget.js"></script>
                <div widget-dashboard-settings="" data-appid="'.$app_id.'" data-userid="'.$user_id.'" data-rows="'.$rows.'" data-cols="'.$cols.'" data-showframe="'.$show_frame.'" data-padding="'.$padding.'">
                    <div class="rs-ltkwidget-container">
                        <div ui-view=""></div>
                    </div>
                </div>
            </div>';
    return $out;
}
add_shortcode('show_ltk_widget_version_two', 'ltk_widget_version_two');

function lookbook_show_widget($atts) {
    extract(shortcode_atts(array(
        'id'    => '0',
        'adblock'  => 'Turn off your ad blocker to view content',
        'enableJs' => 'Turn on your JavaScript to view content'
    ), $atts));

    $out = '<div class="lookbook-widget" data-widget-id="'.$id.'">
                <script type="text/javascript" language="javascript">
                    !function(d,s,id){
                        var e, p = /^http:/.test(d.location) ? \'http\' : \'https\';
                        if(!d.getElementById(id)) {
                            e     = d.createElement(s);
                            e.id  = id;
                            e.src = p + \'://widgets.rewardstyle.com/js/lookbook.js\';
                            d.body.appendChild(e);
                        }
                        if(typeof(window.__lookbook) === \'object\') if(d.readyState === \'complete\') {
                            window.__lookbook.init();
                        }
                    }(document, \'script\', \'lookbook-script\');
                </script>
                <div class="rs-adblock">
                    <img src="//assets.rewardstyle.com/images/search/350.gif" style="width:15px;height:15px;" onerror="this.parentNode.innerHTML=\''.$adblock.'\'" />
                    <noscript>'.$enableJs.'</noscript>
                </div>
            </div>';
    return $out;
}
add_shortcode('show_lookbook_widget', 'lookbook_show_widget');

function shopthepost_show_widget($atts) {
    extract(shortcode_atts(array(
        'id'    => '0',
        'adblock'  => 'Turn off your ad blocker to view content',
        'enableJs' => 'Turn on your JavaScript to view content'
    ), $atts));

    $out = '<div class="shopthepost-widget" data-widget-id="'.$id.'">
                <script type="text/javascript" language="javascript">
                    !function(d,s,id){
                        var e, p = /^http:/.test(d.location) ? \'http\' : \'https\';
                        if(!d.getElementById(id)) {
                            e     = d.createElement(s);
                            e.id  = id;
                            e.src = p + \'://widgets.rewardstyle.com/js/shopthepost.js\';
                            d.body.appendChild(e);
                        }
                        if(typeof window.__stp === \'object\') if(d.readyState === \'complete\') {
                            window.__stp.init();
                        }
                    }(document, \'script\', \'shopthepost-script\');
                </script>
                <div class="rs-adblock">
                    <img src="//assets.rewardstyle.com/images/search/350.gif" style="width:15px;height:15px;" onerror="this.parentNode.innerHTML=\''.$adblock.'\'" />
                    <noscript>'.$enableJs.'</noscript>
                </div>
            </div>';
    return $out;
}
add_shortcode('show_shopthepost_widget', 'shopthepost_show_widget');

function boutique_show_widget($atts) {
    extract(shortcode_atts(array(
        'id'    => '0',
        'adblock'  => 'Turn off your ad blocker to view content',
        'enableJs' => 'Turn on your JavaScript to view content'
    ), $atts));

    $out = '<div class="boutique-widget" data-widget-id="'.$id.'">
                <script type="text/javascript" language="javascript">
                    !function(d,s,id){
                        var e, p = /^http:/.test(d.location) ? \'http\' : \'https\';
                        if(!d.getElementById(id)) {
                            e     = d.createElement(s);
                            e.id  = id;
                            e.src = p + \'://widgets.rewardstyle.com/js/boutique.js\';
                            d.body.appendChild(e);
                        }
                        if(typeof window.__boutique === \'object\') if(d.readyState === \'complete\') {
                            window.__boutique.init();
                        }
                    }(document, \'script\', \'boutique-script\');
                </script>
                <div class="rs-adblock">
                    <img src="//assets.rewardstyle.com/images/search/350.gif" style="width:15px;height:15px;" onerror="this.parentNode.innerHTML=\''.$adblock.'\'" />
                    <noscript>'.$enableJs.'</noscript>
                </div>
            </div>';
    return $out;
}
add_shortcode('show_boutique_widget', 'boutique_show_widget');

add_filter('widget_text', 'do_shortcode');
add_filter('the_excerpt', 'do_shortcode');

?>

然后是我的 front-page.php

<?php
/*
 * Template Name:
 */

get_header();
get_template_part ('inc/carousel');

$the_query = new WP_Query( [
    'posts_per_page' => 14,
    'paged' => get_query_var('paged', 1)
] );

if ( $the_query->have_posts() ) { ?>
    <div id="ajax">
    <?php
    $i = 0;
    while ( $the_query->have_posts() ) { $the_query->the_post();

        if ( $i % 7 === 0 ) { // Large post: on the first iteration and every 7th post after... ?>
        <article <?php post_class( 'col-sm-12 col-md-12' ); ?>>
            <div class="large-front-container">
<?php the_post_thumbnail('full', array('class' => 'large-front-thumbnail')); ?>
                </div>
            <h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
            <div class="front-post-info">
            <a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
                <?php get_template_part ('front-page-shop'); ?>
                                 <?php get_template_part( 'share-buttons' ); ?>
                <div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
                <?php echo do_shortcode("show_shopthepost_widget"); ?>
            </article><?php

        } else { // Small posts ?>
            <article <?php post_class( 'col-sm-6 col-md-4' ); ?>>
                <div class="front-thumbnail-image"><?php the_post_thumbnail('full', array('class' => 'medium-front-thumbnail')); ?></div>
                <a class="front-page-post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
                <a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
                <?php get_template_part ('front-page-shop'); ?>
                                 <?php get_template_part( 'share-buttons' ); ?>
                <div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
             <?php echo do_shortcode("show_shopthepost_widget"); ?>
            </article>
            <?php
        }
        $i++;
    }?>
    </div>
    <?php if(get_query_var('paged') < $the_query->max_num_pages) {
       load_more_button();
    }
}
elseif (!get_query_var('paged') || get_query_var('paged') == '1') {
    echo '<p>Sorry, no posts matched your criteria.</p>';
}
wp_reset_postdata();
get_footer();

更新了 front-page.php

<?php
/*
 * Template Name:
 */

get_header();
get_template_part ('inc/carousel');

$the_query = new WP_Query( [
    'posts_per_page' => 14,
    'paged' => get_query_var('paged', 1)
] );

if ( $the_query->have_posts() ) { ?>
    <div id="ajax">
    <?php
    $i = 0;
    while ( $the_query->have_posts() ) { $the_query->the_post();

        if ( $i % 7 === 0 ) { // Large post: on the first iteration and every 7th post after... ?>
        <article <?php post_class( 'col-sm-12 col-md-12' ); ?>>
            <div class="large-front-container">
<?php the_post_thumbnail('full', array('class' => 'large-front-thumbnail')); ?>
                </div>
            <h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
            <div class="front-post-info">
            <a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
                <?php get_template_part ('front-page-shop'); ?>
                                 <?php get_template_part( 'share-buttons' ); ?>
                <div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
                <?php echo do_shortcode("show_shopthepost_widget"); ?>
                <?php if (shortcode_exists('show_shopthepost_widget')) {

    // Get the value of the custom field defined in the editor
    $widgetId = get_post_meta(get_the_ID(), 'shortcode_id', true);

    // Check if a value is set
    if (!empty($widgetId)) {

        $shortcode = '[show_shopthepost_widget id="'.$widgetId.'"]';

    } else {

        // or use a default widget
        $shortcode = '[show_shopthepost_widget id="12345_some_id"]';
    }

    do_shortcode($shortcode);
} ?>
            </article><?php

        } else { // Small posts ?>
            <article <?php post_class( 'col-sm-6 col-md-4' ); ?>>
                <div class="front-thumbnail-image"><?php the_post_thumbnail('full', array('class' => 'medium-front-thumbnail')); ?></div>
                <a class="front-page-post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
                <a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
                <?php get_template_part ('front-page-shop'); ?>
                                 <?php get_template_part( 'share-buttons' ); ?>
                <div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
             <?php if (shortcode_exists('show_shopthepost_widget')) {

    // Get the value of the custom field defined in the editor
    $widgetId = get_post_meta(get_the_ID(), 'shortcode_id', true);

    // Check if a value is set
    if (!empty($widgetId)) {

        $shortcode = '[show_shopthepost_widget id="'.$widgetId.'"]';

    } else {

        // or use a default widget
        $shortcode = '[show_shopthepost_widget id="12345_some_id"]';
    }

    do_shortcode($shortcode);
} ?>
            </article>
            <?php
        }
        $i++;
    }?>
    </div>
    <?php if(get_query_var('paged') < $the_query->max_num_pages) {
       load_more_button();
    }
}
elseif (!get_query_var('paged') || get_query_var('paged') == '1') {
    echo '<p>Sorry, no posts matched your criteria.</p>';
}
wp_reset_postdata();
get_footer();

最佳答案

实际上,do_shortcode()正是您所需要的,只是您需要按原样输入整个短代码,而不对其进行更改(即删除 [])

这应该可以很好地显示上面的小部件:

echo do_shortcode('[show_shopthepost_widget id="2371382"]');

此外,我建议将其包装在 shortcode_exists() 中检查,否则如果插件因任何原因被禁用或不可用,它会在页面上吐出短代码。 请注意,此函数需要传递不带 [] 的短代码。

if (shortcode_exists('show_shopthepost_widget')) {

    echo do_shortcode('[show_shopthepost_widget id="2371382"]');
}

Wordpress Stack Exchange如果您一直在使用 WP,网站可能会为您提供更多答案。希望这有帮助!

编辑

动态解决方案

如果您需要在每个页面上显示不同的短代码,您可以修改上述代码以使用自定义字段来显示与页面关联的任何小部件,或者如果您未设置任何小部件,则显示默认小部件。

在内容编辑器中

为此,您需要在网站的 wp-adminadd a custom field 中编辑页面。向他们提供您想要在页面上显示的小部件的 ID,并将其命名为诸如 shortcode_id 之类的合理名称。

在你的主题中

您需要修改逻辑以使用与当前页面关联的 shortcode_id 键获取帖子元,并创建要相应显示的短代码。此外,您还可以设置一个默认小部件,如果您没有为页面设置任何小部件,则会显示该默认小部件。

if (shortcode_exists('show_shopthepost_widget')) {

    // Get the value of the custom field defined in the editor
    $widgetId = get_post_meta(get_the_ID(), 'shortcode_id', true);

    // Check if a value is set
    if (!empty($widgetId)) {

        $shortcode = '[show_shopthepost_widget id="'.$widgetId.'"]';

    } else {

        // or use a default widget
        $shortcode = '[show_shopthepost_widget id="12345_some_id"]';
    }

    echo do_shortcode($shortcode);
}

关于javascript - 在首页上显示帖子中的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41898308/

相关文章:

javascript - 如何在删除字段时计算输入字段值并将其分配给另一个字段

php - 投影mySQL数据库,如何处理多类别

javascript - 当您想要搜索具有特定值的多个 HtmlObject 时,哪种 JavaScript 代码更有效?

jquery - 在 jQuery 中添加带有 for 循环的 div

javascript - 在 php 中上传图像时显示错误

javascript - 使用 JavaScript 调用 Shell 脚本实现自动化

javascript - Div animate 消失,而不是调整大小

php - 在 Android 中将 Retrofit 发布到 Rest 服务器

php - 注册 PHP session 变量

javascript - 用于加载更多内容的 Jquery 代码不起作用