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
235,599
<p>I'm trying to have a Bootsrap carousel to display my post -</p> <p>They are being display, However, it doesn't work correctly. It doesn't slide basically....</p> <p>Here is the live example:</p> <p><a href="http://latitudesadventure.co.uk/novocore/dusty-oak/" rel="nofollow">http://latitudesadventure.co.uk/novocore/dusty-oak/</a></p> <p>I'm using the code below:</p> <pre><code>&lt;div id="myCarousel" class="carousel slide"&gt; &lt;!-- Carousel items --&gt; &lt;div class="carousel-inner"&gt; &lt;?php $my_query = new WP_Query('posts_per_page=5'); while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); $do_not_duplicate = $post-&gt;ID;?&gt; &lt;!-- The 1st Loop... --&gt; &lt;div class="active item well-blue"&gt; &lt;div class="offset1"&gt; &lt;div class="carousel-image"&gt; &lt;?php if (class_exists('MultiPostThumbnails')) : MultiPostThumbnails::the_post_thumbnail(get_post_type(), 'secondary-image'); endif; ?&gt; &lt;/div&gt; &lt;h3 style="color:white;text-align:center"&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;h3 style="color:white;text-align:center"&gt; &lt;?php the_field( "number" ); ?&gt;&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; // The 2nd Loop limits the query to 2 more posts... $limit_query = new WP_Query('posts_per_page=2'); if($limit_query-&gt;have_posts()) : while ($limit_query-&gt;have_posts()) : $limit_query-&gt;the_post(); if( $post-&gt;ID == $do_not_duplicate ) continue; ?&gt; &lt;!-- The 2nd Loop same data as 1st loop --&gt; &lt;?php endwhile; endif; wp_reset_query(); ?&gt; &lt;/div&gt; &lt;!-- Carousel nav --&gt; &lt;a class="carousel-control left" href="#myCarousel" data-slide="prev"&gt;&amp;lsaquo;&lt;/a&gt; &lt;a class="carousel-control right" href="#myCarousel" data-slide="next"&gt;&amp;rsaquo;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>If i select 'post_per-page=1' they all display ( in two rows) however, it still doesn't slide - I would like all the post to be display - sliding one by one with a current status but nothing to do, it doesn't work.</p> <p>Any help will be amazing,</p> <p>thank you !</p>
[ { "answer_id": 235751, "author": "pallavi", "author_id": 96726, "author_profile": "https://wordpress.stackexchange.com/users/96726", "pm_score": 1, "selected": false, "text": "<p>You have added active class in all slides. Due to this all slides is displaying. You have to add active class to first slides only. Check below bootstrap slider code-</p>\n\n<pre><code>&lt;div class=\"carousel-inner\" role=\"listbox\"&gt;\n &lt;div class=\"item active\"&gt;\n &lt;img src=\"...\" alt=\"...\"&gt;\n &lt;div class=\"carousel-caption\"&gt;\n ...\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"item\"&gt;\n &lt;img src=\"...\" alt=\"...\"&gt;\n &lt;div class=\"carousel-caption\"&gt;\n ...\n &lt;/div&gt;\n &lt;/div&gt;\n ...\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 235757, "author": "bagpipper", "author_id": 80397, "author_profile": "https://wordpress.stackexchange.com/users/80397", "pm_score": 0, "selected": false, "text": "<pre><code> &lt;div id=\"myCarousel\" class=\"carousel slide\"&gt;\n &lt;!-- Carousel items --&gt;\n&lt;div class=\"carousel-inner\"&gt;\n&lt;?php \n $my_query = new WP_Query('posts_per_page=5');\n $count=1;\n while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post();\n $do_not_duplicate = $post-&gt;ID;\n$active= ($count==1? 'active' : '');// this is to add active to the first slider\n ?&gt;\n &lt;!-- The 1st Loop... --&gt;\n &lt;div class=\"&lt;?php echo $active ?&gt; item well-blue\"&gt;\n &lt;div class=\"offset1\"&gt; \n &lt;div class=\"carousel-image\"&gt;\n &lt;?php \n $count++;\n\n\nif (class_exists('MultiPostThumbnails')) : \n\nMultiPostThumbnails::the_post_thumbnail(get_post_type(), 'secondary-image');\n\nendif;\n\n ?&gt;\n &lt;/div&gt;\n\n &lt;h3 style=\"color:white;text-align:center\"&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;\n &lt;h3 style=\"color:white;text-align:center\"&gt; &lt;?php the_field( \"number\" ); ?&gt;&lt;/h3&gt;\n &lt;/div&gt; \n &lt;/div&gt;\n&lt;?php endwhile;\n // The 2nd Loop limits the query to 2 more posts...\n$limit_query = new WP_Query('posts_per_page=2');\nif($limit_query-&gt;have_posts()) : while ($limit_query-&gt;have_posts()) : $limit_query-&gt;the_post(); \nif( $post-&gt;ID == $do_not_duplicate ) continue; ?&gt;\n&lt;!-- The 2nd Loop same data as 1st loop --&gt;\n&lt;?php endwhile; endif; wp_reset_query(); ?&gt;\n &lt;/div&gt;\n &lt;!-- Carousel nav --&gt;\n &lt;a class=\"carousel-control left\" href=\"#myCarousel\" data-slide=\"prev\"&gt;&amp;lsaquo;&lt;/a&gt;\n &lt;a class=\"carousel-control right\" href=\"#myCarousel\" data-slide=\"next\"&gt;&amp;rsaquo;&lt;/a&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>I have added a counter to add active class only to your first slide. This should work let me know if it works or not</p>\n" } ]
2016/08/10
[ "https://wordpress.stackexchange.com/questions/235599", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54146/" ]
I'm trying to have a Bootsrap carousel to display my post - They are being display, However, it doesn't work correctly. It doesn't slide basically.... Here is the live example: <http://latitudesadventure.co.uk/novocore/dusty-oak/> I'm using the code below: ``` <div id="myCarousel" class="carousel slide"> <!-- Carousel items --> <div class="carousel-inner"> <?php $my_query = new WP_Query('posts_per_page=5'); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID;?> <!-- The 1st Loop... --> <div class="active item well-blue"> <div class="offset1"> <div class="carousel-image"> <?php if (class_exists('MultiPostThumbnails')) : MultiPostThumbnails::the_post_thumbnail(get_post_type(), 'secondary-image'); endif; ?> </div> <h3 style="color:white;text-align:center"><?php the_title(); ?></h3> <h3 style="color:white;text-align:center"> <?php the_field( "number" ); ?></h3> </div> </div> <?php endwhile; // The 2nd Loop limits the query to 2 more posts... $limit_query = new WP_Query('posts_per_page=2'); if($limit_query->have_posts()) : while ($limit_query->have_posts()) : $limit_query->the_post(); if( $post->ID == $do_not_duplicate ) continue; ?> <!-- The 2nd Loop same data as 1st loop --> <?php endwhile; endif; wp_reset_query(); ?> </div> <!-- Carousel nav --> <a class="carousel-control left" href="#myCarousel" data-slide="prev">&lsaquo;</a> <a class="carousel-control right" href="#myCarousel" data-slide="next">&rsaquo;</a> </div> ``` If i select 'post\_per-page=1' they all display ( in two rows) however, it still doesn't slide - I would like all the post to be display - sliding one by one with a current status but nothing to do, it doesn't work. Any help will be amazing, thank you !
You have added active class in all slides. Due to this all slides is displaying. You have to add active class to first slides only. Check below bootstrap slider code- ``` <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="..." alt="..."> <div class="carousel-caption"> ... </div> </div> <div class="item"> <img src="..." alt="..."> <div class="carousel-caption"> ... </div> </div> ... </div> ```
235,602
<p>I want to end up with url structure for galleries like the one below ; </p> <p><a href="http://myurl.com/gallery-name/gallery-item-name" rel="nofollow">http://myurl.com/gallery-name/gallery-item-name</a></p> <p>as you see there will be two variables. </p> <p>I separated templates like content-default and content-gallery.. So far it's OK. But what should i do to open a single gallery element page when user goes to this link?</p>
[ { "answer_id": 235751, "author": "pallavi", "author_id": 96726, "author_profile": "https://wordpress.stackexchange.com/users/96726", "pm_score": 1, "selected": false, "text": "<p>You have added active class in all slides. Due to this all slides is displaying. You have to add active class to first slides only. Check below bootstrap slider code-</p>\n\n<pre><code>&lt;div class=\"carousel-inner\" role=\"listbox\"&gt;\n &lt;div class=\"item active\"&gt;\n &lt;img src=\"...\" alt=\"...\"&gt;\n &lt;div class=\"carousel-caption\"&gt;\n ...\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"item\"&gt;\n &lt;img src=\"...\" alt=\"...\"&gt;\n &lt;div class=\"carousel-caption\"&gt;\n ...\n &lt;/div&gt;\n &lt;/div&gt;\n ...\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 235757, "author": "bagpipper", "author_id": 80397, "author_profile": "https://wordpress.stackexchange.com/users/80397", "pm_score": 0, "selected": false, "text": "<pre><code> &lt;div id=\"myCarousel\" class=\"carousel slide\"&gt;\n &lt;!-- Carousel items --&gt;\n&lt;div class=\"carousel-inner\"&gt;\n&lt;?php \n $my_query = new WP_Query('posts_per_page=5');\n $count=1;\n while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post();\n $do_not_duplicate = $post-&gt;ID;\n$active= ($count==1? 'active' : '');// this is to add active to the first slider\n ?&gt;\n &lt;!-- The 1st Loop... --&gt;\n &lt;div class=\"&lt;?php echo $active ?&gt; item well-blue\"&gt;\n &lt;div class=\"offset1\"&gt; \n &lt;div class=\"carousel-image\"&gt;\n &lt;?php \n $count++;\n\n\nif (class_exists('MultiPostThumbnails')) : \n\nMultiPostThumbnails::the_post_thumbnail(get_post_type(), 'secondary-image');\n\nendif;\n\n ?&gt;\n &lt;/div&gt;\n\n &lt;h3 style=\"color:white;text-align:center\"&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;\n &lt;h3 style=\"color:white;text-align:center\"&gt; &lt;?php the_field( \"number\" ); ?&gt;&lt;/h3&gt;\n &lt;/div&gt; \n &lt;/div&gt;\n&lt;?php endwhile;\n // The 2nd Loop limits the query to 2 more posts...\n$limit_query = new WP_Query('posts_per_page=2');\nif($limit_query-&gt;have_posts()) : while ($limit_query-&gt;have_posts()) : $limit_query-&gt;the_post(); \nif( $post-&gt;ID == $do_not_duplicate ) continue; ?&gt;\n&lt;!-- The 2nd Loop same data as 1st loop --&gt;\n&lt;?php endwhile; endif; wp_reset_query(); ?&gt;\n &lt;/div&gt;\n &lt;!-- Carousel nav --&gt;\n &lt;a class=\"carousel-control left\" href=\"#myCarousel\" data-slide=\"prev\"&gt;&amp;lsaquo;&lt;/a&gt;\n &lt;a class=\"carousel-control right\" href=\"#myCarousel\" data-slide=\"next\"&gt;&amp;rsaquo;&lt;/a&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>I have added a counter to add active class only to your first slide. This should work let me know if it works or not</p>\n" } ]
2016/08/10
[ "https://wordpress.stackexchange.com/questions/235602", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98843/" ]
I want to end up with url structure for galleries like the one below ; <http://myurl.com/gallery-name/gallery-item-name> as you see there will be two variables. I separated templates like content-default and content-gallery.. So far it's OK. But what should i do to open a single gallery element page when user goes to this link?
You have added active class in all slides. Due to this all slides is displaying. You have to add active class to first slides only. Check below bootstrap slider code- ``` <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="..." alt="..."> <div class="carousel-caption"> ... </div> </div> <div class="item"> <img src="..." alt="..."> <div class="carousel-caption"> ... </div> </div> ... </div> ```
235,605
<p>After each menu item, I want to add the page excerpt underneath it.</p> <p>So if i have a menu that looks like this:</p> <ul> <li>Home</li> <li>About</li> <li>Contact</li> </ul> <p>I want to get the page excerpt into the menu like this:</p> <ul> <li>Home <ul> <li>This is the home page excerpt</li> </ul></li> <li>About <ul> <li>This is the about page excerpt</li> </ul></li> <li>Contact <ul> <li>This is the contact page excerpt</li> </ul></li> </ul> <p>Can I do this using the parameters in the <code>wp_nav_menu()</code> call? Or do I have to make a custom Nav Walker?</p>
[ { "answer_id": 235606, "author": "kingkool68", "author_id": 2744, "author_profile": "https://wordpress.stackexchange.com/users/2744", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/#source\" rel=\"nofollow\">wp_nav_menu()</a> calls <a href=\"https://developer.wordpress.org/reference/functions/walk_nav_menu_tree/#source\" rel=\"nofollow\">walk_nav_menu_tree()</a> which calls the <a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/#source\" rel=\"nofollow\">Walker_Nav_Menu class</a>.</p>\n\n<p>There are a couple of filters you can hook into in those functions but I would take a look at the <code>nav_menu_item_title</code> filter in the <code>Walker_Nav_Menu</code> class. Here is the source:</p>\n\n<pre><code>/**\n* Filter a menu item's title.\n*\n* @since 4.4.0\n*\n* @param string $title The menu item's title.\n* @param object $item The current menu item.\n* @param array $args An array of {@see wp_nav_menu()} arguments.\n* @param int $depth Depth of menu item. Used for padding.\n*/\n$title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );\n</code></pre>\n\n<p>So you could write a filter like so:</p>\n\n<pre><code>function my_nav_menu_item_title( $title, $item, $args, $depth ) {\n $title .= '&lt;span class=\"excerpt\"&gt;' . $item-&gt;post_excerpt . '&lt;/span&gt;';\n return $title;\n}\nadd_filter( 'nav_menu_item_title', 'my_nav_menu_item_title', 10, 4 );\n</code></pre>\n\n<p>I haven't tested this but it should lead you in the right direction. I would inspect what is contained in <code>$item</code>.</p>\n" }, { "answer_id": 235675, "author": "user3869231", "author_id": 100857, "author_profile": "https://wordpress.stackexchange.com/users/100857", "pm_score": 1, "selected": false, "text": "<p>Solved thanks to kingkool68</p>\n\n<pre><code>function my_nav_menu_item_title( $title, $item, $args, $depth ) {\n $pid = $item-&gt;object_id;\n\n $text = get_the_excerpt($pid);\n\n $title .= '&lt;span class=\"excerpt\"&gt;' . $text . '&lt;/span&gt;';\n return $title;\n\n}\n</code></pre>\n" } ]
2016/08/11
[ "https://wordpress.stackexchange.com/questions/235605", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100817/" ]
After each menu item, I want to add the page excerpt underneath it. So if i have a menu that looks like this: * Home * About * Contact I want to get the page excerpt into the menu like this: * Home + This is the home page excerpt * About + This is the about page excerpt * Contact + This is the contact page excerpt Can I do this using the parameters in the `wp_nav_menu()` call? Or do I have to make a custom Nav Walker?
[wp\_nav\_menu()](https://developer.wordpress.org/reference/functions/wp_nav_menu/#source) calls [walk\_nav\_menu\_tree()](https://developer.wordpress.org/reference/functions/walk_nav_menu_tree/#source) which calls the [Walker\_Nav\_Menu class](https://developer.wordpress.org/reference/classes/walker_nav_menu/#source). There are a couple of filters you can hook into in those functions but I would take a look at the `nav_menu_item_title` filter in the `Walker_Nav_Menu` class. Here is the source: ``` /** * Filter a menu item's title. * * @since 4.4.0 * * @param string $title The menu item's title. * @param object $item The current menu item. * @param array $args An array of {@see wp_nav_menu()} arguments. * @param int $depth Depth of menu item. Used for padding. */ $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth ); ``` So you could write a filter like so: ``` function my_nav_menu_item_title( $title, $item, $args, $depth ) { $title .= '<span class="excerpt">' . $item->post_excerpt . '</span>'; return $title; } add_filter( 'nav_menu_item_title', 'my_nav_menu_item_title', 10, 4 ); ``` I haven't tested this but it should lead you in the right direction. I would inspect what is contained in `$item`.
235,617
<p>I'm looking into setting up a development -> staging -> production workflow, and the biggest issue so far is figuring out how to sync the databases.</p> <p>To this end, I'm trying to figure out exactly which actions will affect the filesystem, the database, or both. Here's how I think it works. Please correct me where I'm wrong, and let me know if my questionable answers are right!</p> <ul> <li>Registering a new user - database</li> <li>Adding a post or comment - database</li> <li>Changing to a new theme - database?</li> <li>Changing a theme's settings - database</li> <li>Installing or removing a plugin - filesystem</li> <li>Activating, or deactivating a plugin - filesystem</li> <li>Updating a plugin - filesystem and database? (DB structure may change?)</li> <li>Changing a plugin's settings - database</li> <li>Uploading media - filesystem and database?</li> <li>Editing custom files not included in a theme or plugin - filesystem</li> <li>Upgrading Wordpress - filesystem?</li> </ul>
[ { "answer_id": 235606, "author": "kingkool68", "author_id": 2744, "author_profile": "https://wordpress.stackexchange.com/users/2744", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/#source\" rel=\"nofollow\">wp_nav_menu()</a> calls <a href=\"https://developer.wordpress.org/reference/functions/walk_nav_menu_tree/#source\" rel=\"nofollow\">walk_nav_menu_tree()</a> which calls the <a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/#source\" rel=\"nofollow\">Walker_Nav_Menu class</a>.</p>\n\n<p>There are a couple of filters you can hook into in those functions but I would take a look at the <code>nav_menu_item_title</code> filter in the <code>Walker_Nav_Menu</code> class. Here is the source:</p>\n\n<pre><code>/**\n* Filter a menu item's title.\n*\n* @since 4.4.0\n*\n* @param string $title The menu item's title.\n* @param object $item The current menu item.\n* @param array $args An array of {@see wp_nav_menu()} arguments.\n* @param int $depth Depth of menu item. Used for padding.\n*/\n$title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );\n</code></pre>\n\n<p>So you could write a filter like so:</p>\n\n<pre><code>function my_nav_menu_item_title( $title, $item, $args, $depth ) {\n $title .= '&lt;span class=\"excerpt\"&gt;' . $item-&gt;post_excerpt . '&lt;/span&gt;';\n return $title;\n}\nadd_filter( 'nav_menu_item_title', 'my_nav_menu_item_title', 10, 4 );\n</code></pre>\n\n<p>I haven't tested this but it should lead you in the right direction. I would inspect what is contained in <code>$item</code>.</p>\n" }, { "answer_id": 235675, "author": "user3869231", "author_id": 100857, "author_profile": "https://wordpress.stackexchange.com/users/100857", "pm_score": 1, "selected": false, "text": "<p>Solved thanks to kingkool68</p>\n\n<pre><code>function my_nav_menu_item_title( $title, $item, $args, $depth ) {\n $pid = $item-&gt;object_id;\n\n $text = get_the_excerpt($pid);\n\n $title .= '&lt;span class=\"excerpt\"&gt;' . $text . '&lt;/span&gt;';\n return $title;\n\n}\n</code></pre>\n" } ]
2016/08/11
[ "https://wordpress.stackexchange.com/questions/235617", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100820/" ]
I'm looking into setting up a development -> staging -> production workflow, and the biggest issue so far is figuring out how to sync the databases. To this end, I'm trying to figure out exactly which actions will affect the filesystem, the database, or both. Here's how I think it works. Please correct me where I'm wrong, and let me know if my questionable answers are right! * Registering a new user - database * Adding a post or comment - database * Changing to a new theme - database? * Changing a theme's settings - database * Installing or removing a plugin - filesystem * Activating, or deactivating a plugin - filesystem * Updating a plugin - filesystem and database? (DB structure may change?) * Changing a plugin's settings - database * Uploading media - filesystem and database? * Editing custom files not included in a theme or plugin - filesystem * Upgrading Wordpress - filesystem?
[wp\_nav\_menu()](https://developer.wordpress.org/reference/functions/wp_nav_menu/#source) calls [walk\_nav\_menu\_tree()](https://developer.wordpress.org/reference/functions/walk_nav_menu_tree/#source) which calls the [Walker\_Nav\_Menu class](https://developer.wordpress.org/reference/classes/walker_nav_menu/#source). There are a couple of filters you can hook into in those functions but I would take a look at the `nav_menu_item_title` filter in the `Walker_Nav_Menu` class. Here is the source: ``` /** * Filter a menu item's title. * * @since 4.4.0 * * @param string $title The menu item's title. * @param object $item The current menu item. * @param array $args An array of {@see wp_nav_menu()} arguments. * @param int $depth Depth of menu item. Used for padding. */ $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth ); ``` So you could write a filter like so: ``` function my_nav_menu_item_title( $title, $item, $args, $depth ) { $title .= '<span class="excerpt">' . $item->post_excerpt . '</span>'; return $title; } add_filter( 'nav_menu_item_title', 'my_nav_menu_item_title', 10, 4 ); ``` I haven't tested this but it should lead you in the right direction. I would inspect what is contained in `$item`.
235,652
<p>What would cause a basic <code>get_posts()</code> query to return an empty array during an Ajax function?</p> <p>I have a front end page which loads a form. There is a dropdown which is populated when the page loads with some post titles. The same function that populates the select list values is called via Ajax when the value of another select list changes.</p> <p>When the function is called via Ajax, the result is an empty array. When the page loads, the select list is fully populated.</p> <p>By using<code>error_log( var_export( $args, true ), 0 );</code> I have confirmed that the arguments passed to the function are the same on both page load and Ajax call and with <code>error_log( var_export( $addons, true ), 0 );</code> I confirmed results on page load and an empty array on Ajax call. This also confirms execution of the correct function via Ajax.</p> <pre><code>/** * Retrieve all addons. * * @since 1.4 * @param arr $args Array of arguments. See @get_posts. * @return arr|bool Addons. */ function mh_get_addons( $args = array() ) { $defaults = array( 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'post_title', 'order' =&gt; 'DESC', 'post_type' =&gt; 'mh-addon', 'post_status' =&gt; 'publish' ); $args = wp_parse_args( $args, $defaults ); error_log( var_export( $args, true ), 0 ); $addons = get_posts( $args ); error_log( var_export( $addons, true ), 0 ); return apply_filters( 'mh_get_addons', $addons ); } // mh_get_addons </code></pre> <p>Here is the Ajax function. As you can see I am passing no args here whilst testing so I would expect to see the same results I do on the initial page load.</p> <pre><code>function mh_update_form_addon_options() { $addons = mh_get_addons(); if ( ! empty( $addons ) ) { $result['type'] = 'success'; $result['addons'] = $addons; } else { $result['type'] = 'success'; $result['addons'] = 'No addons'; } echo json_encode( $result ); die(); } // mh_update_form_addon_options add_action( 'wp_ajax_mh_update_form_addon_options', 'mh_update_form_addon_options' ); add_action( 'wp_ajax_nopriv_mh_update_form_addon_options', 'mh_update_form_addon_options' ); </code></pre> <p>`</p> <p><strong>UPDATE</strong> The function is now returning results via the Ajax call when a user is logged in. However, if not logged in, no results. Strange thing is that the initial call to the <code>mh_get_addons()</code> function which is initiated on page load <em>without</em> ajax returns results regardless of whether or not a user is logged in...</p>
[ { "answer_id": 235654, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 1, "selected": false, "text": "<p>To get data from AJAX call you have to <code>echo</code> or <code>print</code> it. In WordPress you should use <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json\" rel=\"nofollow\"><code>wp_send_json()</code></a> function to send data as response to call.</p>\n\n<pre><code>function mh_get_addons( $args = array() ) {\n\n $defaults = array(\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'post_title',\n 'order' =&gt; 'DESC',\n 'post_type' =&gt; 'mh-addon',\n 'post_status' =&gt; 'publish'\n );\n\n $args = wp_parse_args( $args, $defaults );\n $addons = get_posts( $args );\n wp_send_json( apply_filters( 'mh_get_addons', $addons ) );\n\n} // mh_get_addons\n</code></pre>\n" }, { "answer_id": 235776, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Instead of using the WP AJAX API, have you tried registering a REST endpoint? This assumes at least WP 4.5:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'mike/v1', '/addons/', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'mh_update_form_addon_options',\n ) );\n} );\n\n\nfunction mh_update_form_addon_options( WP_REST_Request $data ) {\n\n $defaults = array(\n 'posts_per_page' =&gt; 200,\n 'orderby' =&gt; 'post_title',\n 'order' =&gt; 'DESC',\n 'post_type' =&gt; 'mh-addon',\n 'post_status' =&gt; 'publish',\n 'suppress_filters' =&gt; false\n );\n\n $addons = get_posts( $args );\n $result = array(); \n if ( empty( $addons ) ) {\n return new WP_Error(\"No addons\");\n }\n\n return $addons;\n}\n</code></pre>\n\n<p>I've also simplified the function and eliminated some uncertainty by removing filters. I've also sped up the get_posts call by setting <code>suppress_filters</code> to false so that it caches the result. I've also added a maximum number, if you somehow ended up with 1 million addons this request would always fail, so always set an upper limit, even if it's a silly number you know it'll never reach</p>\n\n<p>Keep in mind in a REST endpoint, we return what we're sending, we don't echo it, and use <code>WP_Error</code> for problems. You can adjust the <code>register_rest_route</code> call to mention arguments, see the WP API documentation for how.</p>\n\n<p>Only WP Core is needed for this, no WP API plugin necessary</p>\n" }, { "answer_id": 293686, "author": "Christian", "author_id": 136573, "author_profile": "https://wordpress.stackexchange.com/users/136573", "pm_score": 0, "selected": false, "text": "<p>Have you tried calling the global <code>$post</code> object at the top of your <code>mh_get_addons()</code> function?</p>\n\n<pre><code>function mh_get_addons( $args = array() ) {\n\n global $post;\n\n $defaults = array(\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'post_title',\n 'order' =&gt; 'DESC',\n 'post_type' =&gt; 'mh-addon',\n 'post_status' =&gt; 'publish'\n );\n\n $args = wp_parse_args( $args, $defaults );\n error_log( var_export( $args, true ), 0 );\n $addons = get_posts( $args );\n error_log( var_export( $addons, true ), 0 );\n return apply_filters( 'mh_get_addons', $addons );\n\n }\n</code></pre>\n\n<p>I'm not quite the wordpress expert yet, but had a similar issue when using <code>get_posts($args)</code> inside a function called via wp-ajax the way you call yours, and that solved it for me. Otherwise <code>get_posts()</code> wasn't able to retrieve any of the post information, hence the empty array you're seeing.</p>\n" } ]
2016/08/11
[ "https://wordpress.stackexchange.com/questions/235652", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69112/" ]
What would cause a basic `get_posts()` query to return an empty array during an Ajax function? I have a front end page which loads a form. There is a dropdown which is populated when the page loads with some post titles. The same function that populates the select list values is called via Ajax when the value of another select list changes. When the function is called via Ajax, the result is an empty array. When the page loads, the select list is fully populated. By using`error_log( var_export( $args, true ), 0 );` I have confirmed that the arguments passed to the function are the same on both page load and Ajax call and with `error_log( var_export( $addons, true ), 0 );` I confirmed results on page load and an empty array on Ajax call. This also confirms execution of the correct function via Ajax. ``` /** * Retrieve all addons. * * @since 1.4 * @param arr $args Array of arguments. See @get_posts. * @return arr|bool Addons. */ function mh_get_addons( $args = array() ) { $defaults = array( 'posts_per_page' => -1, 'orderby' => 'post_title', 'order' => 'DESC', 'post_type' => 'mh-addon', 'post_status' => 'publish' ); $args = wp_parse_args( $args, $defaults ); error_log( var_export( $args, true ), 0 ); $addons = get_posts( $args ); error_log( var_export( $addons, true ), 0 ); return apply_filters( 'mh_get_addons', $addons ); } // mh_get_addons ``` Here is the Ajax function. As you can see I am passing no args here whilst testing so I would expect to see the same results I do on the initial page load. ``` function mh_update_form_addon_options() { $addons = mh_get_addons(); if ( ! empty( $addons ) ) { $result['type'] = 'success'; $result['addons'] = $addons; } else { $result['type'] = 'success'; $result['addons'] = 'No addons'; } echo json_encode( $result ); die(); } // mh_update_form_addon_options add_action( 'wp_ajax_mh_update_form_addon_options', 'mh_update_form_addon_options' ); add_action( 'wp_ajax_nopriv_mh_update_form_addon_options', 'mh_update_form_addon_options' ); ``` ` **UPDATE** The function is now returning results via the Ajax call when a user is logged in. However, if not logged in, no results. Strange thing is that the initial call to the `mh_get_addons()` function which is initiated on page load *without* ajax returns results regardless of whether or not a user is logged in...
To get data from AJAX call you have to `echo` or `print` it. In WordPress you should use [`wp_send_json()`](https://codex.wordpress.org/Function_Reference/wp_send_json) function to send data as response to call. ``` function mh_get_addons( $args = array() ) { $defaults = array( 'posts_per_page' => -1, 'orderby' => 'post_title', 'order' => 'DESC', 'post_type' => 'mh-addon', 'post_status' => 'publish' ); $args = wp_parse_args( $args, $defaults ); $addons = get_posts( $args ); wp_send_json( apply_filters( 'mh_get_addons', $addons ) ); } // mh_get_addons ```
235,671
<p>I've been asked to make some changes to a Wordpress site and the previous dev has displayed information from certain current pages on the homepage. </p> <p>What's confusing me is how they've managed to do this... he/she seems to have categorised certain pages by number. For example, the following WP_Query() code seems to target a set number of pages:</p> <pre><code> &lt;?php $id = get_post(41); setup_postdata($id); ?&gt; &lt;?php $args = array( 'post_parent' =&gt; $id, 'post_type' =&gt; 'page', 'hierarchical' =&gt; true, 'orderby' =&gt; 'menu_order', 'order' =&gt; 'ASC' ); $child_query = new WP_Query($args); ?&gt; </code></pre> <p>There are other WP_Query()'s throughout the page that target other posts and the only difference is the number in <code>get_post()</code> but I can't work out how they've done this...</p> <p>Anyone done/come across this before?</p> <p>Any help would be greatly appreciated.</p> <p>Thanks</p>
[ { "answer_id": 235673, "author": "John O'Sullivan", "author_id": 100858, "author_profile": "https://wordpress.stackexchange.com/users/100858", "pm_score": 1, "selected": false, "text": "<p>I worked it out, when in the admin area of a page/post you can find the post ID in the browser URL:</p>\n\n<pre><code>http://localhost/newsite/wp-admin/post.php?post=1807&amp;action=edit\n</code></pre>\n\n<p>So the previous dev simply uses this page as a 'parent', and refers to it as they set <code>$id = get_post(1807);</code></p>\n\n<p>Now the query find posts/pages that a 'children' of this page.</p>\n" }, { "answer_id": 235674, "author": "twolf", "author_id": 100819, "author_profile": "https://wordpress.stackexchange.com/users/100819", "pm_score": 0, "selected": false, "text": "<p>41 is the post ID. The developer has hardcoded the specific page that he wants to get the data from. get_post(41) will grab the associated details of the page with that ID. You can use a plugin like <a href=\"https://wordpress.org/plugins/wpsite-show-ids/\" rel=\"nofollow\">https://wordpress.org/plugins/wpsite-show-ids/</a> to see the id of your page directly in the admin dashboard to determine which page is being used here.</p>\n" } ]
2016/08/11
[ "https://wordpress.stackexchange.com/questions/235671", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100858/" ]
I've been asked to make some changes to a Wordpress site and the previous dev has displayed information from certain current pages on the homepage. What's confusing me is how they've managed to do this... he/she seems to have categorised certain pages by number. For example, the following WP\_Query() code seems to target a set number of pages: ``` <?php $id = get_post(41); setup_postdata($id); ?> <?php $args = array( 'post_parent' => $id, 'post_type' => 'page', 'hierarchical' => true, 'orderby' => 'menu_order', 'order' => 'ASC' ); $child_query = new WP_Query($args); ?> ``` There are other WP\_Query()'s throughout the page that target other posts and the only difference is the number in `get_post()` but I can't work out how they've done this... Anyone done/come across this before? Any help would be greatly appreciated. Thanks
I worked it out, when in the admin area of a page/post you can find the post ID in the browser URL: ``` http://localhost/newsite/wp-admin/post.php?post=1807&action=edit ``` So the previous dev simply uses this page as a 'parent', and refers to it as they set `$id = get_post(1807);` Now the query find posts/pages that a 'children' of this page.
235,683
<p>I have a loop that pulls the first three posts of a category. I want to use the featured image of the first post pulled for the background of the section the titles and links to these posts are displayed.</p> <p>Is it possible to pull the first image without pulling all other images of posts that were pulled in the loop?</p> <p>Here's the current loop:</p> <pre><code> &lt;?php $cinemasight_header_query = new WP_Query( array( 'category_name' =&gt; 'academy-awards', 'posts_per_page' =&gt; 3 ) ); if ($cinemasight_header_query-&gt;have_posts()) : while($cinemasight_header_query-&gt;have_posts()) : $cinemasight_header_query-&gt;the_post();?&gt; &lt;span class="Categories_Upper_Left"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;br /&gt; &lt;/span&gt; &lt;?php endwhile; endif; wp_reset_postdata();?&gt; </code></pre> <p><strong>EDIT (8/13/16, 8:56AM CST)</strong></p> <p>Revised for most recent corrections.</p> <pre><code>&lt;div class="Header_Section_Left"&gt;&lt;span class="Category_Header_Title"&gt;ACADEMY AWARDS&lt;br /&gt;&lt;/span&gt;&lt;div id="Header_Upper_Left"&gt; &lt;?php $cinemasight_header_query = new WP_Query( array( 'category_name' =&gt; 'academy-awards', 'posts_per_page' =&gt; 3 ) ); if ($cinemasight_header_query-&gt;have_posts()) : while($cinemasight_header_query-&gt;have_posts()) : $cinemasight_header_query-&gt;the_post(); if( 0 == $cinemasight_header_query-&gt;current_post ) : $thumbnail_id = get_post_thumbnail_id(); $image_src = wp_get_attachment_image_src( $thumbnail_id );?&gt; &lt;div class="Categories_Upper_Left" style="background-image: url( '&lt;?php echo $image_src[0]; ?&gt;') ;"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php echo the_title(); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php continue; endif;?&gt; &lt;span class="Categories_Upper_Left"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;br /&gt; &lt;/span&gt; &lt;?php endwhile; endif; wp_reset_postdata();?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 235688, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 2, "selected": true, "text": "<p>I believe you are referring to <a href=\"https://wordpress.stackexchange.com/a/235365/99217\">this answer</a></p>\n\n<p>You could check the index of the current loop and use <code>get_the_post_thumbnail</code> to get the image tag or <code>the_post_thumbnail</code> to echo it.</p>\n\n<p>You can use the <code>$current_post</code> <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Properties\" rel=\"nofollow noreferrer\">property</a> to get the current index and show only on first occurrence. Here's the loop modified to achieve this.</p>\n\n<pre><code>&lt;?php\n\n$cinemasight_header_query = new WP_Query( array( \n 'category_name' =&gt; 'academy-awards',\n 'posts_per_page' =&gt; 3 \n) );\n\nif ($cinemasight_header_query-&gt;have_posts()) :\n\n while($cinemasight_header_query-&gt;have_posts()) :\n\n $cinemasight_header_query-&gt;the_post(); \n\n if( 0 == $cinemasight_header_query-&gt;current_post ) : // This will print on first index only\n?&gt;\n\n&lt;span class=\"Categories_Upper_Left\"&gt;\n &lt;span class=\"my-image-class\"&gt; &lt;?php the_post_thumbnail(); ?&gt;&lt;/span&gt;\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;br /&gt;\n&lt;/span&gt;\n\n&lt;?php \n continue; // skip the rest of this loop because we got what we needed\nendif; // End if for first index ?&gt; \n\n&lt;span class=\"Categories_Upper_Left\"&gt;\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;br /&gt;\n&lt;/span&gt;\n\n&lt;?php \n\n endwhile;\n\nendif; // End loop\n\nwp_reset_postdata();\n\n?&gt;\n</code></pre>\n\n<p>In my comment below, I used <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow noreferrer\">get_the_post_thumbnail()</a> which returns the <code>&lt;img&gt;</code> tag without printing it.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\">the_post_thumbnail()</a> will echo it's output. If you have custom image size, you can pass it as an argument with this function to retrieve it. Essentially, this function is a wrapper for <code>get_the_post_thumbnail()</code> and passes <code>post-thumbnail</code> as a default image size if none is given.</p>\n\n<p>Chose which one suits you better</p>\n\n<p><strong>EDIT</strong> </p>\n\n<p>For some reason I missed that you wanted to get the image to use as background. So you need only to fetch the <code>src</code> of the image and not the whole <code>&lt;img&gt;</code> tag</p>\n\n<p>Just change the conditional for the first index like so</p>\n\n<pre><code> if( 0 == $cinemasight_header_query-&gt;current_post ) : // This will print on first index only\n $thumbnail_id = get_post_thumbnail_id();\n $image_src = wp_get_attachment_image_src( $thumbnail_id ); ?&gt;\n\n&lt;div class=\"my-image-class\" style=\"background-image: url( '&lt;?php echo $image_src[0]; ?&gt;') ;\"&gt;\n &lt;span&gt; &lt;?php echo the_title(); ?&gt; &lt;/span&gt;\n&lt;/div&gt;\n\n &lt;?php \n continue; // skip the rest of this loop because we got what we needed\n endif; // End if for first index ?&gt; \n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">wp_get_attachment_image_src()</a> will return an array of </p>\n\n<ul>\n<li>[0] : image url</li>\n<li>[1] : width</li>\n<li>[2] : height</li>\n<li>[3] : is_intermediate </li>\n<li>false if no image is found</li>\n</ul>\n\n<p>and you can also pass the image size as second parameter to the function</p>\n" }, { "answer_id": 235715, "author": "lucian", "author_id": 70333, "author_profile": "https://wordpress.stackexchange.com/users/70333", "pm_score": 0, "selected": false, "text": "<p>Cleanest is with two separate loops. Run a first loop for just one item (thumbnail included) and then a second loop for the other items with <code>'offset' =&gt; 1</code> (thumbnails not included).</p>\n" }, { "answer_id": 235809, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php\n$cinemasight_header_query = new WP_Query( array( \n 'category_name' =&gt; 'academy-awards',\n 'posts_per_page' =&gt; 3 \n) );\n\nif ($cinemasight_header_query-&gt;have_posts()) :\n $counter = 0;\n while($cinemasight_header_query-&gt;have_posts()) :\n $counter++;\n $cinemasight_header_query-&gt;the_post();\n\n if ( $counter == 1 ) {\n if ( has_post_thumbnail() ) {\n the_post_thumbnail( 'image_size', array( 'class' =&gt; 'img-responsive' ) );\n }\n } ?&gt;\n\n &lt;span class=\"Categories_Upper_Left\"&gt;\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;br /&gt;\n &lt;/span&gt;\n\n &lt;?php endwhile;\n\nendif;\n\nwp_reset_postdata();?&gt;\n</code></pre>\n" } ]
2016/08/11
[ "https://wordpress.stackexchange.com/questions/235683", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100669/" ]
I have a loop that pulls the first three posts of a category. I want to use the featured image of the first post pulled for the background of the section the titles and links to these posts are displayed. Is it possible to pull the first image without pulling all other images of posts that were pulled in the loop? Here's the current loop: ``` <?php $cinemasight_header_query = new WP_Query( array( 'category_name' => 'academy-awards', 'posts_per_page' => 3 ) ); if ($cinemasight_header_query->have_posts()) : while($cinemasight_header_query->have_posts()) : $cinemasight_header_query->the_post();?> <span class="Categories_Upper_Left"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br /> </span> <?php endwhile; endif; wp_reset_postdata();?> ``` **EDIT (8/13/16, 8:56AM CST)** Revised for most recent corrections. ``` <div class="Header_Section_Left"><span class="Category_Header_Title">ACADEMY AWARDS<br /></span><div id="Header_Upper_Left"> <?php $cinemasight_header_query = new WP_Query( array( 'category_name' => 'academy-awards', 'posts_per_page' => 3 ) ); if ($cinemasight_header_query->have_posts()) : while($cinemasight_header_query->have_posts()) : $cinemasight_header_query->the_post(); if( 0 == $cinemasight_header_query->current_post ) : $thumbnail_id = get_post_thumbnail_id(); $image_src = wp_get_attachment_image_src( $thumbnail_id );?> <div class="Categories_Upper_Left" style="background-image: url( '<?php echo $image_src[0]; ?>') ;"> <a href="<?php the_permalink() ?>"><?php echo the_title(); ?></a> </div> <?php continue; endif;?> <span class="Categories_Upper_Left"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br /> </span> <?php endwhile; endif; wp_reset_postdata();?> </div> ```
I believe you are referring to [this answer](https://wordpress.stackexchange.com/a/235365/99217) You could check the index of the current loop and use `get_the_post_thumbnail` to get the image tag or `the_post_thumbnail` to echo it. You can use the `$current_post` [property](https://codex.wordpress.org/Class_Reference/WP_Query#Properties) to get the current index and show only on first occurrence. Here's the loop modified to achieve this. ``` <?php $cinemasight_header_query = new WP_Query( array( 'category_name' => 'academy-awards', 'posts_per_page' => 3 ) ); if ($cinemasight_header_query->have_posts()) : while($cinemasight_header_query->have_posts()) : $cinemasight_header_query->the_post(); if( 0 == $cinemasight_header_query->current_post ) : // This will print on first index only ?> <span class="Categories_Upper_Left"> <span class="my-image-class"> <?php the_post_thumbnail(); ?></span> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br /> </span> <?php continue; // skip the rest of this loop because we got what we needed endif; // End if for first index ?> <span class="Categories_Upper_Left"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br /> </span> <?php endwhile; endif; // End loop wp_reset_postdata(); ?> ``` In my comment below, I used [get\_the\_post\_thumbnail()](https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/) which returns the `<img>` tag without printing it. [the\_post\_thumbnail()](https://developer.wordpress.org/reference/functions/the_post_thumbnail/) will echo it's output. If you have custom image size, you can pass it as an argument with this function to retrieve it. Essentially, this function is a wrapper for `get_the_post_thumbnail()` and passes `post-thumbnail` as a default image size if none is given. Chose which one suits you better **EDIT** For some reason I missed that you wanted to get the image to use as background. So you need only to fetch the `src` of the image and not the whole `<img>` tag Just change the conditional for the first index like so ``` if( 0 == $cinemasight_header_query->current_post ) : // This will print on first index only $thumbnail_id = get_post_thumbnail_id(); $image_src = wp_get_attachment_image_src( $thumbnail_id ); ?> <div class="my-image-class" style="background-image: url( '<?php echo $image_src[0]; ?>') ;"> <span> <?php echo the_title(); ?> </span> </div> <?php continue; // skip the rest of this loop because we got what we needed endif; // End if for first index ?> ``` [wp\_get\_attachment\_image\_src()](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/) will return an array of * [0] : image url * [1] : width * [2] : height * [3] : is\_intermediate * false if no image is found and you can also pass the image size as second parameter to the function
235,685
<p>I want to pull the three most recent posts from a specific category. I have the code to do that, but I'm trying to figure out if there's a way to reverse the order of these three posts when displaying/pulling the data?</p> <p>Current Code: <pre><code> 'category_name' =&gt; 'dvd-report', 'posts_per_page' =&gt; 3, ) ); if ($cinemasight_header_query-&gt;have_posts()) : while($cinemasight_header_query-&gt;have_posts()) : $cinemasight_header_query-&gt;the_post();?&gt; &lt;span class="Categories_Lower_Right"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;br /&gt; &lt;/span&gt; &lt;?php endwhile; endif; wp_reset_postdata();?&gt; </code></pre>
[ { "answer_id": 235693, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<p>Assuming you are refering to the code of <a href=\"https://wordpress.stackexchange.com/a/235365/99217\">this answer</a> </p>\n\n<p>Taking the query from that answer</p>\n\n<pre><code>$args = array( \n 'category_name' =&gt; 'your-category-slug',\n 'posts_per_page' =&gt; 3,\n);\n\n$wpse_235685_query = new WP_Query( $args );\n</code></pre>\n\n<p>you would then, to reverse the order of your results, need to modify the query <code>$posts</code> object, like so</p>\n\n<pre><code>$temp_posts = $wpse_235685_query-&gt;posts; // store the posts to work with\n$wpse_235685_query-&gt;posts = array(); // empty the $posts object\n$wpse_235685_query-&gt;posts = array_reverse($temp_post); // set back the object to use new reverse order\n</code></pre>\n\n<p>of course this could be simplified by getting rid of the temporary variable like so</p>\n\n<pre><code>$wpse_235685_query-&gt;posts = array_reverse( $wpse_235685_query-&gt;posts );\n</code></pre>\n\n<p>This code should go between your <code>if( $wpse_235685_query-&gt;have_posts() ) :</code> and your <code>while( $wpse_235685_query-&gt;have_posts() ) :</code> so it doesn't run when the query returns an empty set.</p>\n" }, { "answer_id": 235695, "author": "KnightHawk", "author_id": 50492, "author_profile": "https://wordpress.stackexchange.com/users/50492", "pm_score": 1, "selected": false, "text": "<p>Once you have your array of the three most recent posts you can use <code>array_reverse()</code> (<a href=\"http://php.net/manual/en/function.array-reverse.php\" rel=\"nofollow\">php manual</a>). This way you will still get the three most recent posts like you already do, but now they are in the reverse order.</p>\n\n<pre><code>$array_of_three_recent_posts = array_reverse($array_of_three_recent_posts);\n</code></pre>\n" }, { "answer_id": 235696, "author": "Frank Thoeny", "author_id": 70680, "author_profile": "https://wordpress.stackexchange.com/users/70680", "pm_score": -1, "selected": false, "text": "<p>The args:</p>\n\n<pre><code> $args = array(\n 'posts_per_page' =&gt; 3,\n 'category_name' =&gt; 'staff', \n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'date'\n );\n</code></pre>\n\n<p>The query:</p>\n\n<pre><code> $the_query = new WP_Query( $args );\n\n if ( $the_query-&gt;have_posts() ) {\n\n echo '&lt;ul&gt;';\n\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;li&gt;' . get_the_title() . '&lt;/li&gt;';\n }\n\n echo '&lt;/ul&gt;';\n /* Restore original Post Data */\n wp_reset_postdata();\n\n } else {\n // no posts found\n }\n</code></pre>\n" } ]
2016/08/11
[ "https://wordpress.stackexchange.com/questions/235685", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100669/" ]
I want to pull the three most recent posts from a specific category. I have the code to do that, but I'm trying to figure out if there's a way to reverse the order of these three posts when displaying/pulling the data? Current Code: ``` 'category_name' => 'dvd-report', 'posts_per_page' => 3, ) ); if ($cinemasight_header_query->have_posts()) : while($cinemasight_header_query->have_posts()) : $cinemasight_header_query->the_post();?> <span class="Categories_Lower_Right"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br /> </span> <?php endwhile; endif; wp_reset_postdata();?> ```
Assuming you are refering to the code of [this answer](https://wordpress.stackexchange.com/a/235365/99217) Taking the query from that answer ``` $args = array( 'category_name' => 'your-category-slug', 'posts_per_page' => 3, ); $wpse_235685_query = new WP_Query( $args ); ``` you would then, to reverse the order of your results, need to modify the query `$posts` object, like so ``` $temp_posts = $wpse_235685_query->posts; // store the posts to work with $wpse_235685_query->posts = array(); // empty the $posts object $wpse_235685_query->posts = array_reverse($temp_post); // set back the object to use new reverse order ``` of course this could be simplified by getting rid of the temporary variable like so ``` $wpse_235685_query->posts = array_reverse( $wpse_235685_query->posts ); ``` This code should go between your `if( $wpse_235685_query->have_posts() ) :` and your `while( $wpse_235685_query->have_posts() ) :` so it doesn't run when the query returns an empty set.
235,711
<p>I am having troubles with the archives for a custom post type.</p> <ul> <li>I have a WordPress page at <code>/address/</code></li> <li>I have created dynamic custom posts that are to appear at <code>/address/post#/</code></li> </ul> <p>When I activate this functionality, the WordPress page at <code>/address/</code> is replaced with the custom posts archive.</p> <p>How can I stop this from happening? I want the WordPress page to appear at <code>/address/</code> instead of the archive.</p>
[ { "answer_id": 235713, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 3, "selected": false, "text": "<p>When you register your post type, set the <code>has_archive</code> argument to false. If you change it, don't forget to flush your rewrite rules to see the change. </p>\n\n<p>Now this works fine if, as you asked, you want to show the page and not the archive. What about the situation where you'd like to show the page's content and also the listing of custom posts?</p>\n\n<p>There are two approaches you can use to achieve this.</p>\n\n<h2>1 - Use a Page Template</h2>\n\n<p>This is the one I see most often around the web. Create a page template and after showing the title and content use a custom loop to show your posts. It does the job, but people seem to get messed up with proper pagination quite often.</p>\n\n<h2>2 - Page for Custom Posts</h2>\n\n<p>This is my preferred approach. I keep <code>has_archive</code> when I register my post type and I make a normal Page to use with the archive template. The Page's slug matches the Archive slug. By default WP's rewrite rules are ordered so that the Archive trumps the Page.</p>\n\n<p>At the start of my <code>archive-{post_type}.php</code> template I place this:</p>\n\n<pre><code>$queried_object = get_queried_object();\n\n$page_data = get_page_by_path( $queried_object-&gt;rewrite['slug'] );\n\n/* no need to check our context, as we know that this \n code will only run for our CPT archives\n*/\n\nif ( !is_single() ) {\n echo apply_filters('the_content', $page_data-&gt;post_content);\n}\n\n// process the content in the same way that the_content would within a loop\n\n// Now go into your usual archive loop...\n</code></pre>\n\n<p>If you prefer you could use a page ID or even set up an option for your post type that's equivalent to the built-in Page for Posts.</p>\n\n<p>This way you aren't having to reconstruct the more difficult archive query for yourself.</p>\n" }, { "answer_id": 235837, "author": "Cyrus", "author_id": 100880, "author_profile": "https://wordpress.stackexchange.com/users/100880", "pm_score": -1, "selected": false, "text": "<p>Thanks everyone for your help.</p>\n\n<p>Andy put me on the right track.\nI just had to add:</p>\n\n<p>flush_rewrite_rules();</p>\n\n<p>Thanks again!</p>\n" } ]
2016/08/11
[ "https://wordpress.stackexchange.com/questions/235711", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100880/" ]
I am having troubles with the archives for a custom post type. * I have a WordPress page at `/address/` * I have created dynamic custom posts that are to appear at `/address/post#/` When I activate this functionality, the WordPress page at `/address/` is replaced with the custom posts archive. How can I stop this from happening? I want the WordPress page to appear at `/address/` instead of the archive.
When you register your post type, set the `has_archive` argument to false. If you change it, don't forget to flush your rewrite rules to see the change. Now this works fine if, as you asked, you want to show the page and not the archive. What about the situation where you'd like to show the page's content and also the listing of custom posts? There are two approaches you can use to achieve this. 1 - Use a Page Template ----------------------- This is the one I see most often around the web. Create a page template and after showing the title and content use a custom loop to show your posts. It does the job, but people seem to get messed up with proper pagination quite often. 2 - Page for Custom Posts ------------------------- This is my preferred approach. I keep `has_archive` when I register my post type and I make a normal Page to use with the archive template. The Page's slug matches the Archive slug. By default WP's rewrite rules are ordered so that the Archive trumps the Page. At the start of my `archive-{post_type}.php` template I place this: ``` $queried_object = get_queried_object(); $page_data = get_page_by_path( $queried_object->rewrite['slug'] ); /* no need to check our context, as we know that this code will only run for our CPT archives */ if ( !is_single() ) { echo apply_filters('the_content', $page_data->post_content); } // process the content in the same way that the_content would within a loop // Now go into your usual archive loop... ``` If you prefer you could use a page ID or even set up an option for your post type that's equivalent to the built-in Page for Posts. This way you aren't having to reconstruct the more difficult archive query for yourself.
235,729
<p>I have been working for 7 days straight to perfect code that generates a submenu on pages that have children. Since it was so complex I figured I'd write it in my index.php file and then migrate it to a widget plugin once I got it working. It now works flawlessly but when I move it over to my plugin it doesn't identify the page levels (parent/child/grandchild) correctly. I have tested the plugin to make sure I'm not doing anything wrong with the setup. It works as it should.</p> <p>Here is the code that works correctly in my index.php. I try pulling in all the code within my <code>&lt;aside&gt;</code> tags to the plugin (excluding the jquery) and I get first + second level pages where I should have second level, and first level pages where I should have third level:</p> <pre><code>&lt;aside class="sidebar"&gt; &lt;div class="submenu"&gt; &lt;?php if(count(get_post_ancestors($post-&gt;ID)) == 1 ) { echo '&lt;ul&gt;'; $args = array( 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'post_parent' =&gt; $post-&gt;post_parent, ); $query = new WP_Query($args); while ($query-&gt;have_posts()) { $query-&gt;the_post(); $child = get_pages('child_of='.$post-&gt;ID); if( count( $child ) != 0 ) : ?&gt; &lt;li class="has-children"&gt;&lt;a href="#&lt;?php the_ID(); ?&gt;" class="list-group-item" data-toggle="collapse"&gt;&lt;?php the_title(); ?&gt;&lt;i class="glyphicon glyphicon-chevron-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;?php $children = wp_list_pages( 'title_li=&amp;child_of='.$post-&gt;ID.'&amp;echo=0&amp;depth=1' ); if ( $children) : ?&gt; &lt;ul class="children collapse" id="&lt;?php the_ID(); ?&gt;"&gt; &lt;li &lt;?php if(is_page($post-&gt;ID )) {?&gt; class="current_page_item" &lt;?php }?&gt; &gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;Overview&lt;/a&gt;&lt;/li&gt; &lt;?php echo $children; ?&gt; &lt;/ul&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;?php else : ?&gt; &lt;li &lt;?php if(is_page($post-&gt;ID )) {?&gt; class="current_page_item" &lt;?php }?&gt;&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php endif; } echo '&lt;/ul&gt;'; } elseif (count(get_post_ancestors($post-&gt;ID)) == 2 ) { echo '&lt;ul&gt;'; $args = array( 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'post_parent' =&gt; get_post( $post-&gt;post_parent )-&gt;post_parent, 'depth' =&gt; 1, ); $query = new WP_Query($args); while ($query-&gt;have_posts()) { $query-&gt;the_post(); $child = get_pages('child_of='.$post-&gt;ID); if( count( $child ) != 0 ) : ?&gt; &lt;li class="has-children"&gt;&lt;a href="#&lt;?php the_ID(); ?&gt;" class="list-group-item" data-toggle="collapse"&gt;&lt;?php the_title(); ?&gt;&lt;i class="glyphicon glyphicon-chevron-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;?php $children = wp_list_pages( 'title_li=&amp;child_of='.$post-&gt;ID.'&amp;echo=0&amp;depth=1' ); if ( $children) : ?&gt; &lt;ul class="children collapse" id="&lt;?php the_ID(); ?&gt;"&gt; &lt;li &lt;?php if(is_page($post-&gt;ID )) {?&gt; class="current_page_item" &lt;?php }?&gt; &gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;Overview&lt;/a&gt;&lt;/li&gt; &lt;?php echo $children; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; &lt;/li&gt; &lt;?php else : ?&gt; &lt;li &lt;?php if(is_page($post-&gt;ID )) {?&gt; class="current_page_item" &lt;?php }?&gt;&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php endif; } echo '&lt;/ul&gt;'; } elseif (get_pages('child_of='.$post-&gt;ID) ) { echo '&lt;ul&gt;'; $args = array( 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'post_parent' =&gt; $post-&gt;ID, 'depth' =&gt; 1, ); $query = new WP_Query($args); while ($query-&gt;have_posts()) { $query-&gt;the_post(); $child = get_pages('child_of='.$post-&gt;ID); if( count( $child ) != 0 ) : ?&gt; &lt;li class="has-children"&gt;&lt;a href="#&lt;?php the_ID(); ?&gt;" class="list-group-item" data-toggle="collapse"&gt;&lt;?php the_title(); ?&gt;&lt;i class="glyphicon glyphicon-chevron-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;?php $children = wp_list_pages( 'title_li=&amp;child_of='.$post-&gt;ID.'&amp;echo=0&amp;depth=1' ); if ( $children) : ?&gt; &lt;ul class="children collapse" id="&lt;?php the_ID(); ?&gt;"&gt; &lt;li &lt;?php if(is_page($post-&gt;ID )) {?&gt; class="current_page_item" &lt;?php }?&gt;&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;Overview&lt;/a&gt;&lt;/li&gt; &lt;?php echo $children; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; &lt;/li&gt; &lt;?php else : ?&gt; &lt;li &lt;?php if(is_page($post-&gt;ID )) {?&gt; class="current_page_item" &lt;?php }?&gt;&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php endif; } echo '&lt;/ul&gt;'; } wp_reset_postdata(); ?&gt; &lt;script type="text/javascript"&gt; var $ = jQuery; $(document).ready(function(){ $(function() { $('.list-group-item').on('click', function() { $('.glyphicon', this) .toggleClass('glyphicon-chevron-right') .toggleClass('glyphicon-chevron-down'); }); }); if ( $('.children li').hasClass('current_page_item') ) { $('.list-group-item .glyphicon', this) .toggleClass('glyphicon-chevron-right') .toggleClass('glyphicon-chevron-down'); $('.children', this) .addClass('in'); }; }); &lt;/script&gt; &lt;/div&gt; &lt;/aside&gt; </code></pre>
[ { "answer_id": 235713, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 3, "selected": false, "text": "<p>When you register your post type, set the <code>has_archive</code> argument to false. If you change it, don't forget to flush your rewrite rules to see the change. </p>\n\n<p>Now this works fine if, as you asked, you want to show the page and not the archive. What about the situation where you'd like to show the page's content and also the listing of custom posts?</p>\n\n<p>There are two approaches you can use to achieve this.</p>\n\n<h2>1 - Use a Page Template</h2>\n\n<p>This is the one I see most often around the web. Create a page template and after showing the title and content use a custom loop to show your posts. It does the job, but people seem to get messed up with proper pagination quite often.</p>\n\n<h2>2 - Page for Custom Posts</h2>\n\n<p>This is my preferred approach. I keep <code>has_archive</code> when I register my post type and I make a normal Page to use with the archive template. The Page's slug matches the Archive slug. By default WP's rewrite rules are ordered so that the Archive trumps the Page.</p>\n\n<p>At the start of my <code>archive-{post_type}.php</code> template I place this:</p>\n\n<pre><code>$queried_object = get_queried_object();\n\n$page_data = get_page_by_path( $queried_object-&gt;rewrite['slug'] );\n\n/* no need to check our context, as we know that this \n code will only run for our CPT archives\n*/\n\nif ( !is_single() ) {\n echo apply_filters('the_content', $page_data-&gt;post_content);\n}\n\n// process the content in the same way that the_content would within a loop\n\n// Now go into your usual archive loop...\n</code></pre>\n\n<p>If you prefer you could use a page ID or even set up an option for your post type that's equivalent to the built-in Page for Posts.</p>\n\n<p>This way you aren't having to reconstruct the more difficult archive query for yourself.</p>\n" }, { "answer_id": 235837, "author": "Cyrus", "author_id": 100880, "author_profile": "https://wordpress.stackexchange.com/users/100880", "pm_score": -1, "selected": false, "text": "<p>Thanks everyone for your help.</p>\n\n<p>Andy put me on the right track.\nI just had to add:</p>\n\n<p>flush_rewrite_rules();</p>\n\n<p>Thanks again!</p>\n" } ]
2016/08/12
[ "https://wordpress.stackexchange.com/questions/235729", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62370/" ]
I have been working for 7 days straight to perfect code that generates a submenu on pages that have children. Since it was so complex I figured I'd write it in my index.php file and then migrate it to a widget plugin once I got it working. It now works flawlessly but when I move it over to my plugin it doesn't identify the page levels (parent/child/grandchild) correctly. I have tested the plugin to make sure I'm not doing anything wrong with the setup. It works as it should. Here is the code that works correctly in my index.php. I try pulling in all the code within my `<aside>` tags to the plugin (excluding the jquery) and I get first + second level pages where I should have second level, and first level pages where I should have third level: ``` <aside class="sidebar"> <div class="submenu"> <?php if(count(get_post_ancestors($post->ID)) == 1 ) { echo '<ul>'; $args = array( 'post_type' => 'page', 'post_status' => 'publish', 'posts_per_page' => -1, 'post_parent' => $post->post_parent, ); $query = new WP_Query($args); while ($query->have_posts()) { $query->the_post(); $child = get_pages('child_of='.$post->ID); if( count( $child ) != 0 ) : ?> <li class="has-children"><a href="#<?php the_ID(); ?>" class="list-group-item" data-toggle="collapse"><?php the_title(); ?><i class="glyphicon glyphicon-chevron-right"></i></a> <?php $children = wp_list_pages( 'title_li=&child_of='.$post->ID.'&echo=0&depth=1' ); if ( $children) : ?> <ul class="children collapse" id="<?php the_ID(); ?>"> <li <?php if(is_page($post->ID )) {?> class="current_page_item" <?php }?> ><a href="<?php the_permalink(); ?>">Overview</a></li> <?php echo $children; ?> </ul> </li> <?php endif; ?> <?php else : ?> <li <?php if(is_page($post->ID )) {?> class="current_page_item" <?php }?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php endif; } echo '</ul>'; } elseif (count(get_post_ancestors($post->ID)) == 2 ) { echo '<ul>'; $args = array( 'post_type' => 'page', 'post_status' => 'publish', 'posts_per_page' => -1, 'post_parent' => get_post( $post->post_parent )->post_parent, 'depth' => 1, ); $query = new WP_Query($args); while ($query->have_posts()) { $query->the_post(); $child = get_pages('child_of='.$post->ID); if( count( $child ) != 0 ) : ?> <li class="has-children"><a href="#<?php the_ID(); ?>" class="list-group-item" data-toggle="collapse"><?php the_title(); ?><i class="glyphicon glyphicon-chevron-right"></i></a> <?php $children = wp_list_pages( 'title_li=&child_of='.$post->ID.'&echo=0&depth=1' ); if ( $children) : ?> <ul class="children collapse" id="<?php the_ID(); ?>"> <li <?php if(is_page($post->ID )) {?> class="current_page_item" <?php }?> ><a href="<?php the_permalink(); ?>">Overview</a></li> <?php echo $children; ?> </ul> <?php endif; ?> </li> <?php else : ?> <li <?php if(is_page($post->ID )) {?> class="current_page_item" <?php }?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php endif; } echo '</ul>'; } elseif (get_pages('child_of='.$post->ID) ) { echo '<ul>'; $args = array( 'post_type' => 'page', 'post_status' => 'publish', 'posts_per_page' => -1, 'post_parent' => $post->ID, 'depth' => 1, ); $query = new WP_Query($args); while ($query->have_posts()) { $query->the_post(); $child = get_pages('child_of='.$post->ID); if( count( $child ) != 0 ) : ?> <li class="has-children"><a href="#<?php the_ID(); ?>" class="list-group-item" data-toggle="collapse"><?php the_title(); ?><i class="glyphicon glyphicon-chevron-right"></i></a> <?php $children = wp_list_pages( 'title_li=&child_of='.$post->ID.'&echo=0&depth=1' ); if ( $children) : ?> <ul class="children collapse" id="<?php the_ID(); ?>"> <li <?php if(is_page($post->ID )) {?> class="current_page_item" <?php }?>><a href="<?php the_permalink(); ?>">Overview</a></li> <?php echo $children; ?> </ul> <?php endif; ?> </li> <?php else : ?> <li <?php if(is_page($post->ID )) {?> class="current_page_item" <?php }?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php endif; } echo '</ul>'; } wp_reset_postdata(); ?> <script type="text/javascript"> var $ = jQuery; $(document).ready(function(){ $(function() { $('.list-group-item').on('click', function() { $('.glyphicon', this) .toggleClass('glyphicon-chevron-right') .toggleClass('glyphicon-chevron-down'); }); }); if ( $('.children li').hasClass('current_page_item') ) { $('.list-group-item .glyphicon', this) .toggleClass('glyphicon-chevron-right') .toggleClass('glyphicon-chevron-down'); $('.children', this) .addClass('in'); }; }); </script> </div> </aside> ```
When you register your post type, set the `has_archive` argument to false. If you change it, don't forget to flush your rewrite rules to see the change. Now this works fine if, as you asked, you want to show the page and not the archive. What about the situation where you'd like to show the page's content and also the listing of custom posts? There are two approaches you can use to achieve this. 1 - Use a Page Template ----------------------- This is the one I see most often around the web. Create a page template and after showing the title and content use a custom loop to show your posts. It does the job, but people seem to get messed up with proper pagination quite often. 2 - Page for Custom Posts ------------------------- This is my preferred approach. I keep `has_archive` when I register my post type and I make a normal Page to use with the archive template. The Page's slug matches the Archive slug. By default WP's rewrite rules are ordered so that the Archive trumps the Page. At the start of my `archive-{post_type}.php` template I place this: ``` $queried_object = get_queried_object(); $page_data = get_page_by_path( $queried_object->rewrite['slug'] ); /* no need to check our context, as we know that this code will only run for our CPT archives */ if ( !is_single() ) { echo apply_filters('the_content', $page_data->post_content); } // process the content in the same way that the_content would within a loop // Now go into your usual archive loop... ``` If you prefer you could use a page ID or even set up an option for your post type that's equivalent to the built-in Page for Posts. This way you aren't having to reconstruct the more difficult archive query for yourself.
235,744
<p>I have a WP theme with its own custom fields. I installed the PowerPress Plugin. The PowerPress Plugin has a textfield called 'Episode Titles'.</p> <p>What I want is when the post is published (or save), WP will grab the data from the custom field 'Speaker' and then populated it into 'Episode Titles'.</p> <p>Can someone show me how to do this? I know how to populate a custom field when publish -> <a href="https://wordpress.stackexchange.com/questions/100934/automatically-fill-custom-field-value-on-post-publish-update">Automatically fill custom field value on post publish/update</a></p>
[ { "answer_id": 235758, "author": "bagpipper", "author_id": 80397, "author_profile": "https://wordpress.stackexchange.com/users/80397", "pm_score": 2, "selected": false, "text": "<pre><code>/* Do something with the data entered */\nadd_action( 'save_post', 'myplugin_save_postdata' );\n\n/* When the post is saved, saves our custom data */\nfunction myplugin_save_postdata( $post_id ) {\n\n // First we need to check if the current user is authorised to do this action. \n if ( 'page' == $_POST['post_type'] ) {// checks for post type.\n if ( ! current_user_can( 'edit_page', $post_id ) )\n return;\n } else {\n if ( ! current_user_can( 'edit_post', $post_id ) )\n return;\n }\n\n $mydata = get_post_meta($post_id,'speaker',true);\n\n update_post_meta( $post_id, '_your_meta_key', $mydata ); // replace your _your_meta_key with Episode Titles key\n\n}\n</code></pre>\n\n<p>This might be what you need. The current code works for pages only, but can be modified to work with posts or CPTs aswell. </p>\n\n<p>What this does is, it grabs the data from your speaker field and updates that value into your episode title. Be sure to add the correct key for your <code>Episode Titles</code></p>\n" }, { "answer_id": 236124, "author": "Angelo Mandato", "author_id": 60369, "author_profile": "https://wordpress.stackexchange.com/users/60369", "pm_score": 0, "selected": false, "text": "<p>I am the lead developer of PowerPress. Please let me know if you have any questions.</p>\n\n<p>I would recommend developing a plugin to do what you need rather than put this in your theme's functions.php since this functionality may live beyond your current theme.</p>\n\n<p>Can you explain what your end goal is? There may be an easier solution. PowerPress uses multi-dimensional arrays for the values as you can have more than one podcast episode box per blog post using custom post types or podcast channels features in PowerPress, which may be overkill for your use.</p>\n" } ]
2016/08/12
[ "https://wordpress.stackexchange.com/questions/235744", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65697/" ]
I have a WP theme with its own custom fields. I installed the PowerPress Plugin. The PowerPress Plugin has a textfield called 'Episode Titles'. What I want is when the post is published (or save), WP will grab the data from the custom field 'Speaker' and then populated it into 'Episode Titles'. Can someone show me how to do this? I know how to populate a custom field when publish -> [Automatically fill custom field value on post publish/update](https://wordpress.stackexchange.com/questions/100934/automatically-fill-custom-field-value-on-post-publish-update)
``` /* Do something with the data entered */ add_action( 'save_post', 'myplugin_save_postdata' ); /* When the post is saved, saves our custom data */ function myplugin_save_postdata( $post_id ) { // First we need to check if the current user is authorised to do this action. if ( 'page' == $_POST['post_type'] ) {// checks for post type. if ( ! current_user_can( 'edit_page', $post_id ) ) return; } else { if ( ! current_user_can( 'edit_post', $post_id ) ) return; } $mydata = get_post_meta($post_id,'speaker',true); update_post_meta( $post_id, '_your_meta_key', $mydata ); // replace your _your_meta_key with Episode Titles key } ``` This might be what you need. The current code works for pages only, but can be modified to work with posts or CPTs aswell. What this does is, it grabs the data from your speaker field and updates that value into your episode title. Be sure to add the correct key for your `Episode Titles`
235,754
<p>Change author, disable comments, enable trackbacks for all items in library with 1 click not each one of them separately?</p>
[ { "answer_id": 235758, "author": "bagpipper", "author_id": 80397, "author_profile": "https://wordpress.stackexchange.com/users/80397", "pm_score": 2, "selected": false, "text": "<pre><code>/* Do something with the data entered */\nadd_action( 'save_post', 'myplugin_save_postdata' );\n\n/* When the post is saved, saves our custom data */\nfunction myplugin_save_postdata( $post_id ) {\n\n // First we need to check if the current user is authorised to do this action. \n if ( 'page' == $_POST['post_type'] ) {// checks for post type.\n if ( ! current_user_can( 'edit_page', $post_id ) )\n return;\n } else {\n if ( ! current_user_can( 'edit_post', $post_id ) )\n return;\n }\n\n $mydata = get_post_meta($post_id,'speaker',true);\n\n update_post_meta( $post_id, '_your_meta_key', $mydata ); // replace your _your_meta_key with Episode Titles key\n\n}\n</code></pre>\n\n<p>This might be what you need. The current code works for pages only, but can be modified to work with posts or CPTs aswell. </p>\n\n<p>What this does is, it grabs the data from your speaker field and updates that value into your episode title. Be sure to add the correct key for your <code>Episode Titles</code></p>\n" }, { "answer_id": 236124, "author": "Angelo Mandato", "author_id": 60369, "author_profile": "https://wordpress.stackexchange.com/users/60369", "pm_score": 0, "selected": false, "text": "<p>I am the lead developer of PowerPress. Please let me know if you have any questions.</p>\n\n<p>I would recommend developing a plugin to do what you need rather than put this in your theme's functions.php since this functionality may live beyond your current theme.</p>\n\n<p>Can you explain what your end goal is? There may be an easier solution. PowerPress uses multi-dimensional arrays for the values as you can have more than one podcast episode box per blog post using custom post types or podcast channels features in PowerPress, which may be overkill for your use.</p>\n" } ]
2016/08/12
[ "https://wordpress.stackexchange.com/questions/235754", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100913/" ]
Change author, disable comments, enable trackbacks for all items in library with 1 click not each one of them separately?
``` /* Do something with the data entered */ add_action( 'save_post', 'myplugin_save_postdata' ); /* When the post is saved, saves our custom data */ function myplugin_save_postdata( $post_id ) { // First we need to check if the current user is authorised to do this action. if ( 'page' == $_POST['post_type'] ) {// checks for post type. if ( ! current_user_can( 'edit_page', $post_id ) ) return; } else { if ( ! current_user_can( 'edit_post', $post_id ) ) return; } $mydata = get_post_meta($post_id,'speaker',true); update_post_meta( $post_id, '_your_meta_key', $mydata ); // replace your _your_meta_key with Episode Titles key } ``` This might be what you need. The current code works for pages only, but can be modified to work with posts or CPTs aswell. What this does is, it grabs the data from your speaker field and updates that value into your episode title. Be sure to add the correct key for your `Episode Titles`
235,789
<p>I have a question that I haven’t been able to find a great answer to. Hoping you guys can help me out. </p> <p>I am in the process of rebuilding our company website. I have a WP theme picked out that I really love (Create from ThemeTrust). I want to use that as the theme for our entire site, except the ecommerce pages. I am hoping to use Shopify as our ecommerce platform, with a Shopify theme. Create already has a Woocommerce theme built in, but I’d like to use Shopify because of their retail POS and mobile sales capabilities. </p> <p>So my question is, can I use one theme (Create) as the base for most of the site, then use a Shopify theme for the ecommerce section of the site? My goal is to not have to use a subdomain for the site…ie (shop.domain.com). I’d like to keep it all together, (domain.com/shop).</p> <p>Any information/advice on this would be much appreciated!</p>
[ { "answer_id": 235758, "author": "bagpipper", "author_id": 80397, "author_profile": "https://wordpress.stackexchange.com/users/80397", "pm_score": 2, "selected": false, "text": "<pre><code>/* Do something with the data entered */\nadd_action( 'save_post', 'myplugin_save_postdata' );\n\n/* When the post is saved, saves our custom data */\nfunction myplugin_save_postdata( $post_id ) {\n\n // First we need to check if the current user is authorised to do this action. \n if ( 'page' == $_POST['post_type'] ) {// checks for post type.\n if ( ! current_user_can( 'edit_page', $post_id ) )\n return;\n } else {\n if ( ! current_user_can( 'edit_post', $post_id ) )\n return;\n }\n\n $mydata = get_post_meta($post_id,'speaker',true);\n\n update_post_meta( $post_id, '_your_meta_key', $mydata ); // replace your _your_meta_key with Episode Titles key\n\n}\n</code></pre>\n\n<p>This might be what you need. The current code works for pages only, but can be modified to work with posts or CPTs aswell. </p>\n\n<p>What this does is, it grabs the data from your speaker field and updates that value into your episode title. Be sure to add the correct key for your <code>Episode Titles</code></p>\n" }, { "answer_id": 236124, "author": "Angelo Mandato", "author_id": 60369, "author_profile": "https://wordpress.stackexchange.com/users/60369", "pm_score": 0, "selected": false, "text": "<p>I am the lead developer of PowerPress. Please let me know if you have any questions.</p>\n\n<p>I would recommend developing a plugin to do what you need rather than put this in your theme's functions.php since this functionality may live beyond your current theme.</p>\n\n<p>Can you explain what your end goal is? There may be an easier solution. PowerPress uses multi-dimensional arrays for the values as you can have more than one podcast episode box per blog post using custom post types or podcast channels features in PowerPress, which may be overkill for your use.</p>\n" } ]
2016/08/12
[ "https://wordpress.stackexchange.com/questions/235789", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100933/" ]
I have a question that I haven’t been able to find a great answer to. Hoping you guys can help me out. I am in the process of rebuilding our company website. I have a WP theme picked out that I really love (Create from ThemeTrust). I want to use that as the theme for our entire site, except the ecommerce pages. I am hoping to use Shopify as our ecommerce platform, with a Shopify theme. Create already has a Woocommerce theme built in, but I’d like to use Shopify because of their retail POS and mobile sales capabilities. So my question is, can I use one theme (Create) as the base for most of the site, then use a Shopify theme for the ecommerce section of the site? My goal is to not have to use a subdomain for the site…ie (shop.domain.com). I’d like to keep it all together, (domain.com/shop). Any information/advice on this would be much appreciated!
``` /* Do something with the data entered */ add_action( 'save_post', 'myplugin_save_postdata' ); /* When the post is saved, saves our custom data */ function myplugin_save_postdata( $post_id ) { // First we need to check if the current user is authorised to do this action. if ( 'page' == $_POST['post_type'] ) {// checks for post type. if ( ! current_user_can( 'edit_page', $post_id ) ) return; } else { if ( ! current_user_can( 'edit_post', $post_id ) ) return; } $mydata = get_post_meta($post_id,'speaker',true); update_post_meta( $post_id, '_your_meta_key', $mydata ); // replace your _your_meta_key with Episode Titles key } ``` This might be what you need. The current code works for pages only, but can be modified to work with posts or CPTs aswell. What this does is, it grabs the data from your speaker field and updates that value into your episode title. Be sure to add the correct key for your `Episode Titles`
235,799
<p>I am trying to implement a solution provided at wcvendors.com knowledgebase and unable to get the indicated results. Can somebody help me with the implementation as to where this is going wrong. I am a beginner at wordpress and php.</p> <p>Basically, I am trying to list vendors by their store location. For this i am using wc vendors multi vendor marketplace plugin. I have created a dropdown custom field as indicated in the code. The custom fields are coming up at the registration time and also reflected in the user profile for view and edit. I want to filter the vendors on this meta key to have vendors categorised by their location.</p> <p>IF there is any other option to do that it would be a great thing.</p>
[ { "answer_id": 235758, "author": "bagpipper", "author_id": 80397, "author_profile": "https://wordpress.stackexchange.com/users/80397", "pm_score": 2, "selected": false, "text": "<pre><code>/* Do something with the data entered */\nadd_action( 'save_post', 'myplugin_save_postdata' );\n\n/* When the post is saved, saves our custom data */\nfunction myplugin_save_postdata( $post_id ) {\n\n // First we need to check if the current user is authorised to do this action. \n if ( 'page' == $_POST['post_type'] ) {// checks for post type.\n if ( ! current_user_can( 'edit_page', $post_id ) )\n return;\n } else {\n if ( ! current_user_can( 'edit_post', $post_id ) )\n return;\n }\n\n $mydata = get_post_meta($post_id,'speaker',true);\n\n update_post_meta( $post_id, '_your_meta_key', $mydata ); // replace your _your_meta_key with Episode Titles key\n\n}\n</code></pre>\n\n<p>This might be what you need. The current code works for pages only, but can be modified to work with posts or CPTs aswell. </p>\n\n<p>What this does is, it grabs the data from your speaker field and updates that value into your episode title. Be sure to add the correct key for your <code>Episode Titles</code></p>\n" }, { "answer_id": 236124, "author": "Angelo Mandato", "author_id": 60369, "author_profile": "https://wordpress.stackexchange.com/users/60369", "pm_score": 0, "selected": false, "text": "<p>I am the lead developer of PowerPress. Please let me know if you have any questions.</p>\n\n<p>I would recommend developing a plugin to do what you need rather than put this in your theme's functions.php since this functionality may live beyond your current theme.</p>\n\n<p>Can you explain what your end goal is? There may be an easier solution. PowerPress uses multi-dimensional arrays for the values as you can have more than one podcast episode box per blog post using custom post types or podcast channels features in PowerPress, which may be overkill for your use.</p>\n" } ]
2016/08/12
[ "https://wordpress.stackexchange.com/questions/235799", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100936/" ]
I am trying to implement a solution provided at wcvendors.com knowledgebase and unable to get the indicated results. Can somebody help me with the implementation as to where this is going wrong. I am a beginner at wordpress and php. Basically, I am trying to list vendors by their store location. For this i am using wc vendors multi vendor marketplace plugin. I have created a dropdown custom field as indicated in the code. The custom fields are coming up at the registration time and also reflected in the user profile for view and edit. I want to filter the vendors on this meta key to have vendors categorised by their location. IF there is any other option to do that it would be a great thing.
``` /* Do something with the data entered */ add_action( 'save_post', 'myplugin_save_postdata' ); /* When the post is saved, saves our custom data */ function myplugin_save_postdata( $post_id ) { // First we need to check if the current user is authorised to do this action. if ( 'page' == $_POST['post_type'] ) {// checks for post type. if ( ! current_user_can( 'edit_page', $post_id ) ) return; } else { if ( ! current_user_can( 'edit_post', $post_id ) ) return; } $mydata = get_post_meta($post_id,'speaker',true); update_post_meta( $post_id, '_your_meta_key', $mydata ); // replace your _your_meta_key with Episode Titles key } ``` This might be what you need. The current code works for pages only, but can be modified to work with posts or CPTs aswell. What this does is, it grabs the data from your speaker field and updates that value into your episode title. Be sure to add the correct key for your `Episode Titles`
235,811
<p>i want to display custom taxonomy images on index.php and for this reason i installed <a href="https://wordpress.org/plugins/taxonomy-images/" rel="nofollow">this plugin</a>. I uploaded my taxonomy images but i couldn't display images on index. I tried the codes which are given by the plugin author. </p> <pre><code> &lt;?php print apply_filters( 'taxonomy-images-queried-term-image', '' ); ?&gt; </code></pre> <p>etc. But it didn't work. I think this code has no echo function, am i right? And the URL, which you can see the below, is my custom taxonomy URL. </p> <pre><code>edit-tags.php?taxonomy=ff-portfolio-tag&amp;post_type=portfolio </code></pre> <p>So how can i display my custom taxonomy images on index.php? Thanks a lot. </p>
[ { "answer_id": 235813, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 0, "selected": false, "text": "<p>Are you looking at a taxonomy archive page? You mention you want to display it on index.php, but since a theme can technically have only that template for all possible URLs that doesn't really give meaningful information.</p>\n\n<p>As the note on the plugin page says, that filter is for displaying the images on a page that has a term in its context, so if you aren't trying to view a taxonomy archive or similar then it won't work.</p>\n\n<p>I use this plugin all the time and as long as you dig into the documentation, everything is pretty clear.</p>\n\n<p>Try:</p>\n\n<pre><code>$terms = apply_filters( \n 'taxonomy-images-get-terms', \n '', \n array( \n 'taxonomy' =&gt; 'ff-portfolio-tag',\n ) \n);\nprint_r( $terms );\n</code></pre>\n\n<p>... for example.</p>\n" }, { "answer_id": 235818, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": 2, "selected": true, "text": "<p>Just like we use <code>get_terms()</code> to get all the terms in a custom taxonomy we can get all the taxonomy images with the below code. Place this code outside the loop to list all the taxonomy images.</p>\n\n<pre><code>$terms = apply_filters( 'taxonomy-images-get-terms', '', array(\n 'taxonomy' =&gt; 'ff-portfolio-tag',\n) );\nif ( ! empty( $terms ) ) {\n print '&lt;ul&gt;';\n foreach ( (array) $terms as $term ) {\n print '&lt;li&gt;&lt;a href=\"' . esc_url( get_term_link( $term, $term-&gt;taxonomy ) ) . '\"&gt;' . wp_get_attachment_image( $term-&gt;image_id, 'detail' ) . '&lt;/li&gt;';\n }\n print '&lt;/ul&gt;';\n}\n</code></pre>\n" } ]
2016/08/12
[ "https://wordpress.stackexchange.com/questions/235811", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100868/" ]
i want to display custom taxonomy images on index.php and for this reason i installed [this plugin](https://wordpress.org/plugins/taxonomy-images/). I uploaded my taxonomy images but i couldn't display images on index. I tried the codes which are given by the plugin author. ``` <?php print apply_filters( 'taxonomy-images-queried-term-image', '' ); ?> ``` etc. But it didn't work. I think this code has no echo function, am i right? And the URL, which you can see the below, is my custom taxonomy URL. ``` edit-tags.php?taxonomy=ff-portfolio-tag&post_type=portfolio ``` So how can i display my custom taxonomy images on index.php? Thanks a lot.
Just like we use `get_terms()` to get all the terms in a custom taxonomy we can get all the taxonomy images with the below code. Place this code outside the loop to list all the taxonomy images. ``` $terms = apply_filters( 'taxonomy-images-get-terms', '', array( 'taxonomy' => 'ff-portfolio-tag', ) ); if ( ! empty( $terms ) ) { print '<ul>'; foreach ( (array) $terms as $term ) { print '<li><a href="' . esc_url( get_term_link( $term, $term->taxonomy ) ) . '">' . wp_get_attachment_image( $term->image_id, 'detail' ) . '</li>'; } print '</ul>'; } ```
235,822
<p>I have a sidebar nav menu set up to display the top level pages. I'd like to display subpages (3rd level) when a user clicks on a parent item. For example, when then user clicks 'Detective Division' the two subpages (Violent Crimes and Property Crimes) will show.</p> <p><a href="https://i.stack.imgur.com/TnfWh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TnfWh.png" alt="Here is my menu setup in admin:"></a></p> <p>Here is my code for calling the menu:</p> <pre><code>&lt;div class="sidebar-nav hide-small"&gt; &lt;?php wp_nav_menu(array( 'theme_location' =&gt; 'sidebar-menu', 'depth' =&gt; 2 )); ?&gt; &lt;/div&gt; </code></pre> <p>Is this controlled with 'depth' or do I need to use a walker?</p>
[ { "answer_id": 235828, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 2, "selected": true, "text": "<p>No need for a custom walker - it's controlled with the <code>depth</code> parameter. At the moment, you're only showing 2 levels of menus - but you need to set this to <code>3</code>!</p>\n\n<p>This, however, will only control what is being output. As for the user clicking, hovering or otherwise to actually see the menu, you'll need to apply your own formatting (usually just CSS, although you could use JavaScript too) on the frontend in order to affect the display. WordPress doesn't handle this for you by default as its up to the theme.</p>\n" }, { "answer_id": 235830, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 0, "selected": false, "text": "<p>Just to clarify - you click on Detective Division, go to that page and you want the menu to show just Violent Crimes, Propery Crimes and so on?</p>\n\n<p>wp_nav_pages doesn't let you do that readily in the way that wp_list_pages does with the child_of argument. </p>\n\n<p>You could look at your own walker. </p>\n\n<p>On my own sites I tend to compromise and use wp_list_pages for subnav, with a plugin to give my users drag and drop ordering of all the subpages. </p>\n" } ]
2016/08/12
[ "https://wordpress.stackexchange.com/questions/235822", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100947/" ]
I have a sidebar nav menu set up to display the top level pages. I'd like to display subpages (3rd level) when a user clicks on a parent item. For example, when then user clicks 'Detective Division' the two subpages (Violent Crimes and Property Crimes) will show. [![Here is my menu setup in admin:](https://i.stack.imgur.com/TnfWh.png)](https://i.stack.imgur.com/TnfWh.png) Here is my code for calling the menu: ``` <div class="sidebar-nav hide-small"> <?php wp_nav_menu(array( 'theme_location' => 'sidebar-menu', 'depth' => 2 )); ?> </div> ``` Is this controlled with 'depth' or do I need to use a walker?
No need for a custom walker - it's controlled with the `depth` parameter. At the moment, you're only showing 2 levels of menus - but you need to set this to `3`! This, however, will only control what is being output. As for the user clicking, hovering or otherwise to actually see the menu, you'll need to apply your own formatting (usually just CSS, although you could use JavaScript too) on the frontend in order to affect the display. WordPress doesn't handle this for you by default as its up to the theme.
235,880
<p>I'm trying to find a way to change the href of a nav menu page link from the parent theme's default, which goes to its relative page, to another url. For example, I have a menu link "Our Philosophy" that links to the "Our Philosophy" page, but desire for it to go to timecube.com (rip).</p> <p>It seems perhaps using a filter (nav_menu_link_attributes?) might be a simple way to achieve this. However, I've been unable to wrap my head around using filters to get this working.</p> <p>I would think I'd need something like:</p> <pre><code>function change_nav_url( $atts, $item ) { // modify $item href? } add_filter ( 'nav_menu_link_attributes', 'change_nav_url'); </code></pre> <p>My initial thought would be I would need to call this function somewhere--with <code>apply_filters()</code> maybe--and would need to get <code>$atts</code> and <code>$item</code> manually from somewhere and pass them into it. But that creates the problem--how do I get them, and from what (a menu object?). And thinking about it, if I do have to retrieve them manually, I don't really see the point of using a filter v. a plain function, so maybe I have to put it into the plugin folder and it'll automatically give me access to <code>$atts</code> or something? (That didn't work). Either way, I'm clearly not understanding something. </p> <p>I appreciate any help bringing light to my newb ignorance.</p>
[ { "answer_id": 235886, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": false, "text": "<p>You are on right track, with few minor kinks.</p>\n\n<ol>\n<li>You need to modify <code>$atts</code> and return it. Any arguments after the first one are provided for information and should not be changed.</li>\n<li>You need to tell <code>add_filter()</code> that you expect more than one argument.</li>\n</ol>\n\n<p>The example with some debug code would be along the lines of:</p>\n\n<pre><code>add_filter( 'nav_menu_link_attributes', function ( $atts, $item, $args, $depth ) {\n\n var_dump( $atts, $item ); // a lot of stuff we can use\n\n var_dump( $atts['href'] ); // string(36) \"http://dev.rarst.net/our-philosophy/\"\n\n var_dump( get_the_title( $item-&gt;object_id ) ); // string(14) \"Our Philosophy\", note $item itself is NOT a page\n\n if ( get_the_title( $item-&gt;object_id ) === 'Our Philosophy' ) { // for example\n\n $atts['href'] = 'https://example.com/';\n }\n\n return $atts;\n}, 10, 4 ); // 4 so we get all arguments\n</code></pre>\n" }, { "answer_id": 298729, "author": "dbmpls", "author_id": 97681, "author_profile": "https://wordpress.stackexchange.com/users/97681", "pm_score": 2, "selected": false, "text": "<p>This will allow you to update the URL for specific menu items. In the case of the OP, \"Link Title\" would be replaced with \"Our Philosophy\".</p>\n\n<p>This would be placed in your child theme's functions.php</p>\n\n<pre><code> function update_menu_link($items){\n\n //look through the menu for items with Label \"Link Title\"\n foreach($items as $item){\n\n if($item-&gt;title === \"Link Title\"){ // this is the link label your searching for\n $item-&gt;url = \"http://newlink.com\"; //this is the new link\n }\n }\n return $items;\n }\n\n add_filter('wp_nav_menu_objects', 'update_menu_link', 10,2);\n</code></pre>\n" } ]
2016/08/13
[ "https://wordpress.stackexchange.com/questions/235880", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100980/" ]
I'm trying to find a way to change the href of a nav menu page link from the parent theme's default, which goes to its relative page, to another url. For example, I have a menu link "Our Philosophy" that links to the "Our Philosophy" page, but desire for it to go to timecube.com (rip). It seems perhaps using a filter (nav\_menu\_link\_attributes?) might be a simple way to achieve this. However, I've been unable to wrap my head around using filters to get this working. I would think I'd need something like: ``` function change_nav_url( $atts, $item ) { // modify $item href? } add_filter ( 'nav_menu_link_attributes', 'change_nav_url'); ``` My initial thought would be I would need to call this function somewhere--with `apply_filters()` maybe--and would need to get `$atts` and `$item` manually from somewhere and pass them into it. But that creates the problem--how do I get them, and from what (a menu object?). And thinking about it, if I do have to retrieve them manually, I don't really see the point of using a filter v. a plain function, so maybe I have to put it into the plugin folder and it'll automatically give me access to `$atts` or something? (That didn't work). Either way, I'm clearly not understanding something. I appreciate any help bringing light to my newb ignorance.
You are on right track, with few minor kinks. 1. You need to modify `$atts` and return it. Any arguments after the first one are provided for information and should not be changed. 2. You need to tell `add_filter()` that you expect more than one argument. The example with some debug code would be along the lines of: ``` add_filter( 'nav_menu_link_attributes', function ( $atts, $item, $args, $depth ) { var_dump( $atts, $item ); // a lot of stuff we can use var_dump( $atts['href'] ); // string(36) "http://dev.rarst.net/our-philosophy/" var_dump( get_the_title( $item->object_id ) ); // string(14) "Our Philosophy", note $item itself is NOT a page if ( get_the_title( $item->object_id ) === 'Our Philosophy' ) { // for example $atts['href'] = 'https://example.com/'; } return $atts; }, 10, 4 ); // 4 so we get all arguments ```
235,893
<p>I'm trying to display user <a href="http://en.gravatar.com/" rel="nofollow">gravatars</a> on this page <a href="http://gepc.themelot.com/survey-comparison/433747624/293281083/" rel="nofollow">http://gepc.themelot.com/survey-comparison/433747624/293281083/</a> but the page keeps showing the default '<a href="http://en.gravatar.com/site/implement/images/#default-image" rel="nofollow">mystery man</a>' avatar. I inspected the page element and it returns the same URL with the same hash value for the gravatar link.</p> <p>Here is my code:</p> <pre><code>&lt;?php if (!empty($matched_answers)) { ?&gt; &lt;h1&gt;&lt;?php $user = get_user_by( 'user_login', $matched_answers[0]['user'] ); echo get_avatar( $user-&gt;ID , 256 ).' '.$matched_answers[0]['user'].' - '.round($matched_answers[0]['percentage'], 2).' &amp;#37;'; ?&gt;&lt;/h1&gt; &lt;table border="0" width="100%"&gt; &lt;thead&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Percentage&lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php foreach ($matched_answers as $value) { $user = get_user_by( 'user_login', $value['user'] ); $user_email = $user-&gt;user_email; $url = 'http://gravatar.com/avatar/' . md5( $user_email ); $url = add_query_arg( array( 's' =&gt; 48, 'd' =&gt; 'mm', ), $url ); $gravatar_url = esc_url_raw( $url ); echo '&lt;tr&gt;'; echo '&lt;td&gt;'.'&lt;img src='.$gravatar_url.' /&gt;'.'&lt;td&gt;'; echo '&lt;td&gt;'.$value['user'] . '&lt;/td&gt;'; echo '&lt;td class="votepercent"&gt;' . round($value['percentage'], 2) . ' &amp;#37;&lt;/td&gt;'; echo '&lt;/tr&gt;'; } ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;?php } ?&gt; </code></pre> <p>How do I return the user's actual gravatar image? What is wrong with my code?</p> <p>Thanks in advance.</p>
[ { "answer_id": 235886, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": false, "text": "<p>You are on right track, with few minor kinks.</p>\n\n<ol>\n<li>You need to modify <code>$atts</code> and return it. Any arguments after the first one are provided for information and should not be changed.</li>\n<li>You need to tell <code>add_filter()</code> that you expect more than one argument.</li>\n</ol>\n\n<p>The example with some debug code would be along the lines of:</p>\n\n<pre><code>add_filter( 'nav_menu_link_attributes', function ( $atts, $item, $args, $depth ) {\n\n var_dump( $atts, $item ); // a lot of stuff we can use\n\n var_dump( $atts['href'] ); // string(36) \"http://dev.rarst.net/our-philosophy/\"\n\n var_dump( get_the_title( $item-&gt;object_id ) ); // string(14) \"Our Philosophy\", note $item itself is NOT a page\n\n if ( get_the_title( $item-&gt;object_id ) === 'Our Philosophy' ) { // for example\n\n $atts['href'] = 'https://example.com/';\n }\n\n return $atts;\n}, 10, 4 ); // 4 so we get all arguments\n</code></pre>\n" }, { "answer_id": 298729, "author": "dbmpls", "author_id": 97681, "author_profile": "https://wordpress.stackexchange.com/users/97681", "pm_score": 2, "selected": false, "text": "<p>This will allow you to update the URL for specific menu items. In the case of the OP, \"Link Title\" would be replaced with \"Our Philosophy\".</p>\n\n<p>This would be placed in your child theme's functions.php</p>\n\n<pre><code> function update_menu_link($items){\n\n //look through the menu for items with Label \"Link Title\"\n foreach($items as $item){\n\n if($item-&gt;title === \"Link Title\"){ // this is the link label your searching for\n $item-&gt;url = \"http://newlink.com\"; //this is the new link\n }\n }\n return $items;\n }\n\n add_filter('wp_nav_menu_objects', 'update_menu_link', 10,2);\n</code></pre>\n" } ]
2016/08/14
[ "https://wordpress.stackexchange.com/questions/235893", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10241/" ]
I'm trying to display user [gravatars](http://en.gravatar.com/) on this page <http://gepc.themelot.com/survey-comparison/433747624/293281083/> but the page keeps showing the default '[mystery man](http://en.gravatar.com/site/implement/images/#default-image)' avatar. I inspected the page element and it returns the same URL with the same hash value for the gravatar link. Here is my code: ``` <?php if (!empty($matched_answers)) { ?> <h1><?php $user = get_user_by( 'user_login', $matched_answers[0]['user'] ); echo get_avatar( $user->ID , 256 ).' '.$matched_answers[0]['user'].' - '.round($matched_answers[0]['percentage'], 2).' &#37;'; ?></h1> <table border="0" width="100%"> <thead> <th>Name</th> <th>Percentage</th> </thead> <tbody> <?php foreach ($matched_answers as $value) { $user = get_user_by( 'user_login', $value['user'] ); $user_email = $user->user_email; $url = 'http://gravatar.com/avatar/' . md5( $user_email ); $url = add_query_arg( array( 's' => 48, 'd' => 'mm', ), $url ); $gravatar_url = esc_url_raw( $url ); echo '<tr>'; echo '<td>'.'<img src='.$gravatar_url.' />'.'<td>'; echo '<td>'.$value['user'] . '</td>'; echo '<td class="votepercent">' . round($value['percentage'], 2) . ' &#37;</td>'; echo '</tr>'; } ?> </tbody> </table> <?php } ?> ``` How do I return the user's actual gravatar image? What is wrong with my code? Thanks in advance.
You are on right track, with few minor kinks. 1. You need to modify `$atts` and return it. Any arguments after the first one are provided for information and should not be changed. 2. You need to tell `add_filter()` that you expect more than one argument. The example with some debug code would be along the lines of: ``` add_filter( 'nav_menu_link_attributes', function ( $atts, $item, $args, $depth ) { var_dump( $atts, $item ); // a lot of stuff we can use var_dump( $atts['href'] ); // string(36) "http://dev.rarst.net/our-philosophy/" var_dump( get_the_title( $item->object_id ) ); // string(14) "Our Philosophy", note $item itself is NOT a page if ( get_the_title( $item->object_id ) === 'Our Philosophy' ) { // for example $atts['href'] = 'https://example.com/'; } return $atts; }, 10, 4 ); // 4 so we get all arguments ```
235,905
<p>I'm working on creating a shortcode which is meant to change the css and js dynamically for that shortcode based on the situation. Now the problem is that I not getting a clue about how to use <code>add_action()</code> inside a <code>add_shortcode()</code>. Let me give you an example snippet code so that you guys can better understand me:</p> <pre><code>add_shortcode('example', function( $atts ) { //extracting the shortcode attributes extract( shortcode_atts( array( 'value1' =&gt; null, 'value2' =&gt; null, 'value3' =&gt; null ), $atts ) ); //Now here I wll do my code for the shortcode // But the shortcode needs some js and css to work // so, I'm trying like this //For the CSS add_action('wp_head', function() { echo '&lt;style type="text/css"&gt; .class { background-color: '. $value2 .'; } &lt;/style&gt;'; }); //For the JS add_action('wp_footer', function() { echo '&lt;script type="text/javascript"&gt; var a = '. $value3 .' &lt;/script&gt;'; }); }); </code></pre> <p>Now obviously it is not working, so I was hoping if any of you can guide me how to the similar thing in the proper way.</p> <p>If you can, please help instead of negative voting the question. </p>
[ { "answer_id": 235886, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": false, "text": "<p>You are on right track, with few minor kinks.</p>\n\n<ol>\n<li>You need to modify <code>$atts</code> and return it. Any arguments after the first one are provided for information and should not be changed.</li>\n<li>You need to tell <code>add_filter()</code> that you expect more than one argument.</li>\n</ol>\n\n<p>The example with some debug code would be along the lines of:</p>\n\n<pre><code>add_filter( 'nav_menu_link_attributes', function ( $atts, $item, $args, $depth ) {\n\n var_dump( $atts, $item ); // a lot of stuff we can use\n\n var_dump( $atts['href'] ); // string(36) \"http://dev.rarst.net/our-philosophy/\"\n\n var_dump( get_the_title( $item-&gt;object_id ) ); // string(14) \"Our Philosophy\", note $item itself is NOT a page\n\n if ( get_the_title( $item-&gt;object_id ) === 'Our Philosophy' ) { // for example\n\n $atts['href'] = 'https://example.com/';\n }\n\n return $atts;\n}, 10, 4 ); // 4 so we get all arguments\n</code></pre>\n" }, { "answer_id": 298729, "author": "dbmpls", "author_id": 97681, "author_profile": "https://wordpress.stackexchange.com/users/97681", "pm_score": 2, "selected": false, "text": "<p>This will allow you to update the URL for specific menu items. In the case of the OP, \"Link Title\" would be replaced with \"Our Philosophy\".</p>\n\n<p>This would be placed in your child theme's functions.php</p>\n\n<pre><code> function update_menu_link($items){\n\n //look through the menu for items with Label \"Link Title\"\n foreach($items as $item){\n\n if($item-&gt;title === \"Link Title\"){ // this is the link label your searching for\n $item-&gt;url = \"http://newlink.com\"; //this is the new link\n }\n }\n return $items;\n }\n\n add_filter('wp_nav_menu_objects', 'update_menu_link', 10,2);\n</code></pre>\n" } ]
2016/08/14
[ "https://wordpress.stackexchange.com/questions/235905", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50584/" ]
I'm working on creating a shortcode which is meant to change the css and js dynamically for that shortcode based on the situation. Now the problem is that I not getting a clue about how to use `add_action()` inside a `add_shortcode()`. Let me give you an example snippet code so that you guys can better understand me: ``` add_shortcode('example', function( $atts ) { //extracting the shortcode attributes extract( shortcode_atts( array( 'value1' => null, 'value2' => null, 'value3' => null ), $atts ) ); //Now here I wll do my code for the shortcode // But the shortcode needs some js and css to work // so, I'm trying like this //For the CSS add_action('wp_head', function() { echo '<style type="text/css"> .class { background-color: '. $value2 .'; } </style>'; }); //For the JS add_action('wp_footer', function() { echo '<script type="text/javascript"> var a = '. $value3 .' </script>'; }); }); ``` Now obviously it is not working, so I was hoping if any of you can guide me how to the similar thing in the proper way. If you can, please help instead of negative voting the question.
You are on right track, with few minor kinks. 1. You need to modify `$atts` and return it. Any arguments after the first one are provided for information and should not be changed. 2. You need to tell `add_filter()` that you expect more than one argument. The example with some debug code would be along the lines of: ``` add_filter( 'nav_menu_link_attributes', function ( $atts, $item, $args, $depth ) { var_dump( $atts, $item ); // a lot of stuff we can use var_dump( $atts['href'] ); // string(36) "http://dev.rarst.net/our-philosophy/" var_dump( get_the_title( $item->object_id ) ); // string(14) "Our Philosophy", note $item itself is NOT a page if ( get_the_title( $item->object_id ) === 'Our Philosophy' ) { // for example $atts['href'] = 'https://example.com/'; } return $atts; }, 10, 4 ); // 4 so we get all arguments ```
235,957
<p>I've created a shortcode for a sitemap page. When I make a change on the page and click update I get a headers already sent error. Below is my shortcode and the two error messages. I'm wondering if I need to work <code>ob_start()</code> and <code>ob_get_clean()</code> into my function but I'm not 100% positive how it should be formatted.</p> <pre><code>function site_map2( $atts ) { $atts = shortcode_atts( array( 'exclude' =&gt; '', ), $atts ); return '&lt;ul&gt;' . wp_list_pages('exclude=' . $atts['exclude'] . '&amp;sort_column=post_title&amp;title_li=') . '&lt;/ul&gt;'; } add_shortcode( 'SiteMap2', 'site_map2' ); </code></pre> <p>Here are the error messages:</p> <blockquote> <p>Warning: Cannot modify header information - headers already sent by (output started at /public_html/wp-includes/post-template.php:1205) in /public_html/wp-admin/post.php on line 197</p> <p>Warning: Cannot modify header information - headers already sent by (output started at /public_html/wp-includes/post-template.php:1205) in /public_html/wp-includes/pluggable.php on line 1167</p> </blockquote>
[ { "answer_id": 235958, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>You need to return the value from <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/\" rel=\"nofollow\"><code>wp_list_pages</code></a> and not <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/#parameters\" rel=\"nofollow\">'echo'</a> by default.</p>\n\n<blockquote>\n <p>'echo'</p>\n \n <p>(bool) Whether or not to echo the list of pages. Default true.</p>\n</blockquote>\n\n<pre><code>return '&lt;ul&gt;' . wp_list_pages( 'echo=false' . '&amp;exclude=' . $atts['exclude'] . '&amp;sort_column=post_title&amp;title_li=') . '&lt;/ul&gt;';\n</code></pre>\n" }, { "answer_id": 236159, "author": "brandozz", "author_id": 64789, "author_profile": "https://wordpress.stackexchange.com/users/64789", "pm_score": 4, "selected": true, "text": "<p>The adjustment to my function below fixed the issue but I wanted to make sure that this is the right way to handle the shortcode. I've added ob_start(); and ob_get_clean(); to the function. Is this the correct way to handle something like this?</p>\n\n<pre><code>function site_map2( $atts ) {\n $atts = shortcode_atts(\n array(\n 'exclude' =&gt; '',\n ), $atts );\n ob_start();\n echo '&lt;ul&gt;' . wp_list_pages('echo=false' . '&amp;exclude=' . $atts['exclude'] . '&amp;sort_column=post_title&amp;title_li=') . '&lt;/ul&gt;';\n return ob_get_clean();\n}\nadd_shortcode( 'SiteMap2', 'site_map2' );\n</code></pre>\n" } ]
2016/08/15
[ "https://wordpress.stackexchange.com/questions/235957", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64789/" ]
I've created a shortcode for a sitemap page. When I make a change on the page and click update I get a headers already sent error. Below is my shortcode and the two error messages. I'm wondering if I need to work `ob_start()` and `ob_get_clean()` into my function but I'm not 100% positive how it should be formatted. ``` function site_map2( $atts ) { $atts = shortcode_atts( array( 'exclude' => '', ), $atts ); return '<ul>' . wp_list_pages('exclude=' . $atts['exclude'] . '&sort_column=post_title&title_li=') . '</ul>'; } add_shortcode( 'SiteMap2', 'site_map2' ); ``` Here are the error messages: > > Warning: Cannot modify header information - headers already sent by (output started at /public\_html/wp-includes/post-template.php:1205) in /public\_html/wp-admin/post.php on line 197 > > > Warning: Cannot modify header information - headers already sent by (output started at /public\_html/wp-includes/post-template.php:1205) in /public\_html/wp-includes/pluggable.php on line 1167 > > >
The adjustment to my function below fixed the issue but I wanted to make sure that this is the right way to handle the shortcode. I've added ob\_start(); and ob\_get\_clean(); to the function. Is this the correct way to handle something like this? ``` function site_map2( $atts ) { $atts = shortcode_atts( array( 'exclude' => '', ), $atts ); ob_start(); echo '<ul>' . wp_list_pages('echo=false' . '&exclude=' . $atts['exclude'] . '&sort_column=post_title&title_li=') . '</ul>'; return ob_get_clean(); } add_shortcode( 'SiteMap2', 'site_map2' ); ```
235,993
<p>In my plugin settings page, I have a list of checkboxes that store the value into an array. While the it works as expected, whenever I uncheck all of the checkboxes and save those changes I get the following error:</p> <blockquote> <p><strong>Notice: Undefined index:</strong> <em>remove_field</em> in ...\settings-profile.php on line 19</p> </blockquote> <p>Below is the code in question:</p> <pre><code>if ( isset( $_POST['dsbl_options'] ) &amp;&amp; !empty( $_POST['dsbl_options'] ) ) { update_option( 'dsbl_remove', $_POST['remove_field'] ); // (Line 19) } </code></pre> <p>The rest of the source code can be found here: <a href="https://github.com/factmaven/disable-blogging/blob/dev/includes/settings-profile.php" rel="nofollow">GitHub</a></p> <p>From doing research online for a similar error, I see that the recommendation is to wrap <code>$_POST['remove_field']</code> with an <code>isset</code>. However, this does not store the values form the checkboxes in the plugin settings.</p> <p>As mentioned above, this error shows up only when all of the checkboxes are unchecked and saved. It looks like there is an issue when saving an empty value in the array. Although the plugin settings works as expected, I'd like to fix this.</p>
[ { "answer_id": 236001, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 3, "selected": true, "text": "<p>I'm not seeing the original snippet from before so I'm not sure of the context anymore. The undefined index notice you are getting is telling you that <code>$_POST['remove_fiel‌​d']</code> does not exist. If no checkbox in your array was set, the <code>$_POST</code> array will not have an index for <code>'remove_field'</code>, and you'll see the error.</p>\n\n<p>To prevent this from happening, ensure it exists:</p>\n\n<pre><code>if ( isset( $_POST['remove_field'] ) ) {\n // do stuff with the values\n}\n</code></pre>\n\n<p>When in an OO context the more frequent solution is to bail out if no value exists so you would reverse your condition:</p>\n\n<pre><code>if ( !isset( $_POST['remove_field'] ) ) {\n return;\n}\n</code></pre>\n" }, { "answer_id": 236023, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 1, "selected": false, "text": "<p>As mentioned <a href=\"https://wordpress.org/support/topic/undefined-index-error-when-saving-empty-array-with-checkboxes?replies=3#post-8758531\" rel=\"nofollow\">here</a> (thanks to <a href=\"https://wordpress.org/support/profile/bcworkz\" rel=\"nofollow\">bcworkz</a>), I was able to fix the issue by inserting <code>NULL</code> if all of the checkboxes are unchecked:</p>\n\n<pre><code>if ( isset( $_POST['dsbl_options'] ) &amp;&amp; !empty( $_POST['dsbl_options'] ) ) {\n if ( array_key_exists('remove_field', $_POST )) {\n update_option( 'dsbl_remove', $_POST['remove_field'] );\n }\n else { // When all options are unchecked, set array to null\n update_option( 'dsbl_remove', NULL );\n }\n}\n</code></pre>\n" } ]
2016/08/15
[ "https://wordpress.stackexchange.com/questions/235993", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98212/" ]
In my plugin settings page, I have a list of checkboxes that store the value into an array. While the it works as expected, whenever I uncheck all of the checkboxes and save those changes I get the following error: > > **Notice: Undefined index:** *remove\_field* in ...\settings-profile.php on line 19 > > > Below is the code in question: ``` if ( isset( $_POST['dsbl_options'] ) && !empty( $_POST['dsbl_options'] ) ) { update_option( 'dsbl_remove', $_POST['remove_field'] ); // (Line 19) } ``` The rest of the source code can be found here: [GitHub](https://github.com/factmaven/disable-blogging/blob/dev/includes/settings-profile.php) From doing research online for a similar error, I see that the recommendation is to wrap `$_POST['remove_field']` with an `isset`. However, this does not store the values form the checkboxes in the plugin settings. As mentioned above, this error shows up only when all of the checkboxes are unchecked and saved. It looks like there is an issue when saving an empty value in the array. Although the plugin settings works as expected, I'd like to fix this.
I'm not seeing the original snippet from before so I'm not sure of the context anymore. The undefined index notice you are getting is telling you that `$_POST['remove_fiel‌​d']` does not exist. If no checkbox in your array was set, the `$_POST` array will not have an index for `'remove_field'`, and you'll see the error. To prevent this from happening, ensure it exists: ``` if ( isset( $_POST['remove_field'] ) ) { // do stuff with the values } ``` When in an OO context the more frequent solution is to bail out if no value exists so you would reverse your condition: ``` if ( !isset( $_POST['remove_field'] ) ) { return; } ```
236,003
<p>When uploading a site logo, I get a 403 Forbidden HTTP error.</p> <p>Also, the Inspect Element preview shows this page:</p> <p><a href="https://i.stack.imgur.com/JiO23.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JiO23.jpg" alt="enter image description here"></a></p> <p>On the site itself, it just says "http error". I tried disabling nonces, no change. I had done <code>chmod -R 750 &lt;web root dir&gt;</code> and <code>chown -R www-data:www-data &lt;web root dir&gt;</code> too, so I assume permissions are not the issue. (Yes, php-fpm and my web server are running as www-data.)</p> <p>This is a default install from Wordpress stable version. I have removed my plugins folder too, no change. My web server is NGINX.</p>
[ { "answer_id": 236001, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 3, "selected": true, "text": "<p>I'm not seeing the original snippet from before so I'm not sure of the context anymore. The undefined index notice you are getting is telling you that <code>$_POST['remove_fiel‌​d']</code> does not exist. If no checkbox in your array was set, the <code>$_POST</code> array will not have an index for <code>'remove_field'</code>, and you'll see the error.</p>\n\n<p>To prevent this from happening, ensure it exists:</p>\n\n<pre><code>if ( isset( $_POST['remove_field'] ) ) {\n // do stuff with the values\n}\n</code></pre>\n\n<p>When in an OO context the more frequent solution is to bail out if no value exists so you would reverse your condition:</p>\n\n<pre><code>if ( !isset( $_POST['remove_field'] ) ) {\n return;\n}\n</code></pre>\n" }, { "answer_id": 236023, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 1, "selected": false, "text": "<p>As mentioned <a href=\"https://wordpress.org/support/topic/undefined-index-error-when-saving-empty-array-with-checkboxes?replies=3#post-8758531\" rel=\"nofollow\">here</a> (thanks to <a href=\"https://wordpress.org/support/profile/bcworkz\" rel=\"nofollow\">bcworkz</a>), I was able to fix the issue by inserting <code>NULL</code> if all of the checkboxes are unchecked:</p>\n\n<pre><code>if ( isset( $_POST['dsbl_options'] ) &amp;&amp; !empty( $_POST['dsbl_options'] ) ) {\n if ( array_key_exists('remove_field', $_POST )) {\n update_option( 'dsbl_remove', $_POST['remove_field'] );\n }\n else { // When all options are unchecked, set array to null\n update_option( 'dsbl_remove', NULL );\n }\n}\n</code></pre>\n" } ]
2016/08/15
[ "https://wordpress.stackexchange.com/questions/236003", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101064/" ]
When uploading a site logo, I get a 403 Forbidden HTTP error. Also, the Inspect Element preview shows this page: [![enter image description here](https://i.stack.imgur.com/JiO23.jpg)](https://i.stack.imgur.com/JiO23.jpg) On the site itself, it just says "http error". I tried disabling nonces, no change. I had done `chmod -R 750 <web root dir>` and `chown -R www-data:www-data <web root dir>` too, so I assume permissions are not the issue. (Yes, php-fpm and my web server are running as www-data.) This is a default install from Wordpress stable version. I have removed my plugins folder too, no change. My web server is NGINX.
I'm not seeing the original snippet from before so I'm not sure of the context anymore. The undefined index notice you are getting is telling you that `$_POST['remove_fiel‌​d']` does not exist. If no checkbox in your array was set, the `$_POST` array will not have an index for `'remove_field'`, and you'll see the error. To prevent this from happening, ensure it exists: ``` if ( isset( $_POST['remove_field'] ) ) { // do stuff with the values } ``` When in an OO context the more frequent solution is to bail out if no value exists so you would reverse your condition: ``` if ( !isset( $_POST['remove_field'] ) ) { return; } ```
236,026
<p>I just create a simple WordPress theme, everything looks fine but when I use a plugins which need shortcode.</p> <p>I put the short code in a page (like this [user-submitted-pos‌​ts]), on front end, it show same short code. When I change to another theme, the short code works fine.</p> <p>Shortcode doesn't work, is this need function.php support it?</p>
[ { "answer_id": 236029, "author": "anmari", "author_id": 3569, "author_profile": "https://wordpress.stackexchange.com/users/3569", "pm_score": 1, "selected": false, "text": "<p>Suggest you look at one of the twenty-x themes to see what's different and read up on using \"apply_filters('the_content',....) before outputting the page or post content.</p>\n" }, { "answer_id": 263516, "author": "Monica Maria Crapanzano", "author_id": 83588, "author_profile": "https://wordpress.stackexchange.com/users/83588", "pm_score": 3, "selected": true, "text": "<p>You should add to theme something like this:</p>\n\n<pre><code>add_filter('shortcode_function_name', 'do_shortcode');\n</code></pre>\n\n<p>This should be enough. \nHere you can find the documentation related to the shortcodes:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/do_shortcode/</a></p>\n" }, { "answer_id": 263537, "author": "ciaika", "author_id": 48497, "author_profile": "https://wordpress.stackexchange.com/users/48497", "pm_score": 0, "selected": false, "text": "<p>If the shortcode is added to the excerpt or widgets areas, then you have to add the following code into the \"functions.php\" file from your main or child theme folder:</p>\n\n<pre>// Adding Shortcodes to the_excerpt() function\nadd_filter('the_excerpt', 'do_shortcode');\n\n// Enable shortcodes in widgets\nadd_filter('widget_text', 'do_shortcode');</pre>\n" } ]
2016/08/16
[ "https://wordpress.stackexchange.com/questions/236026", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31425/" ]
I just create a simple WordPress theme, everything looks fine but when I use a plugins which need shortcode. I put the short code in a page (like this [user-submitted-pos‌​ts]), on front end, it show same short code. When I change to another theme, the short code works fine. Shortcode doesn't work, is this need function.php support it?
You should add to theme something like this: ``` add_filter('shortcode_function_name', 'do_shortcode'); ``` This should be enough. Here you can find the documentation related to the shortcodes: <https://developer.wordpress.org/reference/functions/do_shortcode/>
236,063
<p>I am adding the variable product in woocommerce pragmatically but the product created in the admin panel is always a simple product. I am using the following code to set the product type variable.</p> <pre><code>$producttype = wp_set_object_terms($post_id, 'variable', 'product_type'); </code></pre> <p>When I print the output in <code>$producttype</code> it says "Invalid taxonomy". </p> <p>What is the problem behind this ?</p>
[ { "answer_id": 237174, "author": "SuperNERD", "author_id": 101671, "author_profile": "https://wordpress.stackexchange.com/users/101671", "pm_score": 1, "selected": false, "text": "<p>Not sure exactly where you're adding that code, but there is a generally accepted way of doing this, which is outlined pretty well here: <a href=\"https://wordpress.stackexchange.com/questions/120215/how-to-add-a-new-product-type-on-woocommerce-product-types/120220\">How to add a new product type on woocommerce product types?</a></p>\n\n<p>There are 2 ways of doing this in the Wordpress/Woocommerce \"recommended\" types of approaches. </p>\n\n<p>1) Copying the files that need these new classes etc into your themes folder into an identical folder structured /woocommerce folder. Technically of course you'll have to re-copy that folder over if you ever update your theme. </p>\n\n<p>2) You can also just do it all in your theme's functions.php file, which is what I did. </p>\n\n<p>/////////////////////////////////</p>\n\n<p>This is exactly what my code starts out like (and you can see where product_type is declared as ta_fundraising_campaign below):</p>\n\n<pre><code>/*******************************************************************************\n * Fundraising custom product_type for WooCommerce.\n ******************************************************************************/\n\n// add a product type\nadd_filter('product_type_selector', 'ta_add_custom_product_type');\nfunction ta_add_custom_product_type($types)\n{\n $types['ta_fundraising_campaign'] = __('Fundraising Campaign');\n return $types;\n}\n\n// create product class on plugins_loaded hook\nadd_action('plugins_loaded', 'ta_create_custom_product_type');\nfunction ta_create_custom_product_type()\n{\n // declare the product class\n class WC_Product_FundRaisingCampaign\n extends WC_Product\n {\n public function __construct($product)\n {\n $product-&gt;product_type = 'ta_fundraising_campaign';\n parent::__construct($product); \n }\n }\n}\n\n/////////////////////////////////\n</code></pre>\n\n<p>Now here's the tricky part - because there is practically NO support out there on the internet for adding custom product_types for variable product_types.</p>\n\n<p>If, you're trying to make your own variable custom product_type, then you'll probably want to add back some of the \"Settings\" ie. Data Panels that allow you to choose different options like Attributes, Inventory and Variations. </p>\n\n<p>****** This is how you add those: *******</p>\n\n<pre><code>add_filter('woocommerce_product_data_tabs', function($tabs) {\n\n array_push($tabs['inventory']['class'], 'show_if_variable show_if_membership show_if_ta_fundraising_campaign');\n array_push($tabs['variations']['class'], 'show_if_membership show_if_ta_fundraising_campaign');\n\n return $tabs;\n\n }, 10, 1); \n</code></pre>\n\n<p>And then, for some reason the \"Used for variations\" checkbox may not show under the Attributes tab. So you may want to copy the file that it's in over to your theme folder and then add a show_if to the class, like this: </p>\n\n<p>This is the file where the checkbox is (copy it into a woocommerce folder in <strong><em>your</em></strong> theme's folder with the exact same structure ie. /yourtheme/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php):</p>\n\n<p>plugins/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php</p>\n\n<p>Then towards the bottom of that file you'll see the checkbox (below). But, notice how the div class has 2 show_if classes....the 2nd one is the one I added to show it on my custom product_type. Hope all this helps some others because it took me forever to figure all this out!!</p>\n\n<pre><code>&lt;div class=\"enable_variation show_if_variable show_if_ta_fundraising_campaign\"&gt;\n &lt;label&gt;&lt;input type=\"checkbox\" class=\"checkbox\" &lt;?php checked( $attribute['is_variation'], 1 ); ?&gt; name=\"attribute_variation[&lt;?php echo $i; ?&gt;]\" value=\"1\" /&gt; &lt;?php _e( 'Used for variations', 'woocommerce' ); ?&gt;&lt;/label&gt;\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 238067, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 0, "selected": false, "text": "<p>You problem is that your taxonomy is <strong>not registered</strong>. Take a look at the output of <a href=\"https://developer.wordpress.org/reference/functions/get_taxonomies/\" rel=\"nofollow\"><code>get_taxonomies()</code></a> at the end of your page to see which taxonomies are available:</p>\n\n<pre><code>add_action( 'shutdown', function() {\n printf( '&lt;pre&gt;%s&lt;/pre&gt;', var_export( get_taxonomies(), TRUE ) );\n}, PHP_MAX_INT -1 );\n</code></pre>\n" } ]
2016/08/16
[ "https://wordpress.stackexchange.com/questions/236063", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83446/" ]
I am adding the variable product in woocommerce pragmatically but the product created in the admin panel is always a simple product. I am using the following code to set the product type variable. ``` $producttype = wp_set_object_terms($post_id, 'variable', 'product_type'); ``` When I print the output in `$producttype` it says "Invalid taxonomy". What is the problem behind this ?
Not sure exactly where you're adding that code, but there is a generally accepted way of doing this, which is outlined pretty well here: [How to add a new product type on woocommerce product types?](https://wordpress.stackexchange.com/questions/120215/how-to-add-a-new-product-type-on-woocommerce-product-types/120220) There are 2 ways of doing this in the Wordpress/Woocommerce "recommended" types of approaches. 1) Copying the files that need these new classes etc into your themes folder into an identical folder structured /woocommerce folder. Technically of course you'll have to re-copy that folder over if you ever update your theme. 2) You can also just do it all in your theme's functions.php file, which is what I did. ///////////////////////////////// This is exactly what my code starts out like (and you can see where product\_type is declared as ta\_fundraising\_campaign below): ``` /******************************************************************************* * Fundraising custom product_type for WooCommerce. ******************************************************************************/ // add a product type add_filter('product_type_selector', 'ta_add_custom_product_type'); function ta_add_custom_product_type($types) { $types['ta_fundraising_campaign'] = __('Fundraising Campaign'); return $types; } // create product class on plugins_loaded hook add_action('plugins_loaded', 'ta_create_custom_product_type'); function ta_create_custom_product_type() { // declare the product class class WC_Product_FundRaisingCampaign extends WC_Product { public function __construct($product) { $product->product_type = 'ta_fundraising_campaign'; parent::__construct($product); } } } ///////////////////////////////// ``` Now here's the tricky part - because there is practically NO support out there on the internet for adding custom product\_types for variable product\_types. If, you're trying to make your own variable custom product\_type, then you'll probably want to add back some of the "Settings" ie. Data Panels that allow you to choose different options like Attributes, Inventory and Variations. \*\*\*\*\*\* This is how you add those: \*\*\*\*\*\*\* ``` add_filter('woocommerce_product_data_tabs', function($tabs) { array_push($tabs['inventory']['class'], 'show_if_variable show_if_membership show_if_ta_fundraising_campaign'); array_push($tabs['variations']['class'], 'show_if_membership show_if_ta_fundraising_campaign'); return $tabs; }, 10, 1); ``` And then, for some reason the "Used for variations" checkbox may not show under the Attributes tab. So you may want to copy the file that it's in over to your theme folder and then add a show\_if to the class, like this: This is the file where the checkbox is (copy it into a woocommerce folder in ***your*** theme's folder with the exact same structure ie. /yourtheme/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php): plugins/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php Then towards the bottom of that file you'll see the checkbox (below). But, notice how the div class has 2 show\_if classes....the 2nd one is the one I added to show it on my custom product\_type. Hope all this helps some others because it took me forever to figure all this out!! ``` <div class="enable_variation show_if_variable show_if_ta_fundraising_campaign"> <label><input type="checkbox" class="checkbox" <?php checked( $attribute['is_variation'], 1 ); ?> name="attribute_variation[<?php echo $i; ?>]" value="1" /> <?php _e( 'Used for variations', 'woocommerce' ); ?></label> </div> ```
236,069
<p>Recently I uploaded a WordPress site, but the page url still displays the old test site url, and the place where my new url is displaying doesnt get the page.</p>
[ { "answer_id": 237174, "author": "SuperNERD", "author_id": 101671, "author_profile": "https://wordpress.stackexchange.com/users/101671", "pm_score": 1, "selected": false, "text": "<p>Not sure exactly where you're adding that code, but there is a generally accepted way of doing this, which is outlined pretty well here: <a href=\"https://wordpress.stackexchange.com/questions/120215/how-to-add-a-new-product-type-on-woocommerce-product-types/120220\">How to add a new product type on woocommerce product types?</a></p>\n\n<p>There are 2 ways of doing this in the Wordpress/Woocommerce \"recommended\" types of approaches. </p>\n\n<p>1) Copying the files that need these new classes etc into your themes folder into an identical folder structured /woocommerce folder. Technically of course you'll have to re-copy that folder over if you ever update your theme. </p>\n\n<p>2) You can also just do it all in your theme's functions.php file, which is what I did. </p>\n\n<p>/////////////////////////////////</p>\n\n<p>This is exactly what my code starts out like (and you can see where product_type is declared as ta_fundraising_campaign below):</p>\n\n<pre><code>/*******************************************************************************\n * Fundraising custom product_type for WooCommerce.\n ******************************************************************************/\n\n// add a product type\nadd_filter('product_type_selector', 'ta_add_custom_product_type');\nfunction ta_add_custom_product_type($types)\n{\n $types['ta_fundraising_campaign'] = __('Fundraising Campaign');\n return $types;\n}\n\n// create product class on plugins_loaded hook\nadd_action('plugins_loaded', 'ta_create_custom_product_type');\nfunction ta_create_custom_product_type()\n{\n // declare the product class\n class WC_Product_FundRaisingCampaign\n extends WC_Product\n {\n public function __construct($product)\n {\n $product-&gt;product_type = 'ta_fundraising_campaign';\n parent::__construct($product); \n }\n }\n}\n\n/////////////////////////////////\n</code></pre>\n\n<p>Now here's the tricky part - because there is practically NO support out there on the internet for adding custom product_types for variable product_types.</p>\n\n<p>If, you're trying to make your own variable custom product_type, then you'll probably want to add back some of the \"Settings\" ie. Data Panels that allow you to choose different options like Attributes, Inventory and Variations. </p>\n\n<p>****** This is how you add those: *******</p>\n\n<pre><code>add_filter('woocommerce_product_data_tabs', function($tabs) {\n\n array_push($tabs['inventory']['class'], 'show_if_variable show_if_membership show_if_ta_fundraising_campaign');\n array_push($tabs['variations']['class'], 'show_if_membership show_if_ta_fundraising_campaign');\n\n return $tabs;\n\n }, 10, 1); \n</code></pre>\n\n<p>And then, for some reason the \"Used for variations\" checkbox may not show under the Attributes tab. So you may want to copy the file that it's in over to your theme folder and then add a show_if to the class, like this: </p>\n\n<p>This is the file where the checkbox is (copy it into a woocommerce folder in <strong><em>your</em></strong> theme's folder with the exact same structure ie. /yourtheme/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php):</p>\n\n<p>plugins/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php</p>\n\n<p>Then towards the bottom of that file you'll see the checkbox (below). But, notice how the div class has 2 show_if classes....the 2nd one is the one I added to show it on my custom product_type. Hope all this helps some others because it took me forever to figure all this out!!</p>\n\n<pre><code>&lt;div class=\"enable_variation show_if_variable show_if_ta_fundraising_campaign\"&gt;\n &lt;label&gt;&lt;input type=\"checkbox\" class=\"checkbox\" &lt;?php checked( $attribute['is_variation'], 1 ); ?&gt; name=\"attribute_variation[&lt;?php echo $i; ?&gt;]\" value=\"1\" /&gt; &lt;?php _e( 'Used for variations', 'woocommerce' ); ?&gt;&lt;/label&gt;\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 238067, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 0, "selected": false, "text": "<p>You problem is that your taxonomy is <strong>not registered</strong>. Take a look at the output of <a href=\"https://developer.wordpress.org/reference/functions/get_taxonomies/\" rel=\"nofollow\"><code>get_taxonomies()</code></a> at the end of your page to see which taxonomies are available:</p>\n\n<pre><code>add_action( 'shutdown', function() {\n printf( '&lt;pre&gt;%s&lt;/pre&gt;', var_export( get_taxonomies(), TRUE ) );\n}, PHP_MAX_INT -1 );\n</code></pre>\n" } ]
2016/08/16
[ "https://wordpress.stackexchange.com/questions/236069", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101095/" ]
Recently I uploaded a WordPress site, but the page url still displays the old test site url, and the place where my new url is displaying doesnt get the page.
Not sure exactly where you're adding that code, but there is a generally accepted way of doing this, which is outlined pretty well here: [How to add a new product type on woocommerce product types?](https://wordpress.stackexchange.com/questions/120215/how-to-add-a-new-product-type-on-woocommerce-product-types/120220) There are 2 ways of doing this in the Wordpress/Woocommerce "recommended" types of approaches. 1) Copying the files that need these new classes etc into your themes folder into an identical folder structured /woocommerce folder. Technically of course you'll have to re-copy that folder over if you ever update your theme. 2) You can also just do it all in your theme's functions.php file, which is what I did. ///////////////////////////////// This is exactly what my code starts out like (and you can see where product\_type is declared as ta\_fundraising\_campaign below): ``` /******************************************************************************* * Fundraising custom product_type for WooCommerce. ******************************************************************************/ // add a product type add_filter('product_type_selector', 'ta_add_custom_product_type'); function ta_add_custom_product_type($types) { $types['ta_fundraising_campaign'] = __('Fundraising Campaign'); return $types; } // create product class on plugins_loaded hook add_action('plugins_loaded', 'ta_create_custom_product_type'); function ta_create_custom_product_type() { // declare the product class class WC_Product_FundRaisingCampaign extends WC_Product { public function __construct($product) { $product->product_type = 'ta_fundraising_campaign'; parent::__construct($product); } } } ///////////////////////////////// ``` Now here's the tricky part - because there is practically NO support out there on the internet for adding custom product\_types for variable product\_types. If, you're trying to make your own variable custom product\_type, then you'll probably want to add back some of the "Settings" ie. Data Panels that allow you to choose different options like Attributes, Inventory and Variations. \*\*\*\*\*\* This is how you add those: \*\*\*\*\*\*\* ``` add_filter('woocommerce_product_data_tabs', function($tabs) { array_push($tabs['inventory']['class'], 'show_if_variable show_if_membership show_if_ta_fundraising_campaign'); array_push($tabs['variations']['class'], 'show_if_membership show_if_ta_fundraising_campaign'); return $tabs; }, 10, 1); ``` And then, for some reason the "Used for variations" checkbox may not show under the Attributes tab. So you may want to copy the file that it's in over to your theme folder and then add a show\_if to the class, like this: This is the file where the checkbox is (copy it into a woocommerce folder in ***your*** theme's folder with the exact same structure ie. /yourtheme/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php): plugins/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php Then towards the bottom of that file you'll see the checkbox (below). But, notice how the div class has 2 show\_if classes....the 2nd one is the one I added to show it on my custom product\_type. Hope all this helps some others because it took me forever to figure all this out!! ``` <div class="enable_variation show_if_variable show_if_ta_fundraising_campaign"> <label><input type="checkbox" class="checkbox" <?php checked( $attribute['is_variation'], 1 ); ?> name="attribute_variation[<?php echo $i; ?>]" value="1" /> <?php _e( 'Used for variations', 'woocommerce' ); ?></label> </div> ```
236,071
<p>I want to use a one taxonomy of two CPT. But I want to have different URL.</p> <p>Like this:</p> <p><strong>city</strong> - taxonomy (taxonomy data is used in two CPT)</p> <p><strong>people</strong> - CPT</p> <p><strong>car</strong> - CPT</p> <p>I want:</p> <p>site.com/people/born/LA</p> <p>site.com/car/place/LA</p> <p>Thus in the first case I show people born in the LA, and in the second case, cars being in LA</p>
[ { "answer_id": 237174, "author": "SuperNERD", "author_id": 101671, "author_profile": "https://wordpress.stackexchange.com/users/101671", "pm_score": 1, "selected": false, "text": "<p>Not sure exactly where you're adding that code, but there is a generally accepted way of doing this, which is outlined pretty well here: <a href=\"https://wordpress.stackexchange.com/questions/120215/how-to-add-a-new-product-type-on-woocommerce-product-types/120220\">How to add a new product type on woocommerce product types?</a></p>\n\n<p>There are 2 ways of doing this in the Wordpress/Woocommerce \"recommended\" types of approaches. </p>\n\n<p>1) Copying the files that need these new classes etc into your themes folder into an identical folder structured /woocommerce folder. Technically of course you'll have to re-copy that folder over if you ever update your theme. </p>\n\n<p>2) You can also just do it all in your theme's functions.php file, which is what I did. </p>\n\n<p>/////////////////////////////////</p>\n\n<p>This is exactly what my code starts out like (and you can see where product_type is declared as ta_fundraising_campaign below):</p>\n\n<pre><code>/*******************************************************************************\n * Fundraising custom product_type for WooCommerce.\n ******************************************************************************/\n\n// add a product type\nadd_filter('product_type_selector', 'ta_add_custom_product_type');\nfunction ta_add_custom_product_type($types)\n{\n $types['ta_fundraising_campaign'] = __('Fundraising Campaign');\n return $types;\n}\n\n// create product class on plugins_loaded hook\nadd_action('plugins_loaded', 'ta_create_custom_product_type');\nfunction ta_create_custom_product_type()\n{\n // declare the product class\n class WC_Product_FundRaisingCampaign\n extends WC_Product\n {\n public function __construct($product)\n {\n $product-&gt;product_type = 'ta_fundraising_campaign';\n parent::__construct($product); \n }\n }\n}\n\n/////////////////////////////////\n</code></pre>\n\n<p>Now here's the tricky part - because there is practically NO support out there on the internet for adding custom product_types for variable product_types.</p>\n\n<p>If, you're trying to make your own variable custom product_type, then you'll probably want to add back some of the \"Settings\" ie. Data Panels that allow you to choose different options like Attributes, Inventory and Variations. </p>\n\n<p>****** This is how you add those: *******</p>\n\n<pre><code>add_filter('woocommerce_product_data_tabs', function($tabs) {\n\n array_push($tabs['inventory']['class'], 'show_if_variable show_if_membership show_if_ta_fundraising_campaign');\n array_push($tabs['variations']['class'], 'show_if_membership show_if_ta_fundraising_campaign');\n\n return $tabs;\n\n }, 10, 1); \n</code></pre>\n\n<p>And then, for some reason the \"Used for variations\" checkbox may not show under the Attributes tab. So you may want to copy the file that it's in over to your theme folder and then add a show_if to the class, like this: </p>\n\n<p>This is the file where the checkbox is (copy it into a woocommerce folder in <strong><em>your</em></strong> theme's folder with the exact same structure ie. /yourtheme/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php):</p>\n\n<p>plugins/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php</p>\n\n<p>Then towards the bottom of that file you'll see the checkbox (below). But, notice how the div class has 2 show_if classes....the 2nd one is the one I added to show it on my custom product_type. Hope all this helps some others because it took me forever to figure all this out!!</p>\n\n<pre><code>&lt;div class=\"enable_variation show_if_variable show_if_ta_fundraising_campaign\"&gt;\n &lt;label&gt;&lt;input type=\"checkbox\" class=\"checkbox\" &lt;?php checked( $attribute['is_variation'], 1 ); ?&gt; name=\"attribute_variation[&lt;?php echo $i; ?&gt;]\" value=\"1\" /&gt; &lt;?php _e( 'Used for variations', 'woocommerce' ); ?&gt;&lt;/label&gt;\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 238067, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 0, "selected": false, "text": "<p>You problem is that your taxonomy is <strong>not registered</strong>. Take a look at the output of <a href=\"https://developer.wordpress.org/reference/functions/get_taxonomies/\" rel=\"nofollow\"><code>get_taxonomies()</code></a> at the end of your page to see which taxonomies are available:</p>\n\n<pre><code>add_action( 'shutdown', function() {\n printf( '&lt;pre&gt;%s&lt;/pre&gt;', var_export( get_taxonomies(), TRUE ) );\n}, PHP_MAX_INT -1 );\n</code></pre>\n" } ]
2016/08/16
[ "https://wordpress.stackexchange.com/questions/236071", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60574/" ]
I want to use a one taxonomy of two CPT. But I want to have different URL. Like this: **city** - taxonomy (taxonomy data is used in two CPT) **people** - CPT **car** - CPT I want: site.com/people/born/LA site.com/car/place/LA Thus in the first case I show people born in the LA, and in the second case, cars being in LA
Not sure exactly where you're adding that code, but there is a generally accepted way of doing this, which is outlined pretty well here: [How to add a new product type on woocommerce product types?](https://wordpress.stackexchange.com/questions/120215/how-to-add-a-new-product-type-on-woocommerce-product-types/120220) There are 2 ways of doing this in the Wordpress/Woocommerce "recommended" types of approaches. 1) Copying the files that need these new classes etc into your themes folder into an identical folder structured /woocommerce folder. Technically of course you'll have to re-copy that folder over if you ever update your theme. 2) You can also just do it all in your theme's functions.php file, which is what I did. ///////////////////////////////// This is exactly what my code starts out like (and you can see where product\_type is declared as ta\_fundraising\_campaign below): ``` /******************************************************************************* * Fundraising custom product_type for WooCommerce. ******************************************************************************/ // add a product type add_filter('product_type_selector', 'ta_add_custom_product_type'); function ta_add_custom_product_type($types) { $types['ta_fundraising_campaign'] = __('Fundraising Campaign'); return $types; } // create product class on plugins_loaded hook add_action('plugins_loaded', 'ta_create_custom_product_type'); function ta_create_custom_product_type() { // declare the product class class WC_Product_FundRaisingCampaign extends WC_Product { public function __construct($product) { $product->product_type = 'ta_fundraising_campaign'; parent::__construct($product); } } } ///////////////////////////////// ``` Now here's the tricky part - because there is practically NO support out there on the internet for adding custom product\_types for variable product\_types. If, you're trying to make your own variable custom product\_type, then you'll probably want to add back some of the "Settings" ie. Data Panels that allow you to choose different options like Attributes, Inventory and Variations. \*\*\*\*\*\* This is how you add those: \*\*\*\*\*\*\* ``` add_filter('woocommerce_product_data_tabs', function($tabs) { array_push($tabs['inventory']['class'], 'show_if_variable show_if_membership show_if_ta_fundraising_campaign'); array_push($tabs['variations']['class'], 'show_if_membership show_if_ta_fundraising_campaign'); return $tabs; }, 10, 1); ``` And then, for some reason the "Used for variations" checkbox may not show under the Attributes tab. So you may want to copy the file that it's in over to your theme folder and then add a show\_if to the class, like this: This is the file where the checkbox is (copy it into a woocommerce folder in ***your*** theme's folder with the exact same structure ie. /yourtheme/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php): plugins/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php Then towards the bottom of that file you'll see the checkbox (below). But, notice how the div class has 2 show\_if classes....the 2nd one is the one I added to show it on my custom product\_type. Hope all this helps some others because it took me forever to figure all this out!! ``` <div class="enable_variation show_if_variable show_if_ta_fundraising_campaign"> <label><input type="checkbox" class="checkbox" <?php checked( $attribute['is_variation'], 1 ); ?> name="attribute_variation[<?php echo $i; ?>]" value="1" /> <?php _e( 'Used for variations', 'woocommerce' ); ?></label> </div> ```
236,081
<p>I've been messing around with rewrites and <code>query_var</code> to generate some listings, for example:</p> <ul> <li>~/my-page/?my_var=1</li> <li>~/my-page/?my_var=2</li> <li>~/my-page/?my_var=3</li> </ul> <p>After perusing StackExchange and the interwebs a bit, it seems that the overwhelming consensus is that <a href="https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint" rel="nofollow">add_rewrite_endpoint</a> is the way to go. As such, I've implemented the following:</p> <pre><code>function wpd_add_my_endpoint(){ add_rewrite_endpoint( 'my_var', EP_PAGES ); } add_action( 'init', 'wpd_add_my_endpoint' ); </code></pre> <p>This yields the following URIs based on the ones I mentioned previously:</p> <ul> <li>~/my-page/my_var/1</li> <li>~/my-page/my_var/2</li> <li>~/my-page/my_var/3</li> </ul> <p>However, I would like to strip out the 'endpoint base' (or slug, not even sure what to call this exactly, in this question/example 'my_var'), so that the URIs would be:</p> <ul> <li>~/my-page/1/</li> <li>~/my-page/2/</li> <li>~/my-page/3/</li> </ul> <p>I've tried a bunch of different ways to do rewrites, but none to any avail, this is what I have so far, which isn't working:</p> <pre><code>function setup_filter_rewrites(){ add_rewrite_rule('my-page/([^/]*)/?', 'index.php?pagename=my-page&amp;my_var=$matches[1]', 'top'); } add_action( 'init', 'setup_filter_rewrites' ); </code></pre> <p><strong>Updated</strong></p> <p>My code in it's entirety is now:</p> <pre><code>// Add Query Var function add_query_vars_filter( $vars ){ $vars[] = "my_var"; return $vars; } add_filter( 'query_vars', 'add_query_vars_filter' ); // Add Endpoint function wpd_add_my_endpoint(){ add_rewrite_endpoint( 'my_var', EP_PERMALINK | EP_PAGES ); } add_action( 'init', 'wpd_add_my_endpoint' ); // Add Rewrite function setup_filter_rewrites(){ add_rewrite_rule('^my-page\/([0-9]+)\/?', 'index.php?pagename=my-page&amp;my_var=$matches[1]', 'top'); } add_action( 'init', 'setup_filter_rewrites' ); </code></pre> <p>With the above code, ~/my-page/my_var/1/ works, but ~/my-page/1/ returns a 404. (I have flushed permalinks)</p> <p>Huge thanks in advance!</p>
[ { "answer_id": 237174, "author": "SuperNERD", "author_id": 101671, "author_profile": "https://wordpress.stackexchange.com/users/101671", "pm_score": 1, "selected": false, "text": "<p>Not sure exactly where you're adding that code, but there is a generally accepted way of doing this, which is outlined pretty well here: <a href=\"https://wordpress.stackexchange.com/questions/120215/how-to-add-a-new-product-type-on-woocommerce-product-types/120220\">How to add a new product type on woocommerce product types?</a></p>\n\n<p>There are 2 ways of doing this in the Wordpress/Woocommerce \"recommended\" types of approaches. </p>\n\n<p>1) Copying the files that need these new classes etc into your themes folder into an identical folder structured /woocommerce folder. Technically of course you'll have to re-copy that folder over if you ever update your theme. </p>\n\n<p>2) You can also just do it all in your theme's functions.php file, which is what I did. </p>\n\n<p>/////////////////////////////////</p>\n\n<p>This is exactly what my code starts out like (and you can see where product_type is declared as ta_fundraising_campaign below):</p>\n\n<pre><code>/*******************************************************************************\n * Fundraising custom product_type for WooCommerce.\n ******************************************************************************/\n\n// add a product type\nadd_filter('product_type_selector', 'ta_add_custom_product_type');\nfunction ta_add_custom_product_type($types)\n{\n $types['ta_fundraising_campaign'] = __('Fundraising Campaign');\n return $types;\n}\n\n// create product class on plugins_loaded hook\nadd_action('plugins_loaded', 'ta_create_custom_product_type');\nfunction ta_create_custom_product_type()\n{\n // declare the product class\n class WC_Product_FundRaisingCampaign\n extends WC_Product\n {\n public function __construct($product)\n {\n $product-&gt;product_type = 'ta_fundraising_campaign';\n parent::__construct($product); \n }\n }\n}\n\n/////////////////////////////////\n</code></pre>\n\n<p>Now here's the tricky part - because there is practically NO support out there on the internet for adding custom product_types for variable product_types.</p>\n\n<p>If, you're trying to make your own variable custom product_type, then you'll probably want to add back some of the \"Settings\" ie. Data Panels that allow you to choose different options like Attributes, Inventory and Variations. </p>\n\n<p>****** This is how you add those: *******</p>\n\n<pre><code>add_filter('woocommerce_product_data_tabs', function($tabs) {\n\n array_push($tabs['inventory']['class'], 'show_if_variable show_if_membership show_if_ta_fundraising_campaign');\n array_push($tabs['variations']['class'], 'show_if_membership show_if_ta_fundraising_campaign');\n\n return $tabs;\n\n }, 10, 1); \n</code></pre>\n\n<p>And then, for some reason the \"Used for variations\" checkbox may not show under the Attributes tab. So you may want to copy the file that it's in over to your theme folder and then add a show_if to the class, like this: </p>\n\n<p>This is the file where the checkbox is (copy it into a woocommerce folder in <strong><em>your</em></strong> theme's folder with the exact same structure ie. /yourtheme/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php):</p>\n\n<p>plugins/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php</p>\n\n<p>Then towards the bottom of that file you'll see the checkbox (below). But, notice how the div class has 2 show_if classes....the 2nd one is the one I added to show it on my custom product_type. Hope all this helps some others because it took me forever to figure all this out!!</p>\n\n<pre><code>&lt;div class=\"enable_variation show_if_variable show_if_ta_fundraising_campaign\"&gt;\n &lt;label&gt;&lt;input type=\"checkbox\" class=\"checkbox\" &lt;?php checked( $attribute['is_variation'], 1 ); ?&gt; name=\"attribute_variation[&lt;?php echo $i; ?&gt;]\" value=\"1\" /&gt; &lt;?php _e( 'Used for variations', 'woocommerce' ); ?&gt;&lt;/label&gt;\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 238067, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 0, "selected": false, "text": "<p>You problem is that your taxonomy is <strong>not registered</strong>. Take a look at the output of <a href=\"https://developer.wordpress.org/reference/functions/get_taxonomies/\" rel=\"nofollow\"><code>get_taxonomies()</code></a> at the end of your page to see which taxonomies are available:</p>\n\n<pre><code>add_action( 'shutdown', function() {\n printf( '&lt;pre&gt;%s&lt;/pre&gt;', var_export( get_taxonomies(), TRUE ) );\n}, PHP_MAX_INT -1 );\n</code></pre>\n" } ]
2016/08/16
[ "https://wordpress.stackexchange.com/questions/236081", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47880/" ]
I've been messing around with rewrites and `query_var` to generate some listings, for example: * ~/my-page/?my\_var=1 * ~/my-page/?my\_var=2 * ~/my-page/?my\_var=3 After perusing StackExchange and the interwebs a bit, it seems that the overwhelming consensus is that [add\_rewrite\_endpoint](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint) is the way to go. As such, I've implemented the following: ``` function wpd_add_my_endpoint(){ add_rewrite_endpoint( 'my_var', EP_PAGES ); } add_action( 'init', 'wpd_add_my_endpoint' ); ``` This yields the following URIs based on the ones I mentioned previously: * ~/my-page/my\_var/1 * ~/my-page/my\_var/2 * ~/my-page/my\_var/3 However, I would like to strip out the 'endpoint base' (or slug, not even sure what to call this exactly, in this question/example 'my\_var'), so that the URIs would be: * ~/my-page/1/ * ~/my-page/2/ * ~/my-page/3/ I've tried a bunch of different ways to do rewrites, but none to any avail, this is what I have so far, which isn't working: ``` function setup_filter_rewrites(){ add_rewrite_rule('my-page/([^/]*)/?', 'index.php?pagename=my-page&my_var=$matches[1]', 'top'); } add_action( 'init', 'setup_filter_rewrites' ); ``` **Updated** My code in it's entirety is now: ``` // Add Query Var function add_query_vars_filter( $vars ){ $vars[] = "my_var"; return $vars; } add_filter( 'query_vars', 'add_query_vars_filter' ); // Add Endpoint function wpd_add_my_endpoint(){ add_rewrite_endpoint( 'my_var', EP_PERMALINK | EP_PAGES ); } add_action( 'init', 'wpd_add_my_endpoint' ); // Add Rewrite function setup_filter_rewrites(){ add_rewrite_rule('^my-page\/([0-9]+)\/?', 'index.php?pagename=my-page&my_var=$matches[1]', 'top'); } add_action( 'init', 'setup_filter_rewrites' ); ``` With the above code, ~/my-page/my\_var/1/ works, but ~/my-page/1/ returns a 404. (I have flushed permalinks) Huge thanks in advance!
Not sure exactly where you're adding that code, but there is a generally accepted way of doing this, which is outlined pretty well here: [How to add a new product type on woocommerce product types?](https://wordpress.stackexchange.com/questions/120215/how-to-add-a-new-product-type-on-woocommerce-product-types/120220) There are 2 ways of doing this in the Wordpress/Woocommerce "recommended" types of approaches. 1) Copying the files that need these new classes etc into your themes folder into an identical folder structured /woocommerce folder. Technically of course you'll have to re-copy that folder over if you ever update your theme. 2) You can also just do it all in your theme's functions.php file, which is what I did. ///////////////////////////////// This is exactly what my code starts out like (and you can see where product\_type is declared as ta\_fundraising\_campaign below): ``` /******************************************************************************* * Fundraising custom product_type for WooCommerce. ******************************************************************************/ // add a product type add_filter('product_type_selector', 'ta_add_custom_product_type'); function ta_add_custom_product_type($types) { $types['ta_fundraising_campaign'] = __('Fundraising Campaign'); return $types; } // create product class on plugins_loaded hook add_action('plugins_loaded', 'ta_create_custom_product_type'); function ta_create_custom_product_type() { // declare the product class class WC_Product_FundRaisingCampaign extends WC_Product { public function __construct($product) { $product->product_type = 'ta_fundraising_campaign'; parent::__construct($product); } } } ///////////////////////////////// ``` Now here's the tricky part - because there is practically NO support out there on the internet for adding custom product\_types for variable product\_types. If, you're trying to make your own variable custom product\_type, then you'll probably want to add back some of the "Settings" ie. Data Panels that allow you to choose different options like Attributes, Inventory and Variations. \*\*\*\*\*\* This is how you add those: \*\*\*\*\*\*\* ``` add_filter('woocommerce_product_data_tabs', function($tabs) { array_push($tabs['inventory']['class'], 'show_if_variable show_if_membership show_if_ta_fundraising_campaign'); array_push($tabs['variations']['class'], 'show_if_membership show_if_ta_fundraising_campaign'); return $tabs; }, 10, 1); ``` And then, for some reason the "Used for variations" checkbox may not show under the Attributes tab. So you may want to copy the file that it's in over to your theme folder and then add a show\_if to the class, like this: This is the file where the checkbox is (copy it into a woocommerce folder in ***your*** theme's folder with the exact same structure ie. /yourtheme/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php): plugins/woocommerce/includes/admin/meta-boxes/views/html-product-attribute.php Then towards the bottom of that file you'll see the checkbox (below). But, notice how the div class has 2 show\_if classes....the 2nd one is the one I added to show it on my custom product\_type. Hope all this helps some others because it took me forever to figure all this out!! ``` <div class="enable_variation show_if_variable show_if_ta_fundraising_campaign"> <label><input type="checkbox" class="checkbox" <?php checked( $attribute['is_variation'], 1 ); ?> name="attribute_variation[<?php echo $i; ?>]" value="1" /> <?php _e( 'Used for variations', 'woocommerce' ); ?></label> </div> ```
236,122
<p>I would like to turn off the emails that the admin gets when a new user registers. We are getting a lot of emails because of new registrations (they are legitimate registrations) but I just don't want to see the email telling me that someone has signed up again and again.</p> <p>So far I've tried <a href="http://wordpress.org/plugins/disable-new-user-notifications/" rel="nofollow noreferrer">installing plugins</a> but they don't work. (support even says they don't work any longer). When searching around here the only question I was able to find was <a href="https://wordpress.stackexchange.com/questions/90311/turn-off-admin-emails-for-new-user-registrations">Turn off admin emails for new user registrations</a> which is from three years ago and doesn't seem to work either. I tried with this code:</p> <pre><code>// Redefine user notification function if ( !function_exists('wp_new_user_notification') ) { function wp_new_user_notification( $user_id, $plaintext_pass = '' ) { $user = new WP_User($user_id); $user_login = stripslashes($user-&gt;user_login); $user_email = stripslashes($user-&gt;user_email); $message = sprintf(__('New user registration on your blog %s:'), get_option('blogname')) . "rnrn"; $message .= sprintf(__('Username: %s'), $user_login) . "rnrn"; $message .= sprintf(__('E-mail: %s'), $user_email) . "rn"; // @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), get_option('blogname')), $message); if ( empty($plaintext_pass) ) return; $message = __('Hi there,') . "rnrn"; $message .= sprintf(__("Welcome to %s! Here's how to log in:"), get_option('blogname')) . "rnrn"; $message .= wp_login_url() . "rn"; $message .= sprintf(__('Username: %s'), $user_login) . "rn"; $message .= sprintf(__('Password: %s'), $plaintext_pass) . "rnrn"; $message .= sprintf(__('If you have any problems, please contact me at %s.'), get_option('admin_email')) . "rnrn"; $message .= __('Adios!'); wp_mail($user_email, sprintf(__('[%s] Your username and password'), get_option('blogname')), $message); } } </code></pre> <p>to my theme functions.php (it has the line @wp_mail commented out) and I've even tried to comment out that line in <code>wp-includes/pluggable.php</code> but I still am getting the emails.</p> <p>I'm using WordPress 4.5.3 right now. (UPDATED to 4.6 as part of this process)</p> <p>I'm trying to be a clear as a can. I don't want the email that goes to the user to stop as they still should get that, but how can I make the email to admin stop?</p>
[ { "answer_id": 236132, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 2, "selected": false, "text": "<p><strong>After some research I determined that you can disable all notification emails, but not those that send to admin.</strong> </p>\n\n<p>Per your original question, I can offer some advice on how to handle unwanted notification email from WordPress user registration and password reset email.</p>\n\n<p>Assuming you have a cPanel environment running your installation, simply follow these steps and you will have effectively removed those particular email. </p>\n\n<p>Access <strong>Account Level Filtering</strong> from the cPanel admin. In this area you can manage filters for your main account. You want to <strong>Create Filter</strong> and proceed to create a <strong>New Filter</strong> for <strong>All Mail on Your Account</strong>.</p>\n\n<p>In the <strong>Rule</strong> field select <strong>To</strong> and <strong>equals</strong>. <em>Note: You can also create filters for other conditions</em>. The last field is a text area which you input the email address you're working with. Below the <strong>rules</strong> area is where the magic happens. Select <strong>Discard Message</strong>. There are also other options. </p>\n\n<p>I've always created an email address I know wont be used and created the filter using it. </p>\n\n<p>I could go on about WordPress pluggable hooks and such, but there is nothing that will do exactly as you would like. Bummer...</p>\n" }, { "answer_id": 236276, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 4, "selected": true, "text": "<p><strong>Generic Pluggable Approach for WordPress &lt; 4.6 (See <a href=\"https://wordpress.stackexchange.com/a/236301/25324\">@birgire's Answer</a> for > 4.6)</strong></p>\n\n<p>Pluggable functions are one of the more depressing relics of WordPress's past and come with a slew of intricacies. That directly modifying the core file (which is entirely inadvisable, as @Jarmerson mentioned in the comments) did not work makes me suspect that another plugin in your installation may be overwriting the pluggable.</p>\n\n<p>The <code>wp-includes/pluggable.php</code> file is loaded after active plugins and mu-plugins, but before the active theme; this means that the \"Pluggable Functions\" can only be superseded by declarations in a plugin.</p>\n\n<p>The modification you discovered in the other answer applies to a much older version of WordPress. In the process of replacing any pluggable function, you should start with <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/pluggable.php#L1699\" rel=\"nofollow noreferrer\">the original function as it exists in your installation's version</a> (in your case, v4.5.3). In doing so, the solution becomes the following (comments omitted; no lines added, only removed):</p>\n\n<pre><code>function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {\n if ( $deprecated !== null )\n _deprecated_argument( __FUNCTION__, '4.3.1' );\n\n if ( 'admin' === $notify || ( empty( $deprecated ) &amp;&amp; empty( $notify ) ) ) \n return;\n\n global $wpdb, $wp_hasher;\n $user = get_userdata( $user_id );\n $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);\n $key = wp_generate_password( 20, false );\n\n do_action( 'retrieve_password_key', $user-&gt;user_login, $key );\n\n if ( empty( $wp_hasher ) ) {\n require_once ABSPATH . WPINC . '/class-phpass.php';\n $wp_hasher = new PasswordHash( 8, true );\n }\n\n $hashed = time() . ':' . $wp_hasher-&gt;HashPassword( $key );\n $wpdb-&gt;update( $wpdb-&gt;users, array( 'user_activation_key' =&gt; $hashed ), array( 'user_login' =&gt; $user-&gt;user_login ) );\n\n $message = sprintf(__('Username: %s'), $user-&gt;user_login) . \"\\r\\n\\r\\n\";\n $message .= __('To set your password, visit the following address:') . \"\\r\\n\\r\\n\";\n $message .= '&lt;' . network_site_url(\"wp-login.php?action=rp&amp;key=$key&amp;login=\" . rawurlencode($user-&gt;user_login), 'login') . \"&gt;\\r\\n\\r\\n\";\n $message .= wp_login_url() . \"\\r\\n\";\n\n wp_mail($user-&gt;user_email, sprintf(__('[%s] Your username and password info'), $blogname), $message);\n}\n</code></pre>\n\n<p>I've omitted the traditional <code>if( !function_exists() )</code> check that typically encapsulates a pluggable override because in this instance a potential duplicate declaration error is desirable - it would indicate that another plugin has overwritten the <code>wp_new_user_notification()</code> function before you, and thus that your attempt to do so is being completely ignored.</p>\n\n<p>I'd recommend placing this function in a <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">mu-plugin</a> as it lessens the chance that another plugin should beat you to the punch. In any scenario, do not modify the core file <code>wp-includes/pluggable.php</code> with the above.</p>\n" }, { "answer_id": 236301, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p><strong>Approach for WordPress 4.6+</strong></p>\n\n<p>Check out the patch in ticket <a href=\"https://core.trac.wordpress.org/ticket/36009\" rel=\"noreferrer\">#36009</a> that was merged into WordPress version 4.6.</p>\n\n<p>It <a href=\"https://core.trac.wordpress.org/attachment/ticket/36009/36009.2.diff\" rel=\"noreferrer\">adds</a> the <code>'user'</code> option for the <code>$notify</code> input parameter of <a href=\"https://github.com/WordPress/WordPress/blob/1dd3ed4bd5bb6c48918c26f934fef89ef8a0550c/wp-includes/pluggable.php#L1699\" rel=\"noreferrer\"><code>wp_new_user_notification()</code></a>, to skip sending those emails to the admin.</p>\n\n<p><strong>How it works</strong></p>\n\n<p>The <code>register_new_user()</code> function contains this part:</p>\n\n<pre><code>do_action( 'register_new_user', $user_id );\n</code></pre>\n\n<p>The email notifications are activated with:</p>\n\n<pre><code>add_action( 'register_new_user', 'wp_send_new_user_notifications' );\n</code></pre>\n\n<p>where the callback is defined as:</p>\n\n<pre><code>function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {\n wp_new_user_notification( $user_id, null, $notify );\n}\n</code></pre>\n\n<p><strong>Workaround</strong></p>\n\n<p>We could therefore try this approach <strike>(untested)</strike> with a custom callback and remove the default one:</p>\n\n<pre><code>add_action( 'init', function()\n{\n remove_action( 'register_new_user', 'wp_send_new_user_notifications' );\n add_action( 'register_new_user', 'wpse236122_send_new_user_notifications' );\n} );\n\nfunction wpse236122_send_new_user_notifications( $user_id, $notify = 'user' )\n{ \n wp_send_new_user_notifications( $user_id, $notify ); \n}\n</code></pre>\n\n<p>where we change the default from <code>'both'</code> to <code>'user'</code>.</p>\n\n<p>It's worth mentioning that <code>wp_send_new_user_notifications()</code> is also hooked into these actions:</p>\n\n<ul>\n<li><code>network_site_new_created_user</code></li>\n<li><code>network_site_users_created_user</code></li>\n<li><code>network_user_new_created_user</code></li>\n<li><code>edit_user_created_user</code></li>\n</ul>\n\n<p>We could deal with them in a similar way as described above.</p>\n" }, { "answer_id": 410459, "author": "roadlink", "author_id": 205323, "author_profile": "https://wordpress.stackexchange.com/users/205323", "pm_score": 0, "selected": false, "text": "<p>This worked for me.\n<a href=\"https://gist.github.com/someguy9/b24866f521ec3eb20b13feb4c72a6afd#file-disable-wordpress-admin-new-user-notification-php\" rel=\"nofollow noreferrer\">https://gist.github.com/someguy9/b24866f521ec3eb20b13feb4c72a6afd#file-disable-wordpress-admin-new-user-notification-php</a></p>\n<pre><code> &lt;?php\n//Disable the new user notification sent to the site admin\nfunction smartwp_disable_new_user_notifications() {\n //Remove original use created emails\n remove_action( 'register_new_user', 'wp_send_new_user_notifications' );\n remove_action( 'edit_user_created_user', 'wp_send_new_user_notifications', 10, 2 );\n \n //Add new function to take over email creation\n add_action( 'register_new_user', 'smartwp_send_new_user_notifications' );\n add_action( 'edit_user_created_user', 'smartwp_send_new_user_notifications', 10, 2 );\n}\nfunction smartwp_send_new_user_notifications( $user_id, $notify = 'user' ) {\n if ( empty($notify) || $notify == 'admin' ) {\n return;\n }elseif( $notify == 'both' ){\n //Only send the new user their email, not the admin\n $notify = 'user';\n }\n wp_send_new_user_notifications( $user_id, $notify );\n}\nadd_action( 'init', 'smartwp_disable_new_user_notifications' );\n</code></pre>\n" } ]
2016/08/16
[ "https://wordpress.stackexchange.com/questions/236122", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77767/" ]
I would like to turn off the emails that the admin gets when a new user registers. We are getting a lot of emails because of new registrations (they are legitimate registrations) but I just don't want to see the email telling me that someone has signed up again and again. So far I've tried [installing plugins](http://wordpress.org/plugins/disable-new-user-notifications/) but they don't work. (support even says they don't work any longer). When searching around here the only question I was able to find was [Turn off admin emails for new user registrations](https://wordpress.stackexchange.com/questions/90311/turn-off-admin-emails-for-new-user-registrations) which is from three years ago and doesn't seem to work either. I tried with this code: ``` // Redefine user notification function if ( !function_exists('wp_new_user_notification') ) { function wp_new_user_notification( $user_id, $plaintext_pass = '' ) { $user = new WP_User($user_id); $user_login = stripslashes($user->user_login); $user_email = stripslashes($user->user_email); $message = sprintf(__('New user registration on your blog %s:'), get_option('blogname')) . "rnrn"; $message .= sprintf(__('Username: %s'), $user_login) . "rnrn"; $message .= sprintf(__('E-mail: %s'), $user_email) . "rn"; // @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), get_option('blogname')), $message); if ( empty($plaintext_pass) ) return; $message = __('Hi there,') . "rnrn"; $message .= sprintf(__("Welcome to %s! Here's how to log in:"), get_option('blogname')) . "rnrn"; $message .= wp_login_url() . "rn"; $message .= sprintf(__('Username: %s'), $user_login) . "rn"; $message .= sprintf(__('Password: %s'), $plaintext_pass) . "rnrn"; $message .= sprintf(__('If you have any problems, please contact me at %s.'), get_option('admin_email')) . "rnrn"; $message .= __('Adios!'); wp_mail($user_email, sprintf(__('[%s] Your username and password'), get_option('blogname')), $message); } } ``` to my theme functions.php (it has the line @wp\_mail commented out) and I've even tried to comment out that line in `wp-includes/pluggable.php` but I still am getting the emails. I'm using WordPress 4.5.3 right now. (UPDATED to 4.6 as part of this process) I'm trying to be a clear as a can. I don't want the email that goes to the user to stop as they still should get that, but how can I make the email to admin stop?
**Generic Pluggable Approach for WordPress < 4.6 (See [@birgire's Answer](https://wordpress.stackexchange.com/a/236301/25324) for > 4.6)** Pluggable functions are one of the more depressing relics of WordPress's past and come with a slew of intricacies. That directly modifying the core file (which is entirely inadvisable, as @Jarmerson mentioned in the comments) did not work makes me suspect that another plugin in your installation may be overwriting the pluggable. The `wp-includes/pluggable.php` file is loaded after active plugins and mu-plugins, but before the active theme; this means that the "Pluggable Functions" can only be superseded by declarations in a plugin. The modification you discovered in the other answer applies to a much older version of WordPress. In the process of replacing any pluggable function, you should start with [the original function as it exists in your installation's version](https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/pluggable.php#L1699) (in your case, v4.5.3). In doing so, the solution becomes the following (comments omitted; no lines added, only removed): ``` function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) { if ( $deprecated !== null ) _deprecated_argument( __FUNCTION__, '4.3.1' ); if ( 'admin' === $notify || ( empty( $deprecated ) && empty( $notify ) ) ) return; global $wpdb, $wp_hasher; $user = get_userdata( $user_id ); $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); $key = wp_generate_password( 20, false ); do_action( 'retrieve_password_key', $user->user_login, $key ); if ( empty( $wp_hasher ) ) { require_once ABSPATH . WPINC . '/class-phpass.php'; $wp_hasher = new PasswordHash( 8, true ); } $hashed = time() . ':' . $wp_hasher->HashPassword( $key ); $wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user->user_login ) ); $message = sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n"; $message .= __('To set your password, visit the following address:') . "\r\n\r\n"; $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user->user_login), 'login') . ">\r\n\r\n"; $message .= wp_login_url() . "\r\n"; wp_mail($user->user_email, sprintf(__('[%s] Your username and password info'), $blogname), $message); } ``` I've omitted the traditional `if( !function_exists() )` check that typically encapsulates a pluggable override because in this instance a potential duplicate declaration error is desirable - it would indicate that another plugin has overwritten the `wp_new_user_notification()` function before you, and thus that your attempt to do so is being completely ignored. I'd recommend placing this function in a [mu-plugin](https://codex.wordpress.org/Must_Use_Plugins) as it lessens the chance that another plugin should beat you to the punch. In any scenario, do not modify the core file `wp-includes/pluggable.php` with the above.
236,134
<p>I have custom post type for "rooms" registered, along with a custom taxonomy. Here is the code:</p> <pre><code>&lt;?php /*******************************************/ /* Rooms CPT /*******************************************/ add_action('init', 'room_register'); function room_register() { $labels = array( 'name' =&gt; _x('Rooms', 'post type general name'), 'singular_name' =&gt; _x('Room', 'post type singular name'), 'add_new' =&gt; _x('Add Room', 'add button'), 'add_new_item' =&gt; __('Add New Room'), 'edit_item' =&gt; __('Edit Room'), 'new_item' =&gt; __('New Room'), 'view_item' =&gt; __('View Room'), 'search_items' =&gt; __('Search Rooms'), 'not_found' =&gt; __('Nothing found'), 'not_found_in_trash' =&gt; __('Nothing found in Trash'), 'parent_item_colon' =&gt; '' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; true, 'has_archive' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; true, 'menu_icon' =&gt; 'dashicons-screenoptions', 'supports' =&gt; array('title','editor'), 'rewrite' =&gt; array( 'slug' =&gt; 'rooms/%room_category%', 'with_front' =&gt; false ) //'rewrite' =&gt; array('slug' =&gt; 'products') ); register_post_type( 'rooms' , $args ); } /*******************************************/ /* Rooms Taxonomy /*******************************************/ add_action( 'init', 'rooms_taxonomy', 0 ); function rooms_taxonomy(){ $labels = array( 'name' =&gt; _x( 'Room Category', 'taxonomy general name' ), 'singular_name' =&gt; _x( 'Room Category', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Room Categories' ), 'all_items' =&gt; __( 'All Room Categories' ), 'parent_item' =&gt; __( 'Parent Room Category' ), 'parent_item_colon' =&gt; __( 'Parent Room Category:' ), 'edit_item' =&gt; __( 'Edit Room Category' ), 'update_item' =&gt; __( 'Update Room Category' ), 'add_new_item' =&gt; __( 'Add New Room Category' ), 'new_item_name' =&gt; __( 'New Room Category' ), 'menu_name' =&gt; __( 'Room Categories' ), ); $args = array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'rooms', 'with_front' =&gt; false ), '_builtin' =&gt; false ); register_taxonomy( 'room_category', 'rooms', $args ); } </code></pre> <p>However when I try to visit the url on my website:</p> <p><a href="http://www.upperhouse.org/rooms" rel="nofollow">http://www.upperhouse.org/rooms</a></p> <p>I am getting a 404 error. Shouldn't this be the landing page for the taxonomy? Very confused here. Thanks for any help!</p>
[ { "answer_id": 236132, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 2, "selected": false, "text": "<p><strong>After some research I determined that you can disable all notification emails, but not those that send to admin.</strong> </p>\n\n<p>Per your original question, I can offer some advice on how to handle unwanted notification email from WordPress user registration and password reset email.</p>\n\n<p>Assuming you have a cPanel environment running your installation, simply follow these steps and you will have effectively removed those particular email. </p>\n\n<p>Access <strong>Account Level Filtering</strong> from the cPanel admin. In this area you can manage filters for your main account. You want to <strong>Create Filter</strong> and proceed to create a <strong>New Filter</strong> for <strong>All Mail on Your Account</strong>.</p>\n\n<p>In the <strong>Rule</strong> field select <strong>To</strong> and <strong>equals</strong>. <em>Note: You can also create filters for other conditions</em>. The last field is a text area which you input the email address you're working with. Below the <strong>rules</strong> area is where the magic happens. Select <strong>Discard Message</strong>. There are also other options. </p>\n\n<p>I've always created an email address I know wont be used and created the filter using it. </p>\n\n<p>I could go on about WordPress pluggable hooks and such, but there is nothing that will do exactly as you would like. Bummer...</p>\n" }, { "answer_id": 236276, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 4, "selected": true, "text": "<p><strong>Generic Pluggable Approach for WordPress &lt; 4.6 (See <a href=\"https://wordpress.stackexchange.com/a/236301/25324\">@birgire's Answer</a> for > 4.6)</strong></p>\n\n<p>Pluggable functions are one of the more depressing relics of WordPress's past and come with a slew of intricacies. That directly modifying the core file (which is entirely inadvisable, as @Jarmerson mentioned in the comments) did not work makes me suspect that another plugin in your installation may be overwriting the pluggable.</p>\n\n<p>The <code>wp-includes/pluggable.php</code> file is loaded after active plugins and mu-plugins, but before the active theme; this means that the \"Pluggable Functions\" can only be superseded by declarations in a plugin.</p>\n\n<p>The modification you discovered in the other answer applies to a much older version of WordPress. In the process of replacing any pluggable function, you should start with <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/pluggable.php#L1699\" rel=\"nofollow noreferrer\">the original function as it exists in your installation's version</a> (in your case, v4.5.3). In doing so, the solution becomes the following (comments omitted; no lines added, only removed):</p>\n\n<pre><code>function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {\n if ( $deprecated !== null )\n _deprecated_argument( __FUNCTION__, '4.3.1' );\n\n if ( 'admin' === $notify || ( empty( $deprecated ) &amp;&amp; empty( $notify ) ) ) \n return;\n\n global $wpdb, $wp_hasher;\n $user = get_userdata( $user_id );\n $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);\n $key = wp_generate_password( 20, false );\n\n do_action( 'retrieve_password_key', $user-&gt;user_login, $key );\n\n if ( empty( $wp_hasher ) ) {\n require_once ABSPATH . WPINC . '/class-phpass.php';\n $wp_hasher = new PasswordHash( 8, true );\n }\n\n $hashed = time() . ':' . $wp_hasher-&gt;HashPassword( $key );\n $wpdb-&gt;update( $wpdb-&gt;users, array( 'user_activation_key' =&gt; $hashed ), array( 'user_login' =&gt; $user-&gt;user_login ) );\n\n $message = sprintf(__('Username: %s'), $user-&gt;user_login) . \"\\r\\n\\r\\n\";\n $message .= __('To set your password, visit the following address:') . \"\\r\\n\\r\\n\";\n $message .= '&lt;' . network_site_url(\"wp-login.php?action=rp&amp;key=$key&amp;login=\" . rawurlencode($user-&gt;user_login), 'login') . \"&gt;\\r\\n\\r\\n\";\n $message .= wp_login_url() . \"\\r\\n\";\n\n wp_mail($user-&gt;user_email, sprintf(__('[%s] Your username and password info'), $blogname), $message);\n}\n</code></pre>\n\n<p>I've omitted the traditional <code>if( !function_exists() )</code> check that typically encapsulates a pluggable override because in this instance a potential duplicate declaration error is desirable - it would indicate that another plugin has overwritten the <code>wp_new_user_notification()</code> function before you, and thus that your attempt to do so is being completely ignored.</p>\n\n<p>I'd recommend placing this function in a <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">mu-plugin</a> as it lessens the chance that another plugin should beat you to the punch. In any scenario, do not modify the core file <code>wp-includes/pluggable.php</code> with the above.</p>\n" }, { "answer_id": 236301, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p><strong>Approach for WordPress 4.6+</strong></p>\n\n<p>Check out the patch in ticket <a href=\"https://core.trac.wordpress.org/ticket/36009\" rel=\"noreferrer\">#36009</a> that was merged into WordPress version 4.6.</p>\n\n<p>It <a href=\"https://core.trac.wordpress.org/attachment/ticket/36009/36009.2.diff\" rel=\"noreferrer\">adds</a> the <code>'user'</code> option for the <code>$notify</code> input parameter of <a href=\"https://github.com/WordPress/WordPress/blob/1dd3ed4bd5bb6c48918c26f934fef89ef8a0550c/wp-includes/pluggable.php#L1699\" rel=\"noreferrer\"><code>wp_new_user_notification()</code></a>, to skip sending those emails to the admin.</p>\n\n<p><strong>How it works</strong></p>\n\n<p>The <code>register_new_user()</code> function contains this part:</p>\n\n<pre><code>do_action( 'register_new_user', $user_id );\n</code></pre>\n\n<p>The email notifications are activated with:</p>\n\n<pre><code>add_action( 'register_new_user', 'wp_send_new_user_notifications' );\n</code></pre>\n\n<p>where the callback is defined as:</p>\n\n<pre><code>function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {\n wp_new_user_notification( $user_id, null, $notify );\n}\n</code></pre>\n\n<p><strong>Workaround</strong></p>\n\n<p>We could therefore try this approach <strike>(untested)</strike> with a custom callback and remove the default one:</p>\n\n<pre><code>add_action( 'init', function()\n{\n remove_action( 'register_new_user', 'wp_send_new_user_notifications' );\n add_action( 'register_new_user', 'wpse236122_send_new_user_notifications' );\n} );\n\nfunction wpse236122_send_new_user_notifications( $user_id, $notify = 'user' )\n{ \n wp_send_new_user_notifications( $user_id, $notify ); \n}\n</code></pre>\n\n<p>where we change the default from <code>'both'</code> to <code>'user'</code>.</p>\n\n<p>It's worth mentioning that <code>wp_send_new_user_notifications()</code> is also hooked into these actions:</p>\n\n<ul>\n<li><code>network_site_new_created_user</code></li>\n<li><code>network_site_users_created_user</code></li>\n<li><code>network_user_new_created_user</code></li>\n<li><code>edit_user_created_user</code></li>\n</ul>\n\n<p>We could deal with them in a similar way as described above.</p>\n" }, { "answer_id": 410459, "author": "roadlink", "author_id": 205323, "author_profile": "https://wordpress.stackexchange.com/users/205323", "pm_score": 0, "selected": false, "text": "<p>This worked for me.\n<a href=\"https://gist.github.com/someguy9/b24866f521ec3eb20b13feb4c72a6afd#file-disable-wordpress-admin-new-user-notification-php\" rel=\"nofollow noreferrer\">https://gist.github.com/someguy9/b24866f521ec3eb20b13feb4c72a6afd#file-disable-wordpress-admin-new-user-notification-php</a></p>\n<pre><code> &lt;?php\n//Disable the new user notification sent to the site admin\nfunction smartwp_disable_new_user_notifications() {\n //Remove original use created emails\n remove_action( 'register_new_user', 'wp_send_new_user_notifications' );\n remove_action( 'edit_user_created_user', 'wp_send_new_user_notifications', 10, 2 );\n \n //Add new function to take over email creation\n add_action( 'register_new_user', 'smartwp_send_new_user_notifications' );\n add_action( 'edit_user_created_user', 'smartwp_send_new_user_notifications', 10, 2 );\n}\nfunction smartwp_send_new_user_notifications( $user_id, $notify = 'user' ) {\n if ( empty($notify) || $notify == 'admin' ) {\n return;\n }elseif( $notify == 'both' ){\n //Only send the new user their email, not the admin\n $notify = 'user';\n }\n wp_send_new_user_notifications( $user_id, $notify );\n}\nadd_action( 'init', 'smartwp_disable_new_user_notifications' );\n</code></pre>\n" } ]
2016/08/16
[ "https://wordpress.stackexchange.com/questions/236134", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91661/" ]
I have custom post type for "rooms" registered, along with a custom taxonomy. Here is the code: ``` <?php /*******************************************/ /* Rooms CPT /*******************************************/ add_action('init', 'room_register'); function room_register() { $labels = array( 'name' => _x('Rooms', 'post type general name'), 'singular_name' => _x('Room', 'post type singular name'), 'add_new' => _x('Add Room', 'add button'), 'add_new_item' => __('Add New Room'), 'edit_item' => __('Edit Room'), 'new_item' => __('New Room'), 'view_item' => __('View Room'), 'search_items' => __('Search Rooms'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'rewrite' => true, 'has_archive' => true, 'capability_type' => 'post', 'hierarchical' => true, 'menu_icon' => 'dashicons-screenoptions', 'supports' => array('title','editor'), 'rewrite' => array( 'slug' => 'rooms/%room_category%', 'with_front' => false ) //'rewrite' => array('slug' => 'products') ); register_post_type( 'rooms' , $args ); } /*******************************************/ /* Rooms Taxonomy /*******************************************/ add_action( 'init', 'rooms_taxonomy', 0 ); function rooms_taxonomy(){ $labels = array( 'name' => _x( 'Room Category', 'taxonomy general name' ), 'singular_name' => _x( 'Room Category', 'taxonomy singular name' ), 'search_items' => __( 'Search Room Categories' ), 'all_items' => __( 'All Room Categories' ), 'parent_item' => __( 'Parent Room Category' ), 'parent_item_colon' => __( 'Parent Room Category:' ), 'edit_item' => __( 'Edit Room Category' ), 'update_item' => __( 'Update Room Category' ), 'add_new_item' => __( 'Add New Room Category' ), 'new_item_name' => __( 'New Room Category' ), 'menu_name' => __( 'Room Categories' ), ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_in_menu' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'rooms', 'with_front' => false ), '_builtin' => false ); register_taxonomy( 'room_category', 'rooms', $args ); } ``` However when I try to visit the url on my website: <http://www.upperhouse.org/rooms> I am getting a 404 error. Shouldn't this be the landing page for the taxonomy? Very confused here. Thanks for any help!
**Generic Pluggable Approach for WordPress < 4.6 (See [@birgire's Answer](https://wordpress.stackexchange.com/a/236301/25324) for > 4.6)** Pluggable functions are one of the more depressing relics of WordPress's past and come with a slew of intricacies. That directly modifying the core file (which is entirely inadvisable, as @Jarmerson mentioned in the comments) did not work makes me suspect that another plugin in your installation may be overwriting the pluggable. The `wp-includes/pluggable.php` file is loaded after active plugins and mu-plugins, but before the active theme; this means that the "Pluggable Functions" can only be superseded by declarations in a plugin. The modification you discovered in the other answer applies to a much older version of WordPress. In the process of replacing any pluggable function, you should start with [the original function as it exists in your installation's version](https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/pluggable.php#L1699) (in your case, v4.5.3). In doing so, the solution becomes the following (comments omitted; no lines added, only removed): ``` function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) { if ( $deprecated !== null ) _deprecated_argument( __FUNCTION__, '4.3.1' ); if ( 'admin' === $notify || ( empty( $deprecated ) && empty( $notify ) ) ) return; global $wpdb, $wp_hasher; $user = get_userdata( $user_id ); $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); $key = wp_generate_password( 20, false ); do_action( 'retrieve_password_key', $user->user_login, $key ); if ( empty( $wp_hasher ) ) { require_once ABSPATH . WPINC . '/class-phpass.php'; $wp_hasher = new PasswordHash( 8, true ); } $hashed = time() . ':' . $wp_hasher->HashPassword( $key ); $wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user->user_login ) ); $message = sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n"; $message .= __('To set your password, visit the following address:') . "\r\n\r\n"; $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user->user_login), 'login') . ">\r\n\r\n"; $message .= wp_login_url() . "\r\n"; wp_mail($user->user_email, sprintf(__('[%s] Your username and password info'), $blogname), $message); } ``` I've omitted the traditional `if( !function_exists() )` check that typically encapsulates a pluggable override because in this instance a potential duplicate declaration error is desirable - it would indicate that another plugin has overwritten the `wp_new_user_notification()` function before you, and thus that your attempt to do so is being completely ignored. I'd recommend placing this function in a [mu-plugin](https://codex.wordpress.org/Must_Use_Plugins) as it lessens the chance that another plugin should beat you to the punch. In any scenario, do not modify the core file `wp-includes/pluggable.php` with the above.
236,137
<p>I am setting up a WordPress site locally from a site online. I downloaded the files and database. I used InstantWP to set up the site. I imported the database and moved over the proper files for the local site. When I go to the site, I get these errors:</p> <blockquote> <p>Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'wp_maybe_load_embeds' not found or invalid function name in C:\Users\William\Desktop\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-includes\plugin.php on line 525</p> <p>Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'rest_cookie_collect_status' not found or invalid function name in C:\Users\William\Desktop\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-includes\plugin.php on line 525</p> <p>Fatal error: Class 'WP_User' not found in C:\Users\William\Desktop\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-includes\pluggable.php on line 38</p> </blockquote> <p>Can someone explain to me what these are and how I can fix them?</p>
[ { "answer_id": 236132, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 2, "selected": false, "text": "<p><strong>After some research I determined that you can disable all notification emails, but not those that send to admin.</strong> </p>\n\n<p>Per your original question, I can offer some advice on how to handle unwanted notification email from WordPress user registration and password reset email.</p>\n\n<p>Assuming you have a cPanel environment running your installation, simply follow these steps and you will have effectively removed those particular email. </p>\n\n<p>Access <strong>Account Level Filtering</strong> from the cPanel admin. In this area you can manage filters for your main account. You want to <strong>Create Filter</strong> and proceed to create a <strong>New Filter</strong> for <strong>All Mail on Your Account</strong>.</p>\n\n<p>In the <strong>Rule</strong> field select <strong>To</strong> and <strong>equals</strong>. <em>Note: You can also create filters for other conditions</em>. The last field is a text area which you input the email address you're working with. Below the <strong>rules</strong> area is where the magic happens. Select <strong>Discard Message</strong>. There are also other options. </p>\n\n<p>I've always created an email address I know wont be used and created the filter using it. </p>\n\n<p>I could go on about WordPress pluggable hooks and such, but there is nothing that will do exactly as you would like. Bummer...</p>\n" }, { "answer_id": 236276, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 4, "selected": true, "text": "<p><strong>Generic Pluggable Approach for WordPress &lt; 4.6 (See <a href=\"https://wordpress.stackexchange.com/a/236301/25324\">@birgire's Answer</a> for > 4.6)</strong></p>\n\n<p>Pluggable functions are one of the more depressing relics of WordPress's past and come with a slew of intricacies. That directly modifying the core file (which is entirely inadvisable, as @Jarmerson mentioned in the comments) did not work makes me suspect that another plugin in your installation may be overwriting the pluggable.</p>\n\n<p>The <code>wp-includes/pluggable.php</code> file is loaded after active plugins and mu-plugins, but before the active theme; this means that the \"Pluggable Functions\" can only be superseded by declarations in a plugin.</p>\n\n<p>The modification you discovered in the other answer applies to a much older version of WordPress. In the process of replacing any pluggable function, you should start with <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/pluggable.php#L1699\" rel=\"nofollow noreferrer\">the original function as it exists in your installation's version</a> (in your case, v4.5.3). In doing so, the solution becomes the following (comments omitted; no lines added, only removed):</p>\n\n<pre><code>function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {\n if ( $deprecated !== null )\n _deprecated_argument( __FUNCTION__, '4.3.1' );\n\n if ( 'admin' === $notify || ( empty( $deprecated ) &amp;&amp; empty( $notify ) ) ) \n return;\n\n global $wpdb, $wp_hasher;\n $user = get_userdata( $user_id );\n $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);\n $key = wp_generate_password( 20, false );\n\n do_action( 'retrieve_password_key', $user-&gt;user_login, $key );\n\n if ( empty( $wp_hasher ) ) {\n require_once ABSPATH . WPINC . '/class-phpass.php';\n $wp_hasher = new PasswordHash( 8, true );\n }\n\n $hashed = time() . ':' . $wp_hasher-&gt;HashPassword( $key );\n $wpdb-&gt;update( $wpdb-&gt;users, array( 'user_activation_key' =&gt; $hashed ), array( 'user_login' =&gt; $user-&gt;user_login ) );\n\n $message = sprintf(__('Username: %s'), $user-&gt;user_login) . \"\\r\\n\\r\\n\";\n $message .= __('To set your password, visit the following address:') . \"\\r\\n\\r\\n\";\n $message .= '&lt;' . network_site_url(\"wp-login.php?action=rp&amp;key=$key&amp;login=\" . rawurlencode($user-&gt;user_login), 'login') . \"&gt;\\r\\n\\r\\n\";\n $message .= wp_login_url() . \"\\r\\n\";\n\n wp_mail($user-&gt;user_email, sprintf(__('[%s] Your username and password info'), $blogname), $message);\n}\n</code></pre>\n\n<p>I've omitted the traditional <code>if( !function_exists() )</code> check that typically encapsulates a pluggable override because in this instance a potential duplicate declaration error is desirable - it would indicate that another plugin has overwritten the <code>wp_new_user_notification()</code> function before you, and thus that your attempt to do so is being completely ignored.</p>\n\n<p>I'd recommend placing this function in a <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">mu-plugin</a> as it lessens the chance that another plugin should beat you to the punch. In any scenario, do not modify the core file <code>wp-includes/pluggable.php</code> with the above.</p>\n" }, { "answer_id": 236301, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p><strong>Approach for WordPress 4.6+</strong></p>\n\n<p>Check out the patch in ticket <a href=\"https://core.trac.wordpress.org/ticket/36009\" rel=\"noreferrer\">#36009</a> that was merged into WordPress version 4.6.</p>\n\n<p>It <a href=\"https://core.trac.wordpress.org/attachment/ticket/36009/36009.2.diff\" rel=\"noreferrer\">adds</a> the <code>'user'</code> option for the <code>$notify</code> input parameter of <a href=\"https://github.com/WordPress/WordPress/blob/1dd3ed4bd5bb6c48918c26f934fef89ef8a0550c/wp-includes/pluggable.php#L1699\" rel=\"noreferrer\"><code>wp_new_user_notification()</code></a>, to skip sending those emails to the admin.</p>\n\n<p><strong>How it works</strong></p>\n\n<p>The <code>register_new_user()</code> function contains this part:</p>\n\n<pre><code>do_action( 'register_new_user', $user_id );\n</code></pre>\n\n<p>The email notifications are activated with:</p>\n\n<pre><code>add_action( 'register_new_user', 'wp_send_new_user_notifications' );\n</code></pre>\n\n<p>where the callback is defined as:</p>\n\n<pre><code>function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {\n wp_new_user_notification( $user_id, null, $notify );\n}\n</code></pre>\n\n<p><strong>Workaround</strong></p>\n\n<p>We could therefore try this approach <strike>(untested)</strike> with a custom callback and remove the default one:</p>\n\n<pre><code>add_action( 'init', function()\n{\n remove_action( 'register_new_user', 'wp_send_new_user_notifications' );\n add_action( 'register_new_user', 'wpse236122_send_new_user_notifications' );\n} );\n\nfunction wpse236122_send_new_user_notifications( $user_id, $notify = 'user' )\n{ \n wp_send_new_user_notifications( $user_id, $notify ); \n}\n</code></pre>\n\n<p>where we change the default from <code>'both'</code> to <code>'user'</code>.</p>\n\n<p>It's worth mentioning that <code>wp_send_new_user_notifications()</code> is also hooked into these actions:</p>\n\n<ul>\n<li><code>network_site_new_created_user</code></li>\n<li><code>network_site_users_created_user</code></li>\n<li><code>network_user_new_created_user</code></li>\n<li><code>edit_user_created_user</code></li>\n</ul>\n\n<p>We could deal with them in a similar way as described above.</p>\n" }, { "answer_id": 410459, "author": "roadlink", "author_id": 205323, "author_profile": "https://wordpress.stackexchange.com/users/205323", "pm_score": 0, "selected": false, "text": "<p>This worked for me.\n<a href=\"https://gist.github.com/someguy9/b24866f521ec3eb20b13feb4c72a6afd#file-disable-wordpress-admin-new-user-notification-php\" rel=\"nofollow noreferrer\">https://gist.github.com/someguy9/b24866f521ec3eb20b13feb4c72a6afd#file-disable-wordpress-admin-new-user-notification-php</a></p>\n<pre><code> &lt;?php\n//Disable the new user notification sent to the site admin\nfunction smartwp_disable_new_user_notifications() {\n //Remove original use created emails\n remove_action( 'register_new_user', 'wp_send_new_user_notifications' );\n remove_action( 'edit_user_created_user', 'wp_send_new_user_notifications', 10, 2 );\n \n //Add new function to take over email creation\n add_action( 'register_new_user', 'smartwp_send_new_user_notifications' );\n add_action( 'edit_user_created_user', 'smartwp_send_new_user_notifications', 10, 2 );\n}\nfunction smartwp_send_new_user_notifications( $user_id, $notify = 'user' ) {\n if ( empty($notify) || $notify == 'admin' ) {\n return;\n }elseif( $notify == 'both' ){\n //Only send the new user their email, not the admin\n $notify = 'user';\n }\n wp_send_new_user_notifications( $user_id, $notify );\n}\nadd_action( 'init', 'smartwp_disable_new_user_notifications' );\n</code></pre>\n" } ]
2016/08/16
[ "https://wordpress.stackexchange.com/questions/236137", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101124/" ]
I am setting up a WordPress site locally from a site online. I downloaded the files and database. I used InstantWP to set up the site. I imported the database and moved over the proper files for the local site. When I go to the site, I get these errors: > > Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'wp\_maybe\_load\_embeds' not found or invalid function name in C:\Users\William\Desktop\InstantWP\_4.5\iwpserver\htdocs\wordpress\wp-includes\plugin.php on line 525 > > > Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'rest\_cookie\_collect\_status' not found or invalid function name in C:\Users\William\Desktop\InstantWP\_4.5\iwpserver\htdocs\wordpress\wp-includes\plugin.php on line 525 > > > Fatal error: Class 'WP\_User' not found in C:\Users\William\Desktop\InstantWP\_4.5\iwpserver\htdocs\wordpress\wp-includes\pluggable.php on line 38 > > > Can someone explain to me what these are and how I can fix them?
**Generic Pluggable Approach for WordPress < 4.6 (See [@birgire's Answer](https://wordpress.stackexchange.com/a/236301/25324) for > 4.6)** Pluggable functions are one of the more depressing relics of WordPress's past and come with a slew of intricacies. That directly modifying the core file (which is entirely inadvisable, as @Jarmerson mentioned in the comments) did not work makes me suspect that another plugin in your installation may be overwriting the pluggable. The `wp-includes/pluggable.php` file is loaded after active plugins and mu-plugins, but before the active theme; this means that the "Pluggable Functions" can only be superseded by declarations in a plugin. The modification you discovered in the other answer applies to a much older version of WordPress. In the process of replacing any pluggable function, you should start with [the original function as it exists in your installation's version](https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/pluggable.php#L1699) (in your case, v4.5.3). In doing so, the solution becomes the following (comments omitted; no lines added, only removed): ``` function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) { if ( $deprecated !== null ) _deprecated_argument( __FUNCTION__, '4.3.1' ); if ( 'admin' === $notify || ( empty( $deprecated ) && empty( $notify ) ) ) return; global $wpdb, $wp_hasher; $user = get_userdata( $user_id ); $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); $key = wp_generate_password( 20, false ); do_action( 'retrieve_password_key', $user->user_login, $key ); if ( empty( $wp_hasher ) ) { require_once ABSPATH . WPINC . '/class-phpass.php'; $wp_hasher = new PasswordHash( 8, true ); } $hashed = time() . ':' . $wp_hasher->HashPassword( $key ); $wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user->user_login ) ); $message = sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n"; $message .= __('To set your password, visit the following address:') . "\r\n\r\n"; $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user->user_login), 'login') . ">\r\n\r\n"; $message .= wp_login_url() . "\r\n"; wp_mail($user->user_email, sprintf(__('[%s] Your username and password info'), $blogname), $message); } ``` I've omitted the traditional `if( !function_exists() )` check that typically encapsulates a pluggable override because in this instance a potential duplicate declaration error is desirable - it would indicate that another plugin has overwritten the `wp_new_user_notification()` function before you, and thus that your attempt to do so is being completely ignored. I'd recommend placing this function in a [mu-plugin](https://codex.wordpress.org/Must_Use_Plugins) as it lessens the chance that another plugin should beat you to the punch. In any scenario, do not modify the core file `wp-includes/pluggable.php` with the above.
236,193
<p>The <code>wp_mail</code> function doesn't work after updating WordPress to version <a href="https://make.wordpress.org/core/4-6/" rel="nofollow">4.6</a>.</p> <p>My code is:</p> <pre><code>$headers = 'From: ' . $this-&gt;from_name . ' &lt;' . $this-&gt;from_email .'&gt;' . "\r\n"; wp_mail( $service-&gt;getEmail(), $this-&gt;admin_daily_subject, $admin_daily_message, $headers ); </code></pre> <p>It worked perfectly before the update. Also, I've noticed that sending emails doesn't work in <a href="https://wordpress.org/plugins/contact-form-7/" rel="nofollow">Contact Form 7</a>. Any ideas? Thanks in advance.</p> <p><strong>UPDATE</strong></p> <p>As I did not find the solution, I replaced <code>wp_mail</code> with mail function and added some headers:</p> <pre><code>$headers = 'From: ' . $this-&gt;from_name . ' &lt;'.$this-&gt;from_email.'&gt;' . "\r\n" . 'Reply-To: '.$this-&gt;from_email . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . "Content-Type: text/html; charset=UTF-8"; mail( $service-&gt;getEmail(), $this-&gt;admin_daily_subject, $admin_daily_message, $headers ); </code></pre> <p>With this update it works. I hope there will be some updates of wp codex about using <code>wp_mail()</code> with 4.6 or somebody will find a solutions.</p> <p><strong>UPDATE 2</strong></p> <p>It looks like I am not the only one that is facing this issue:</p> <p><a href="https://wordpress.org/support/topic/there-was-an-error-trying-to-send-your-message-please-try-again-later-15" rel="nofollow">There was an error trying to send your message</a></p>
[ { "answer_id": 236206, "author": "TheGentleman", "author_id": 68563, "author_profile": "https://wordpress.stackexchange.com/users/68563", "pm_score": 2, "selected": false, "text": "<p>On you on WAMP? Regardless, it sounds like the built-in php <a href=\"http://php.net/manual/en/function.mail.php\" rel=\"nofollow\"><code>mail()</code></a> function in your php build is unavailable for whatever reason (it doesn't usually work on WAMP or on *nix builds that don't have an internal smtp server). Your best bet is probably to start using SMTP to send emails. </p>\n\n<p>You could roll your own plugin for that, but I personally like to use <a href=\"https://wordpress.org/plugins/wp-mail-smtp/\" rel=\"nofollow\">WP Mail SMTP</a>. You could use a gmail account for SMTP credentials or something like <a href=\"http://www.mailgun.com/\" rel=\"nofollow\">Mailgun</a> depending on the volume of emails you need to send.</p>\n\n<p>If you did want to write your own plugin, you would want to hook <code>phpmailer_init</code> and modify the global <code>$phpmailer</code> variable with something like this:</p>\n\n<pre><code>$phpmailer-&gt;IsSMTP();\n$phpmailer-&gt;Host = \"smtp.example.com\";\n$phpmailer-&gt;Port = &lt;SMTP PORT&gt;;\n$phpmailer-&gt;SMTPSecure = 'ssl'; //optional, can also be 'tls'\n$phpmailer-&gt;SMTPAuth = true;\n$phpmailer-&gt;Username = '&lt;your smtp username&gt;';\n$phpmailer-&gt;Password = '&lt;your smtp password&gt;';\n</code></pre>\n" }, { "answer_id": 236421, "author": "IvnH", "author_id": 100743, "author_profile": "https://wordpress.stackexchange.com/users/100743", "pm_score": 4, "selected": true, "text": "<p>The solution has been found here - <a href=\"https://core.trac.wordpress.org/attachment/ticket/37736/37736.patch\" rel=\"noreferrer\">Make WordPress Core</a></p>\n\n<p>I've made changes in wp-includes/pluggable.php on line 352 from</p>\n\n<pre><code>$phpmailer-&gt;setFrom( $from_email, $from_name ); \n</code></pre>\n\n<p>to</p>\n\n<pre><code>$phpmailer-&gt;setFrom( $from_email, $from_name, false ); \n</code></pre>\n\n<p>And it works! Thanks to Marius L. J. (Clorith)!</p>\n" }, { "answer_id": 264746, "author": "islandnet.com Web Hosting", "author_id": 118346, "author_profile": "https://wordpress.stackexchange.com/users/118346", "pm_score": 0, "selected": false, "text": "<p>I installed WP-Mail-SMTP\nCreated a [email protected] with a 0b quote.\nConfigured the WP-Mail-SMTP to use the [email protected]\n - SSL On\n - Change localhost to the server you host on\n - SMTP port for SSL is 465\nTested WP-Mail-SMTP worked.</p>\n\n<p>I them still could not get contact form 7 to work, I then thought missing piece of that puzzle was that I had to edit the contact form 7 from address which was [email protected] to be [email protected]</p>\n\n<p>Also, reading the <a href=\"https://contactform7.com/faq/\" rel=\"nofollow noreferrer\">https://contactform7.com/faq/</a> was helpful, turned me onto using the track delivery app in the cpanel hosting, good to check this as it will tell you if your even connecting and trying to send email. Also user had akismet enabled but was not active so turned that off. Also mentions some issues with cache clearing frequency.</p>\n\n<p>Other things to look at are if you have the right PHP version set in cPanel.</p>\n\n<p>A previous post mentioning to edit pluggable.php in wp includes is a bad idea, you should not be editing the core of WordPress to fix such issues as a new core update will just break it again most likely.</p>\n\n<p>UPDATE</p>\n\n<p>I removed captcha from one form that was not working and it worked!!</p>\n\n<p>Recaptcha<br />\n [recaptcha] </p>\n\n<p>Something with recaptcha is broken.</p>\n\n<hr>\n\n<p><strong>FIXED!</strong> </p>\n\n<p>Plugin support forums about recaptcha breaking the form sending said to add:</p>\n\n<p><a href=\"https://wordpress.org/plugins/contact-form-7-recaptcha/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/contact-form-7-recaptcha/</a></p>\n\n<p>Thought I would document my entire effort to fix in case any of my failed efforts bear fruit for someone else struggling.</p>\n" } ]
2016/08/17
[ "https://wordpress.stackexchange.com/questions/236193", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100743/" ]
The `wp_mail` function doesn't work after updating WordPress to version [4.6](https://make.wordpress.org/core/4-6/). My code is: ``` $headers = 'From: ' . $this->from_name . ' <' . $this->from_email .'>' . "\r\n"; wp_mail( $service->getEmail(), $this->admin_daily_subject, $admin_daily_message, $headers ); ``` It worked perfectly before the update. Also, I've noticed that sending emails doesn't work in [Contact Form 7](https://wordpress.org/plugins/contact-form-7/). Any ideas? Thanks in advance. **UPDATE** As I did not find the solution, I replaced `wp_mail` with mail function and added some headers: ``` $headers = 'From: ' . $this->from_name . ' <'.$this->from_email.'>' . "\r\n" . 'Reply-To: '.$this->from_email . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . "Content-Type: text/html; charset=UTF-8"; mail( $service->getEmail(), $this->admin_daily_subject, $admin_daily_message, $headers ); ``` With this update it works. I hope there will be some updates of wp codex about using `wp_mail()` with 4.6 or somebody will find a solutions. **UPDATE 2** It looks like I am not the only one that is facing this issue: [There was an error trying to send your message](https://wordpress.org/support/topic/there-was-an-error-trying-to-send-your-message-please-try-again-later-15)
The solution has been found here - [Make WordPress Core](https://core.trac.wordpress.org/attachment/ticket/37736/37736.patch) I've made changes in wp-includes/pluggable.php on line 352 from ``` $phpmailer->setFrom( $from_email, $from_name ); ``` to ``` $phpmailer->setFrom( $from_email, $from_name, false ); ``` And it works! Thanks to Marius L. J. (Clorith)!
236,213
<pre><code>&lt;?php $args = array( 'post_type' =&gt; 'product', 'stock' =&gt; 1, 'posts_per_page' =&gt; 4, 'product_cat' =&gt; '&lt;?php echo get_theme_mod('vatname', 'Clothing'); ?&gt;', 'orderby' =&gt;'date', 'order' =&gt; 'ASC' ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); global $product; ?&gt; &lt;p&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt; &lt;?php endwhile; wp_reset_query(); ?&gt; </code></pre> <p>I'm trying to echo the product category name. The custom loop works fine but when I echo the function:</p> <pre><code>&lt;?php echo get_theme_mod( 'vatname', 'Clothing' ); ?&gt; </code></pre> <p>The loop stops. Can anyone help me? im trying to use wordpress cutomization api to enter the category name in loop examole 'product_cat' => 'clothing',</p> <p>so i made text function im trying to eco the value in product_cat buy i give sybtax error </p>
[ { "answer_id": 236206, "author": "TheGentleman", "author_id": 68563, "author_profile": "https://wordpress.stackexchange.com/users/68563", "pm_score": 2, "selected": false, "text": "<p>On you on WAMP? Regardless, it sounds like the built-in php <a href=\"http://php.net/manual/en/function.mail.php\" rel=\"nofollow\"><code>mail()</code></a> function in your php build is unavailable for whatever reason (it doesn't usually work on WAMP or on *nix builds that don't have an internal smtp server). Your best bet is probably to start using SMTP to send emails. </p>\n\n<p>You could roll your own plugin for that, but I personally like to use <a href=\"https://wordpress.org/plugins/wp-mail-smtp/\" rel=\"nofollow\">WP Mail SMTP</a>. You could use a gmail account for SMTP credentials or something like <a href=\"http://www.mailgun.com/\" rel=\"nofollow\">Mailgun</a> depending on the volume of emails you need to send.</p>\n\n<p>If you did want to write your own plugin, you would want to hook <code>phpmailer_init</code> and modify the global <code>$phpmailer</code> variable with something like this:</p>\n\n<pre><code>$phpmailer-&gt;IsSMTP();\n$phpmailer-&gt;Host = \"smtp.example.com\";\n$phpmailer-&gt;Port = &lt;SMTP PORT&gt;;\n$phpmailer-&gt;SMTPSecure = 'ssl'; //optional, can also be 'tls'\n$phpmailer-&gt;SMTPAuth = true;\n$phpmailer-&gt;Username = '&lt;your smtp username&gt;';\n$phpmailer-&gt;Password = '&lt;your smtp password&gt;';\n</code></pre>\n" }, { "answer_id": 236421, "author": "IvnH", "author_id": 100743, "author_profile": "https://wordpress.stackexchange.com/users/100743", "pm_score": 4, "selected": true, "text": "<p>The solution has been found here - <a href=\"https://core.trac.wordpress.org/attachment/ticket/37736/37736.patch\" rel=\"noreferrer\">Make WordPress Core</a></p>\n\n<p>I've made changes in wp-includes/pluggable.php on line 352 from</p>\n\n<pre><code>$phpmailer-&gt;setFrom( $from_email, $from_name ); \n</code></pre>\n\n<p>to</p>\n\n<pre><code>$phpmailer-&gt;setFrom( $from_email, $from_name, false ); \n</code></pre>\n\n<p>And it works! Thanks to Marius L. J. (Clorith)!</p>\n" }, { "answer_id": 264746, "author": "islandnet.com Web Hosting", "author_id": 118346, "author_profile": "https://wordpress.stackexchange.com/users/118346", "pm_score": 0, "selected": false, "text": "<p>I installed WP-Mail-SMTP\nCreated a [email protected] with a 0b quote.\nConfigured the WP-Mail-SMTP to use the [email protected]\n - SSL On\n - Change localhost to the server you host on\n - SMTP port for SSL is 465\nTested WP-Mail-SMTP worked.</p>\n\n<p>I them still could not get contact form 7 to work, I then thought missing piece of that puzzle was that I had to edit the contact form 7 from address which was [email protected] to be [email protected]</p>\n\n<p>Also, reading the <a href=\"https://contactform7.com/faq/\" rel=\"nofollow noreferrer\">https://contactform7.com/faq/</a> was helpful, turned me onto using the track delivery app in the cpanel hosting, good to check this as it will tell you if your even connecting and trying to send email. Also user had akismet enabled but was not active so turned that off. Also mentions some issues with cache clearing frequency.</p>\n\n<p>Other things to look at are if you have the right PHP version set in cPanel.</p>\n\n<p>A previous post mentioning to edit pluggable.php in wp includes is a bad idea, you should not be editing the core of WordPress to fix such issues as a new core update will just break it again most likely.</p>\n\n<p>UPDATE</p>\n\n<p>I removed captcha from one form that was not working and it worked!!</p>\n\n<p>Recaptcha<br />\n [recaptcha] </p>\n\n<p>Something with recaptcha is broken.</p>\n\n<hr>\n\n<p><strong>FIXED!</strong> </p>\n\n<p>Plugin support forums about recaptcha breaking the form sending said to add:</p>\n\n<p><a href=\"https://wordpress.org/plugins/contact-form-7-recaptcha/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/contact-form-7-recaptcha/</a></p>\n\n<p>Thought I would document my entire effort to fix in case any of my failed efforts bear fruit for someone else struggling.</p>\n" } ]
2016/08/17
[ "https://wordpress.stackexchange.com/questions/236213", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101171/" ]
``` <?php $args = array( 'post_type' => 'product', 'stock' => 1, 'posts_per_page' => 4, 'product_cat' => '<?php echo get_theme_mod('vatname', 'Clothing'); ?>', 'orderby' =>'date', 'order' => 'ASC' ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?> <p><?php the_title(); ?></p> <?php endwhile; wp_reset_query(); ?> ``` I'm trying to echo the product category name. The custom loop works fine but when I echo the function: ``` <?php echo get_theme_mod( 'vatname', 'Clothing' ); ?> ``` The loop stops. Can anyone help me? im trying to use wordpress cutomization api to enter the category name in loop examole 'product\_cat' => 'clothing', so i made text function im trying to eco the value in product\_cat buy i give sybtax error
The solution has been found here - [Make WordPress Core](https://core.trac.wordpress.org/attachment/ticket/37736/37736.patch) I've made changes in wp-includes/pluggable.php on line 352 from ``` $phpmailer->setFrom( $from_email, $from_name ); ``` to ``` $phpmailer->setFrom( $from_email, $from_name, false ); ``` And it works! Thanks to Marius L. J. (Clorith)!
236,234
<p>How to display image in email header. I tried below, it in gmail it is not displaying the image. Please any one help me to resolve this. Thanks in advance.</p> <pre><code> $to = $_REQUEST['userEmail']; $firstName = $_REQUEST['firstName']; $lastName = $_REQUEST['lastName']; $email = $_REQUEST['email']; $question = $_POST['message']; $subject = 'Test Email'; $message = "&lt;html&gt;&lt;head&gt;&lt;img src='http://192.168.1.157/Shop/wp-content/uploads/2016/07/image_nmae.png'/&gt;&lt;/head&gt;" . "&lt;body&gt;&lt;h1&gt;Visitor Information&lt;/h1&gt;" . "&lt;p&gt;Visitor Information: Fist Name:&amp;nbsp;&amp;nbsp;".$firstName."&amp;nbsp;&amp;nbsp; Last Name:&amp;nbsp;&amp;nbsp; ".$lastName."&lt;/p&gt;" . "&lt;p&gt;Email:&amp;nbsp;&amp;nbsp;".$email."&lt;/p&gt;&lt;p&gt;Question:&amp;nbsp;&amp;nbsp;".$question."&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"; $headers = array('Content-Type: text/html; charset=UTF-8'); $mailSend = wp_mail($to, $subject, $message,$headers); </code></pre>
[ { "answer_id": 236240, "author": "Joseph Seyi Taiwo", "author_id": 101144, "author_profile": "https://wordpress.stackexchange.com/users/101144", "pm_score": 0, "selected": false, "text": "<p>You can add your <code>$headers</code> before the form.\nAlso parse <code>$headers</code> like this</p>\n\n<pre><code>$headers .= \n&quot;Content-Type: text/html; \ncharset=UTF-8\\r\\n&quot;;</code></pre>\n" }, { "answer_id": 337357, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p>The email header is not the same as the <code>&lt;head&gt;</code> of an HTML document (even if that document is an email). So the question shouldn't be how to display an image in the email header because the answer is that you can't.</p>\n\n<p>Second, the same thing holds true for an HTML document. The <code>&lt;head&gt;</code> section (where the <code>&lt;img&gt;</code> tag is currently located in the OP) is for holding information about the document, and what is contained in there will not be displayed.</p>\n\n<p>Since the <code>&lt;img&gt;</code> tag in the <code>&lt;head&gt;</code> location will not be displayed, the problem is simply malformed HTML. To display, the <code>&lt;img&gt;</code> must be inside the <code>&lt;body&gt;</code> tag somewhere.</p>\n\n<pre><code>$to = $_REQUEST['userEmail'];\n$firstName = $_REQUEST['firstName'];\n$lastName = $_REQUEST['lastName'];\n$email = $_REQUEST['email'];\n$question = $_POST['message'];\n$subject = 'Test Email';\n$message = \"&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;img src='http://192.168.1.157/Shop/wp-content/uploads/2016/07/image_nmae.png'/&gt;\"\n . \"&lt;h1&gt;Visitor Information&lt;/h1&gt;\"\n . \"&lt;p&gt;Visitor Information: Fist Name:&amp;nbsp;&amp;nbsp;\".$firstName.\"&amp;nbsp;&amp;nbsp; Last Name:&amp;nbsp;&amp;nbsp; \".$lastName.\"&lt;/p&gt;\"\n . \"&lt;p&gt;Email:&amp;nbsp;&amp;nbsp;\".$email.\"&lt;/p&gt;&lt;p&gt;Question:&amp;nbsp;&amp;nbsp;\".$question.\"&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;\";\n$headers = array('Content-Type: text/html; charset=UTF-8');\n$mailSend = wp_mail($to, $subject, $message,$headers);\n</code></pre>\n" } ]
2016/08/17
[ "https://wordpress.stackexchange.com/questions/236234", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98499/" ]
How to display image in email header. I tried below, it in gmail it is not displaying the image. Please any one help me to resolve this. Thanks in advance. ``` $to = $_REQUEST['userEmail']; $firstName = $_REQUEST['firstName']; $lastName = $_REQUEST['lastName']; $email = $_REQUEST['email']; $question = $_POST['message']; $subject = 'Test Email'; $message = "<html><head><img src='http://192.168.1.157/Shop/wp-content/uploads/2016/07/image_nmae.png'/></head>" . "<body><h1>Visitor Information</h1>" . "<p>Visitor Information: Fist Name:&nbsp;&nbsp;".$firstName."&nbsp;&nbsp; Last Name:&nbsp;&nbsp; ".$lastName."</p>" . "<p>Email:&nbsp;&nbsp;".$email."</p><p>Question:&nbsp;&nbsp;".$question."</p></body></html>"; $headers = array('Content-Type: text/html; charset=UTF-8'); $mailSend = wp_mail($to, $subject, $message,$headers); ```
The email header is not the same as the `<head>` of an HTML document (even if that document is an email). So the question shouldn't be how to display an image in the email header because the answer is that you can't. Second, the same thing holds true for an HTML document. The `<head>` section (where the `<img>` tag is currently located in the OP) is for holding information about the document, and what is contained in there will not be displayed. Since the `<img>` tag in the `<head>` location will not be displayed, the problem is simply malformed HTML. To display, the `<img>` must be inside the `<body>` tag somewhere. ``` $to = $_REQUEST['userEmail']; $firstName = $_REQUEST['firstName']; $lastName = $_REQUEST['lastName']; $email = $_REQUEST['email']; $question = $_POST['message']; $subject = 'Test Email'; $message = "<html><head></head><body><img src='http://192.168.1.157/Shop/wp-content/uploads/2016/07/image_nmae.png'/>" . "<h1>Visitor Information</h1>" . "<p>Visitor Information: Fist Name:&nbsp;&nbsp;".$firstName."&nbsp;&nbsp; Last Name:&nbsp;&nbsp; ".$lastName."</p>" . "<p>Email:&nbsp;&nbsp;".$email."</p><p>Question:&nbsp;&nbsp;".$question."</p></body></html>"; $headers = array('Content-Type: text/html; charset=UTF-8'); $mailSend = wp_mail($to, $subject, $message,$headers); ```
236,235
<p>How do we get wp_link_pages() to show the Next and Previous button when it is the start of the multi-page post as well at the end of a multipage. Currently it only shows Next if it is the first page, and Previous at the end of the page. </p>
[ { "answer_id": 236246, "author": "Joseph Seyi Taiwo", "author_id": 101144, "author_profile": "https://wordpress.stackexchange.com/users/101144", "pm_score": -1, "selected": false, "text": "<p>You can take a look at this\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_link_pages\" rel=\"nofollow\">wp_link_pages Function</a></p>\n" }, { "answer_id": 288282, "author": "Levi Dulstein", "author_id": 101988, "author_profile": "https://wordpress.stackexchange.com/users/101988", "pm_score": 0, "selected": false, "text": "<p>I've just faced the same issue and here is my solution. I'm using globals to get current page and total page count:</p>\n\n<pre><code>/* first i'm looking into $multipage global to check \nif the post actually has pages */\nglobal $multipage;\n\nif ( $multipage === 1 ) {\n global $page; // this is current page number\n global $numpages; // this is total page count\n\n // display disabled left arrow on page 1\n if ( 1 === $page ) :\n ?&gt;\n &lt;span class=\"pagination__arrow pagination__arrow--prev pagination__arrow--disabled\"&gt;&lt; Previous&lt;/span&gt;\n &lt;span class=\"pagination__separator\"&gt; | &lt;/span&gt;\n &lt;?php \n endif;\n\n // standard wp pagination\n wp_link_pages( [\n 'next_or_number' =&gt; 'next',\n 'before' =&gt; '',\n 'previouspagelink' =&gt; '&lt;span class=\"pagination__arrow pagination__arrow--prev\"&gt;&lt; Previous&lt;/span&gt;',\n 'nextpagelink' =&gt; '&lt;span class=\"pagination__arrow pagination__arrow--next\"&gt;Next &gt;&lt;/span&gt;',\n 'separator' =&gt; '&lt;span class=\"pagination__separator\"&gt;|&lt;/span&gt;',\n ] );\n\n // display disabled right arrow on last page\n if ( $page === $numpages ) :\n ?&gt;\n &lt;span class=\"pagination__separator\"&gt; | &lt;/span&gt;\n &lt;span class=\"pagination__arrow pagination__arrow--next pagination__arrow--disabled\"&gt;Next &gt;&lt;/span&gt;\n &lt;?php\n endif;\n\n}\n</code></pre>\n" } ]
2016/08/17
[ "https://wordpress.stackexchange.com/questions/236235", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101181/" ]
How do we get wp\_link\_pages() to show the Next and Previous button when it is the start of the multi-page post as well at the end of a multipage. Currently it only shows Next if it is the first page, and Previous at the end of the page.
I've just faced the same issue and here is my solution. I'm using globals to get current page and total page count: ``` /* first i'm looking into $multipage global to check if the post actually has pages */ global $multipage; if ( $multipage === 1 ) { global $page; // this is current page number global $numpages; // this is total page count // display disabled left arrow on page 1 if ( 1 === $page ) : ?> <span class="pagination__arrow pagination__arrow--prev pagination__arrow--disabled">< Previous</span> <span class="pagination__separator"> | </span> <?php endif; // standard wp pagination wp_link_pages( [ 'next_or_number' => 'next', 'before' => '', 'previouspagelink' => '<span class="pagination__arrow pagination__arrow--prev">< Previous</span>', 'nextpagelink' => '<span class="pagination__arrow pagination__arrow--next">Next ></span>', 'separator' => '<span class="pagination__separator">|</span>', ] ); // display disabled right arrow on last page if ( $page === $numpages ) : ?> <span class="pagination__separator"> | </span> <span class="pagination__arrow pagination__arrow--next pagination__arrow--disabled">Next ></span> <?php endif; } ```
236,249
<p>I'm trying to use a custom endpoint (basically to get a random sorting working) and am using the following code:</p> <pre><code>// Custom WP API endpoint function theme_enable_random_api() { // create json-api endpoint add_action('rest_api_init', function () { // http://example.com/wp-json/random/v2/posts register_rest_route('random/v2', '/random', array ( 'methods' =&gt; 'GET', 'callback' =&gt; 'wp_json_offers_v2__posts', 'permission_callback' =&gt; function (WP_REST_Request $request) { return true; } )); }); // handle the request function wp_json_offers_v2__posts($request) { // json-api params $parameters = $request-&gt;get_query_params(); // default search args $args = array( 'post_type' =&gt; $parameters['type'], 'numberposts' =&gt; 9, 'offset' =&gt; $parameters['offset'], 'post_not_in' =&gt; $parameters['exclude'], 'orderby' =&gt; 'rand', ); // run query $posts = get_posts($args); // return results return new WP_REST_Response($posts, 200); } } add_action('init', 'theme_enable_random_api'); </code></pre> <p>However the response I'm getting is not the same as the response I would get from a standard call to the api.</p> <p>Standard:</p> <p><a href="https://i.stack.imgur.com/9VoHq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9VoHq.png" alt=""></a></p> <p>Custom Endpoint:</p> <p><a href="https://i.stack.imgur.com/23fMn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/23fMn.png" alt=""></a></p> <p>The problem really is that I can't access the taxonomy/acf information like I can in the standard one. I'm not great with PHP so more than likely I'm not getting it properly.</p> <p>Cheers.</p>
[ { "answer_id": 236289, "author": "Chris Morris", "author_id": 39242, "author_profile": "https://wordpress.stackexchange.com/users/39242", "pm_score": 4, "selected": true, "text": "<p>You can call the REST API methods to prepare your output in the same way that the plugin does by default, this will also allow any plugins to tie into the output as you have used the ACF plugin as seen in your example output.</p>\n\n<p>The <code>WP_REST_Posts_Controller</code> class has the following in its get posts method </p>\n\n<pre><code>$posts_query = new WP_Query();\n$query_result = $posts_query-&gt;query( $query_args );\n\n$posts = array();\nforeach ( $query_result as $post ) {\n if ( ! $this-&gt;check_read_permission( $post ) ) {\n continue;\n }\n\n $data = $this-&gt;prepare_item_for_response( $post, $request );\n $posts[] = $this-&gt;prepare_response_for_collection( $data );\n}\n</code></pre>\n\n<p>So you could instantiate a new <code>WP_REST_Posts_Controller</code> instance and call the <code>prepare_item_for_response</code> and <code>prepare_response_for_collection</code> methods on your data to format it identically to the default endpoints.</p>\n\n<p>Something similar to the following should work (untested)</p>\n\n<pre><code>function wp_json_offers_v2__posts($request) {\n // json-api params\n\n $parameters = $request-&gt;get_query_params();\n\n // default search args\n\n $args = array(\n 'post_type' =&gt; $parameters['type'],\n 'numberposts' =&gt; 9,\n 'offset' =&gt; $parameters['offset'],\n 'post_not_in' =&gt; $parameters['exclude'],\n 'orderby' =&gt; 'rand',\n );\n\n // run query\n\n $posts = get_posts($args);\n\n $controller = new WP_REST_Posts_Controller($parameters['type']);\n\n foreach ( $posts as $post ) {\n $data = $controller-&gt;prepare_item_for_response( $post, $request );\n $posts[] = $controller-&gt;prepare_response_for_collection( $data );\n }\n\n // return results\n return new WP_REST_Response($posts, 200);\n}\n</code></pre>\n" }, { "answer_id": 299205, "author": "Myles Hyson", "author_id": 140667, "author_profile": "https://wordpress.stackexchange.com/users/140667", "pm_score": 1, "selected": false, "text": "<p>The above answer forgot to set a new array variable. Once you add that it works great.</p>\n\n<pre><code>function get_all_posts($request)\n{\n $posts = get_posts([\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n ]);\n\n $controller = new WP_REST_Posts_Controller('post');\n\n $array = [];\n\n foreach ( $posts as $post ) {\n $data = $controller-&gt;prepare_item_for_response($post,$request);\n $array[] = $controller-&gt;prepare_response_for_collection($data);\n }\n\n return $array;\n}\n</code></pre>\n\n<p>Output looks just like the normal api response.</p>\n" }, { "answer_id": 358663, "author": "Kostiantyn Petlia", "author_id": 104932, "author_profile": "https://wordpress.stackexchange.com/users/104932", "pm_score": 2, "selected": false, "text": "<p>The accepted answer was helpful. Thanks. But prepare_item_for_response() method was deprecated since v.3.0, so, hope this snippet will help someone with a custom endpoint for WC Orders.</p>\n\n<pre><code> // Parse all others params\n $args = wp_parse_args( $request-&gt;get_params(), $args );\n\n // Get orders\n $orders = wc_get_orders( $args );\n\n if ( ! empty( $orders ) &amp;&amp; is_array( $orders ) ) {\n $controller = new WC_REST_Orders_Controller ();\n\n // The response data\n $orders_data = [];\n // We need prepare objects to the response\n foreach ( $orders as $order ) {\n if ( $order instanceof WC_Order ) {\n // Objects\n $prepared_object = $controller-&gt;prepare_object_for_response( $order, $request );\n $orders_data[] = $controller-&gt;prepare_response_for_collection( $prepared_object );\n } else {\n // IDs\n $orders_data[] = (int) $order;\n }\n }\n\n // Return the response\n return new WP_REST_Response( $orders_data, 200 );\n\n }\n</code></pre>\n" } ]
2016/08/17
[ "https://wordpress.stackexchange.com/questions/236249", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51164/" ]
I'm trying to use a custom endpoint (basically to get a random sorting working) and am using the following code: ``` // Custom WP API endpoint function theme_enable_random_api() { // create json-api endpoint add_action('rest_api_init', function () { // http://example.com/wp-json/random/v2/posts register_rest_route('random/v2', '/random', array ( 'methods' => 'GET', 'callback' => 'wp_json_offers_v2__posts', 'permission_callback' => function (WP_REST_Request $request) { return true; } )); }); // handle the request function wp_json_offers_v2__posts($request) { // json-api params $parameters = $request->get_query_params(); // default search args $args = array( 'post_type' => $parameters['type'], 'numberposts' => 9, 'offset' => $parameters['offset'], 'post_not_in' => $parameters['exclude'], 'orderby' => 'rand', ); // run query $posts = get_posts($args); // return results return new WP_REST_Response($posts, 200); } } add_action('init', 'theme_enable_random_api'); ``` However the response I'm getting is not the same as the response I would get from a standard call to the api. Standard: [![](https://i.stack.imgur.com/9VoHq.png)](https://i.stack.imgur.com/9VoHq.png) Custom Endpoint: [![](https://i.stack.imgur.com/23fMn.png)](https://i.stack.imgur.com/23fMn.png) The problem really is that I can't access the taxonomy/acf information like I can in the standard one. I'm not great with PHP so more than likely I'm not getting it properly. Cheers.
You can call the REST API methods to prepare your output in the same way that the plugin does by default, this will also allow any plugins to tie into the output as you have used the ACF plugin as seen in your example output. The `WP_REST_Posts_Controller` class has the following in its get posts method ``` $posts_query = new WP_Query(); $query_result = $posts_query->query( $query_args ); $posts = array(); foreach ( $query_result as $post ) { if ( ! $this->check_read_permission( $post ) ) { continue; } $data = $this->prepare_item_for_response( $post, $request ); $posts[] = $this->prepare_response_for_collection( $data ); } ``` So you could instantiate a new `WP_REST_Posts_Controller` instance and call the `prepare_item_for_response` and `prepare_response_for_collection` methods on your data to format it identically to the default endpoints. Something similar to the following should work (untested) ``` function wp_json_offers_v2__posts($request) { // json-api params $parameters = $request->get_query_params(); // default search args $args = array( 'post_type' => $parameters['type'], 'numberposts' => 9, 'offset' => $parameters['offset'], 'post_not_in' => $parameters['exclude'], 'orderby' => 'rand', ); // run query $posts = get_posts($args); $controller = new WP_REST_Posts_Controller($parameters['type']); foreach ( $posts as $post ) { $data = $controller->prepare_item_for_response( $post, $request ); $posts[] = $controller->prepare_response_for_collection( $data ); } // return results return new WP_REST_Response($posts, 200); } ```
236,256
<p>I have purchased few plugins and they work fine, but one existing plugin doesn't work. The plugin developer telling: refund or provide admin access.</p> <p>How to handle such requests? <strong>Create a special user with some admin rights just be able to work on plugin directory?</strong> </p>
[ { "answer_id": 236289, "author": "Chris Morris", "author_id": 39242, "author_profile": "https://wordpress.stackexchange.com/users/39242", "pm_score": 4, "selected": true, "text": "<p>You can call the REST API methods to prepare your output in the same way that the plugin does by default, this will also allow any plugins to tie into the output as you have used the ACF plugin as seen in your example output.</p>\n\n<p>The <code>WP_REST_Posts_Controller</code> class has the following in its get posts method </p>\n\n<pre><code>$posts_query = new WP_Query();\n$query_result = $posts_query-&gt;query( $query_args );\n\n$posts = array();\nforeach ( $query_result as $post ) {\n if ( ! $this-&gt;check_read_permission( $post ) ) {\n continue;\n }\n\n $data = $this-&gt;prepare_item_for_response( $post, $request );\n $posts[] = $this-&gt;prepare_response_for_collection( $data );\n}\n</code></pre>\n\n<p>So you could instantiate a new <code>WP_REST_Posts_Controller</code> instance and call the <code>prepare_item_for_response</code> and <code>prepare_response_for_collection</code> methods on your data to format it identically to the default endpoints.</p>\n\n<p>Something similar to the following should work (untested)</p>\n\n<pre><code>function wp_json_offers_v2__posts($request) {\n // json-api params\n\n $parameters = $request-&gt;get_query_params();\n\n // default search args\n\n $args = array(\n 'post_type' =&gt; $parameters['type'],\n 'numberposts' =&gt; 9,\n 'offset' =&gt; $parameters['offset'],\n 'post_not_in' =&gt; $parameters['exclude'],\n 'orderby' =&gt; 'rand',\n );\n\n // run query\n\n $posts = get_posts($args);\n\n $controller = new WP_REST_Posts_Controller($parameters['type']);\n\n foreach ( $posts as $post ) {\n $data = $controller-&gt;prepare_item_for_response( $post, $request );\n $posts[] = $controller-&gt;prepare_response_for_collection( $data );\n }\n\n // return results\n return new WP_REST_Response($posts, 200);\n}\n</code></pre>\n" }, { "answer_id": 299205, "author": "Myles Hyson", "author_id": 140667, "author_profile": "https://wordpress.stackexchange.com/users/140667", "pm_score": 1, "selected": false, "text": "<p>The above answer forgot to set a new array variable. Once you add that it works great.</p>\n\n<pre><code>function get_all_posts($request)\n{\n $posts = get_posts([\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n ]);\n\n $controller = new WP_REST_Posts_Controller('post');\n\n $array = [];\n\n foreach ( $posts as $post ) {\n $data = $controller-&gt;prepare_item_for_response($post,$request);\n $array[] = $controller-&gt;prepare_response_for_collection($data);\n }\n\n return $array;\n}\n</code></pre>\n\n<p>Output looks just like the normal api response.</p>\n" }, { "answer_id": 358663, "author": "Kostiantyn Petlia", "author_id": 104932, "author_profile": "https://wordpress.stackexchange.com/users/104932", "pm_score": 2, "selected": false, "text": "<p>The accepted answer was helpful. Thanks. But prepare_item_for_response() method was deprecated since v.3.0, so, hope this snippet will help someone with a custom endpoint for WC Orders.</p>\n\n<pre><code> // Parse all others params\n $args = wp_parse_args( $request-&gt;get_params(), $args );\n\n // Get orders\n $orders = wc_get_orders( $args );\n\n if ( ! empty( $orders ) &amp;&amp; is_array( $orders ) ) {\n $controller = new WC_REST_Orders_Controller ();\n\n // The response data\n $orders_data = [];\n // We need prepare objects to the response\n foreach ( $orders as $order ) {\n if ( $order instanceof WC_Order ) {\n // Objects\n $prepared_object = $controller-&gt;prepare_object_for_response( $order, $request );\n $orders_data[] = $controller-&gt;prepare_response_for_collection( $prepared_object );\n } else {\n // IDs\n $orders_data[] = (int) $order;\n }\n }\n\n // Return the response\n return new WP_REST_Response( $orders_data, 200 );\n\n }\n</code></pre>\n" } ]
2016/08/17
[ "https://wordpress.stackexchange.com/questions/236256", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101194/" ]
I have purchased few plugins and they work fine, but one existing plugin doesn't work. The plugin developer telling: refund or provide admin access. How to handle such requests? **Create a special user with some admin rights just be able to work on plugin directory?**
You can call the REST API methods to prepare your output in the same way that the plugin does by default, this will also allow any plugins to tie into the output as you have used the ACF plugin as seen in your example output. The `WP_REST_Posts_Controller` class has the following in its get posts method ``` $posts_query = new WP_Query(); $query_result = $posts_query->query( $query_args ); $posts = array(); foreach ( $query_result as $post ) { if ( ! $this->check_read_permission( $post ) ) { continue; } $data = $this->prepare_item_for_response( $post, $request ); $posts[] = $this->prepare_response_for_collection( $data ); } ``` So you could instantiate a new `WP_REST_Posts_Controller` instance and call the `prepare_item_for_response` and `prepare_response_for_collection` methods on your data to format it identically to the default endpoints. Something similar to the following should work (untested) ``` function wp_json_offers_v2__posts($request) { // json-api params $parameters = $request->get_query_params(); // default search args $args = array( 'post_type' => $parameters['type'], 'numberposts' => 9, 'offset' => $parameters['offset'], 'post_not_in' => $parameters['exclude'], 'orderby' => 'rand', ); // run query $posts = get_posts($args); $controller = new WP_REST_Posts_Controller($parameters['type']); foreach ( $posts as $post ) { $data = $controller->prepare_item_for_response( $post, $request ); $posts[] = $controller->prepare_response_for_collection( $data ); } // return results return new WP_REST_Response($posts, 200); } ```
236,260
<p>I've used a small javascript file to create an off canvas push navbar. I loaded the file as described in the Wordpres Codex: </p> <pre><code>function sidebar () { wp_enqueue_script('theme-js', get_stylesheet_directory_uri() . '/js/nav-sidebar.js',array( 'jquery' ),$version,true ); } add_action('wp_enqueue_scripts', 'sidebar'); </code></pre> <p>However, it seems that the only js that is loaded is the nav-sidebar and the bootstrap.js refuses to load. If i remove nav-sidebar.js, bootstrap.js loads just fine. It creates a conflict that i can't solve.</p> <p>You can find the script i've used <a href="http://jsbin.com/pecefezigo/edit?html,css,js,output" rel="nofollow">here</a></p>
[ { "answer_id": 236273, "author": "Rituparna sonowal", "author_id": 71232, "author_profile": "https://wordpress.stackexchange.com/users/71232", "pm_score": 0, "selected": false, "text": "<p>I am assuming you have already enqueued bootstrap js in your theme functions.php with handle named 'bootstrapjs' in the same way you did with nav-sidebar.js, which you didn't mentioned. Now make a little change to your code.</p>\n\n<pre><code>function sidebar(){\nwp_enqueue_script('theme-js', get_stylesheet_directory_uri() . '/js/nav-sidebar.js', array( 'jquery','bootstrapjs' ),$version, true );\n}\nadd_action('wp_enqueue_scripts', 'sidebar');\n</code></pre>\n\n<p>Other possible reason you haven't enqueued the bootstrap js properly. Also check for 404 error.</p>\n" }, { "answer_id": 236281, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 2, "selected": true, "text": "<p>Expanding <a href=\"https://wordpress.stackexchange.com/users/17305/rrikesh\">@RRikesh</a> comment, you might have enqueued/loaded the <code>bootstap.js</code> with same handle <code>theme-js</code>. So only one script gets enqueued.</p>\n\n<p>Try to use different handle for example <code>nav-sidebar</code>. See the following code. Also it's recommended to use prefix, here I used <code>wpse</code>. Also use <code>get_template_directory_uri</code> instead of <code>get_stylesheet_directory_uri()</code> if it's not a child theme.</p>\n\n<pre><code>function wpse_sidebar () {\n wp_enqueue_script('nav-sidebar', get_template_directory_uri() . '/js/nav-sidebar.js',array( 'jquery' ),'1.0.0',true );\n}\nadd_action('wp_enqueue_scripts', 'wpse_sidebar');\n</code></pre>\n" } ]
2016/08/18
[ "https://wordpress.stackexchange.com/questions/236260", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25605/" ]
I've used a small javascript file to create an off canvas push navbar. I loaded the file as described in the Wordpres Codex: ``` function sidebar () { wp_enqueue_script('theme-js', get_stylesheet_directory_uri() . '/js/nav-sidebar.js',array( 'jquery' ),$version,true ); } add_action('wp_enqueue_scripts', 'sidebar'); ``` However, it seems that the only js that is loaded is the nav-sidebar and the bootstrap.js refuses to load. If i remove nav-sidebar.js, bootstrap.js loads just fine. It creates a conflict that i can't solve. You can find the script i've used [here](http://jsbin.com/pecefezigo/edit?html,css,js,output)
Expanding [@RRikesh](https://wordpress.stackexchange.com/users/17305/rrikesh) comment, you might have enqueued/loaded the `bootstap.js` with same handle `theme-js`. So only one script gets enqueued. Try to use different handle for example `nav-sidebar`. See the following code. Also it's recommended to use prefix, here I used `wpse`. Also use `get_template_directory_uri` instead of `get_stylesheet_directory_uri()` if it's not a child theme. ``` function wpse_sidebar () { wp_enqueue_script('nav-sidebar', get_template_directory_uri() . '/js/nav-sidebar.js',array( 'jquery' ),'1.0.0',true ); } add_action('wp_enqueue_scripts', 'wpse_sidebar'); ```
236,279
<p>How can I make my own custom sidebar for my blog when my theme does not provide an option to add a custom sidebar?</p>
[ { "answer_id": 236286, "author": "user53340", "author_id": 98778, "author_profile": "https://wordpress.stackexchange.com/users/98778", "pm_score": 1, "selected": false, "text": "<p>You need to register the widget area in your themes functions.php file. Your code should look something like this.</p>\n\n<pre><code>//register the widget area\nfunction your_function_name() {\n register_sidebar(array(\n 'name' =&gt; esc_html__('Sidebar', 'your_theme_name'),\n 'id' =&gt; 'sidebar-1',\n 'description' =&gt; esc_html__('Add widgets here.', 'your_theme_name'),\n 'before_widget' =&gt; '&lt;section id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/section&gt;',\n 'before_title' =&gt; '&lt;h2 class=\"widget-title\"&gt;',\n 'after_title' =&gt; '&lt;/h2&gt;',\n )); } \n\nadd_action('widgets_init', 'your_function_name'); //This hooks into WordPress wigets_init function.\n</code></pre>\n\n<p>You can learn more about widgetizing themes <a href=\"https://codex.wordpress.org/Widgetizing_Themes\" rel=\"nofollow\">here</a>. Another great place to learn and understand hooks, actions and filters is this <a href=\"http://docs.presscustomizr.com/article/26-wordpress-actions-filters-and-hooks-a-guide-for-non-developers\" rel=\"nofollow\">site</a>, it really helped me out. I hope this all helps. =)</p>\n" }, { "answer_id": 236321, "author": "Joseph Seyi Taiwo", "author_id": 101144, "author_profile": "https://wordpress.stackexchange.com/users/101144", "pm_score": 0, "selected": false, "text": "<p>You should also create a sidebar.php template in your theme, embed the first code shared by @user53340 the add <code>&lt;?php get_sidebar(); ?&gt;</code> anywhere you want the sidebar to show, you should also float the css class you used to wrap it to left or right just as you like.</p>\n" } ]
2016/08/18
[ "https://wordpress.stackexchange.com/questions/236279", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93995/" ]
How can I make my own custom sidebar for my blog when my theme does not provide an option to add a custom sidebar?
You need to register the widget area in your themes functions.php file. Your code should look something like this. ``` //register the widget area function your_function_name() { register_sidebar(array( 'name' => esc_html__('Sidebar', 'your_theme_name'), 'id' => 'sidebar-1', 'description' => esc_html__('Add widgets here.', 'your_theme_name'), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', )); } add_action('widgets_init', 'your_function_name'); //This hooks into WordPress wigets_init function. ``` You can learn more about widgetizing themes [here](https://codex.wordpress.org/Widgetizing_Themes). Another great place to learn and understand hooks, actions and filters is this [site](http://docs.presscustomizr.com/article/26-wordpress-actions-filters-and-hooks-a-guide-for-non-developers), it really helped me out. I hope this all helps. =)
236,298
<p>I have tried <code>preformatted</code> button, <code>Paste as text</code> button or <code>Text</code> tab element before pasting source code, WordPress always stripped indent tabs and broke code formatting.</p> <p>For example, the source code:</p> <pre><code>final class HtmlAttr { /** * Constructor * * @param string $filter A filter hook to modify the attribute(s). */ function __construct(array $attrs, $filter = '') { // Something... } /** * Render attribute(s) */ function __toString() { // Something... } } </code></pre> <p>will become:</p> <pre><code>final class HtmlAttr { /** * Constructor * * @param string $filter A filter hook to modify the attribute(s). */ function __construct(array $attrs, $filter = '') { // Something... } /** * Render attribute(s) */ function __toString() { // Something... } } </code></pre> <p>I'm using Atom IDE and can't figure out the right way to paste source code from IDE into WordPress TinyMCE Editor directly. Really appreciate your help!</p>
[ { "answer_id": 236286, "author": "user53340", "author_id": 98778, "author_profile": "https://wordpress.stackexchange.com/users/98778", "pm_score": 1, "selected": false, "text": "<p>You need to register the widget area in your themes functions.php file. Your code should look something like this.</p>\n\n<pre><code>//register the widget area\nfunction your_function_name() {\n register_sidebar(array(\n 'name' =&gt; esc_html__('Sidebar', 'your_theme_name'),\n 'id' =&gt; 'sidebar-1',\n 'description' =&gt; esc_html__('Add widgets here.', 'your_theme_name'),\n 'before_widget' =&gt; '&lt;section id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/section&gt;',\n 'before_title' =&gt; '&lt;h2 class=\"widget-title\"&gt;',\n 'after_title' =&gt; '&lt;/h2&gt;',\n )); } \n\nadd_action('widgets_init', 'your_function_name'); //This hooks into WordPress wigets_init function.\n</code></pre>\n\n<p>You can learn more about widgetizing themes <a href=\"https://codex.wordpress.org/Widgetizing_Themes\" rel=\"nofollow\">here</a>. Another great place to learn and understand hooks, actions and filters is this <a href=\"http://docs.presscustomizr.com/article/26-wordpress-actions-filters-and-hooks-a-guide-for-non-developers\" rel=\"nofollow\">site</a>, it really helped me out. I hope this all helps. =)</p>\n" }, { "answer_id": 236321, "author": "Joseph Seyi Taiwo", "author_id": 101144, "author_profile": "https://wordpress.stackexchange.com/users/101144", "pm_score": 0, "selected": false, "text": "<p>You should also create a sidebar.php template in your theme, embed the first code shared by @user53340 the add <code>&lt;?php get_sidebar(); ?&gt;</code> anywhere you want the sidebar to show, you should also float the css class you used to wrap it to left or right just as you like.</p>\n" } ]
2016/08/18
[ "https://wordpress.stackexchange.com/questions/236298", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92212/" ]
I have tried `preformatted` button, `Paste as text` button or `Text` tab element before pasting source code, WordPress always stripped indent tabs and broke code formatting. For example, the source code: ``` final class HtmlAttr { /** * Constructor * * @param string $filter A filter hook to modify the attribute(s). */ function __construct(array $attrs, $filter = '') { // Something... } /** * Render attribute(s) */ function __toString() { // Something... } } ``` will become: ``` final class HtmlAttr { /** * Constructor * * @param string $filter A filter hook to modify the attribute(s). */ function __construct(array $attrs, $filter = '') { // Something... } /** * Render attribute(s) */ function __toString() { // Something... } } ``` I'm using Atom IDE and can't figure out the right way to paste source code from IDE into WordPress TinyMCE Editor directly. Really appreciate your help!
You need to register the widget area in your themes functions.php file. Your code should look something like this. ``` //register the widget area function your_function_name() { register_sidebar(array( 'name' => esc_html__('Sidebar', 'your_theme_name'), 'id' => 'sidebar-1', 'description' => esc_html__('Add widgets here.', 'your_theme_name'), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', )); } add_action('widgets_init', 'your_function_name'); //This hooks into WordPress wigets_init function. ``` You can learn more about widgetizing themes [here](https://codex.wordpress.org/Widgetizing_Themes). Another great place to learn and understand hooks, actions and filters is this [site](http://docs.presscustomizr.com/article/26-wordpress-actions-filters-and-hooks-a-guide-for-non-developers), it really helped me out. I hope this all helps. =)
236,318
<p>Using the WordPress <code>the_content</code> tag, I am running a custom function to search for all images that do not have a <code>width</code> and <code>height</code> attribute set and insert the proper dimensions. Below is the function:</p> <pre><code>add_filter( 'the_content', 'add_img_dimensions' ); function add_img_dimensions( $image_no_dimensions ) { // Insert width &amp; height to images missing dimensions if ( preg_match_all( '/&lt;img [^&gt;]+width=[^&gt;]+height=&gt;/i', $image_no_dimensions, $result ) ) { // Do nothing... } else { preg_match_all( '/(alt|title|src)=("[^"]*")/i', $image_no_dimensions, $img ); list( $width, $height, $type, $attr ) = getimagesize( str_replace( "\"", "" , ( $img[2][0] ) ) ); $imgname = str_replace( "\"", "" , ( $img[2][0] ) ); } return sprintf( '&lt;img src="%s" width="%dpx" height="%dpx" /&gt;', str_replace("\"", "" , ( $img[2][0] ) ), $width, $height ); } </code></pre> <p>For example, if there is an image on one of my pages that looks like the following:</p> <pre><code>&lt;img src="https://link.to/sum/img.jpg" alt="Image Title" /&gt; </code></pre> <p>It will then insert the <code>width</code> and <code>height</code> of the actual image:</p> <pre><code>&lt;img width="150" height="50" src="https://link.to/sum/img.jpg" alt="Image Title" /&gt; </code></pre> <p>The function works as expected. However, all of the page's content is replace with the first image that it finds that don't have dimensions set.</p> <p>How can I <code>return</code> all of the content but only change the images that don't have a dimension?</p> <p><strong>Before and after</strong> <a href="https://i.stack.imgur.com/iImP8.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iImP8.gif" alt="enter image description here"></a></p>
[ { "answer_id": 236369, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>You always need to return the full content when using <code>the_content</code> filter. But the code you have will not quite handle multiple images anyway... something like this might do it better, by extracting all the image tags first then looping to maybe add the width/height to each and replacing the original tag:</p>\n\n<pre><code>add_filter( 'the_content', 'add_img_dimensions' );\n\nfunction add_img_dimensions( $content ) { \n\n preg_match_all( '/&lt;img[^&gt;]+&gt;/i', $content, $images);\n if (count($images) &lt; 1) {return $content;}\n\n foreach ($images as $image) {\n preg_match_all( '/(alt|title|src|width|height)=(\"[^\"]*\")/i', $image[0], $img );\n // Insert width &amp; height to image if no width specified\n if (!isset($img[3])) {\n $imgalt = str_replace( \"\\\"\", \"\" , ( $img[0][0] ) ); \n $imgtitle = str_replace( \"\\\"\", \"\" , ( $img[1][0] ) );\n $imgname = str_replace( \"\\\"\", \"\" , ( $img[2][0] ) ); \n list( $width, $height, $type, $attr ) = getimagesize( $imgname );\n $newimagetag = sprintf( '&lt;img src=\"%s\" alt=\"%s\" title=\"%s\" width=\"%dpx\" height=\"%dpx\" /&gt;', $imgname, $imgalt, $imgtitle, $width, $height );\n $content = str_replace($image, $newimagetag, $content);\n }\n }\n\n return $content;\n}\n</code></pre>\n\n<p>Note: Untested I'm not sure I have the index references just right... also you will lose any inline styles or other attributes (eg. border) this way so further would need to be done to preserve those.</p>\n" }, { "answer_id": 236556, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 3, "selected": true, "text": "<p>Tested and confirmed that this works:</p>\n\n<pre><code>add_filter( 'the_content', 'add_image_dimensions' );\n\nfunction add_image_dimensions( $content ) {\n\n preg_match_all( '/&lt;img[^&gt;]+&gt;/i', $content, $images);\n\n if (count($images) &lt; 1)\n return $content;\n\n foreach ($images[0] as $image) {\n preg_match_all( '/(alt|title|src|width|class|id|height)=(\"[^\"]*\")/i', $image, $img );\n\n if ( !in_array( 'src', $img[1] ) )\n continue;\n\n if ( !in_array( 'width', $img[1] ) || !in_array( 'height', $img[1] ) ) {\n $src = $img[2][ array_search('src', $img[1]) ];\n $alt = in_array( 'alt', $img[1] ) ? ' alt=' . $img[2][ array_search('alt', $img[1]) ] : '';\n $title = in_array( 'title', $img[1] ) ? ' title=' . $img[2][ array_search('title', $img[1]) ] : '';\n $class = in_array( 'class', $img[1] ) ? ' class=' . $img[2][ array_search('class', $img[1]) ] : '';\n $id = in_array( 'id', $img[1] ) ? ' id=' . $img[2][ array_search('id', $img[1]) ] : '';\n list( $width, $height, $type, $attr ) = getimagesize( str_replace( \"\\\"\", \"\" , $src ) );\n\n $image_tag = sprintf( '&lt;img src=%s%s%s%s%s width=\"%d\" height=\"%d\" /&gt;', $src, $alt, $title, $class, $id, $width, $height );\n $content = str_replace($image, $image_tag, $content);\n }\n }\n\n return $content;\n}\n</code></pre>\n" } ]
2016/08/18
[ "https://wordpress.stackexchange.com/questions/236318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98212/" ]
Using the WordPress `the_content` tag, I am running a custom function to search for all images that do not have a `width` and `height` attribute set and insert the proper dimensions. Below is the function: ``` add_filter( 'the_content', 'add_img_dimensions' ); function add_img_dimensions( $image_no_dimensions ) { // Insert width & height to images missing dimensions if ( preg_match_all( '/<img [^>]+width=[^>]+height=>/i', $image_no_dimensions, $result ) ) { // Do nothing... } else { preg_match_all( '/(alt|title|src)=("[^"]*")/i', $image_no_dimensions, $img ); list( $width, $height, $type, $attr ) = getimagesize( str_replace( "\"", "" , ( $img[2][0] ) ) ); $imgname = str_replace( "\"", "" , ( $img[2][0] ) ); } return sprintf( '<img src="%s" width="%dpx" height="%dpx" />', str_replace("\"", "" , ( $img[2][0] ) ), $width, $height ); } ``` For example, if there is an image on one of my pages that looks like the following: ``` <img src="https://link.to/sum/img.jpg" alt="Image Title" /> ``` It will then insert the `width` and `height` of the actual image: ``` <img width="150" height="50" src="https://link.to/sum/img.jpg" alt="Image Title" /> ``` The function works as expected. However, all of the page's content is replace with the first image that it finds that don't have dimensions set. How can I `return` all of the content but only change the images that don't have a dimension? **Before and after** [![enter image description here](https://i.stack.imgur.com/iImP8.gif)](https://i.stack.imgur.com/iImP8.gif)
Tested and confirmed that this works: ``` add_filter( 'the_content', 'add_image_dimensions' ); function add_image_dimensions( $content ) { preg_match_all( '/<img[^>]+>/i', $content, $images); if (count($images) < 1) return $content; foreach ($images[0] as $image) { preg_match_all( '/(alt|title|src|width|class|id|height)=("[^"]*")/i', $image, $img ); if ( !in_array( 'src', $img[1] ) ) continue; if ( !in_array( 'width', $img[1] ) || !in_array( 'height', $img[1] ) ) { $src = $img[2][ array_search('src', $img[1]) ]; $alt = in_array( 'alt', $img[1] ) ? ' alt=' . $img[2][ array_search('alt', $img[1]) ] : ''; $title = in_array( 'title', $img[1] ) ? ' title=' . $img[2][ array_search('title', $img[1]) ] : ''; $class = in_array( 'class', $img[1] ) ? ' class=' . $img[2][ array_search('class', $img[1]) ] : ''; $id = in_array( 'id', $img[1] ) ? ' id=' . $img[2][ array_search('id', $img[1]) ] : ''; list( $width, $height, $type, $attr ) = getimagesize( str_replace( "\"", "" , $src ) ); $image_tag = sprintf( '<img src=%s%s%s%s%s width="%d" height="%d" />', $src, $alt, $title, $class, $id, $width, $height ); $content = str_replace($image, $image_tag, $content); } } return $content; } ```
236,323
<p>I have created a <code>Custom Post Type</code> to publish multiple images together.</p> <p>--->>> title &lt;&lt;&lt;--- <br> --->>> image default - thumbnail &lt;&lt;&lt;--- <br> --->>> cotent &lt;&lt;&lt;--- <br> --->>>images&lt;&lt;&lt;--- <br> --->>>images&lt;&lt;&lt;--- <br> .....</p> <p>The first three sections (title, image default and content) is the basics. Is ready.</p> <p>I thought about using <code>custom metabox</code> and add each image URL. However, add url by url is nothing intuitive and a lot more work for the user, be it newbie or advanced. Furthermore, the amount will vary pictures can be 1, may be 5 may be 10 and so on....</p> <p>So, how do I add multiple images within a single post <code>CPT</code>?</p> <p>The Dashboard would look like this:</p> <p>--->>> title &lt;&lt;&lt;--- <br> --->>> image default - thumbnail &lt;&lt;&lt;--- <br> --->>> cotent &lt;&lt;&lt;--- <br> --->>> add images&lt;&lt;&lt;--- <br></p> <p>How can I do this? Be a plugin or direct in <code>function.php</code>.</p>
[ { "answer_id": 236325, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>As you rightly note storing URL is inconvenient for users. Also it is inconvenient for code, since it is hard to perform such operations as outputting different size of image when URL is all you have. It is rather challenging to do a <em>generic</em> reversal from image URL to its attachment data.</p>\n\n<p>For storage typical practice is to store attachment IDs. They are friendly for storage, querying, output, and resilient to changes like image sizes being replaced.</p>\n\n<p>Unfortunately natively WP only provides interface to store a single image — featured image aka post thumbnail.</p>\n\n<p>For the structure you describe basic approaches would be:</p>\n\n<ol>\n<li>Store thumbnail as featured image and rest of images in content, using native or plugin-extended gallery functionality. This just works and is convenient/familiar to users, but leaves more space for them to break it.</li>\n<li>Implement a custom meta box with custom interface for images. Core is of little help in this, but there are <em>multiple</em> custom field frameworks around that can be helpful, it's obviously a common use case. This makes development more challenging, but interface more specialized and with less room for user error.</li>\n</ol>\n" }, { "answer_id": 236399, "author": "user53340", "author_id": 98778, "author_profile": "https://wordpress.stackexchange.com/users/98778", "pm_score": 2, "selected": false, "text": "<p>As I understand it, you will need create a meta box with fields and use jQuery to add/remove the image boxes. You can also use jQuery UI to make the fields draggable if you like. </p>\n\n<p>Your meta box code will look something like this </p>\n\n<pre><code>// Fields\n$prefix = 'your_prefix_';\n\n$custom_meta_fields = array(\narray(\n 'label' =&gt; 'Gallery Images',\n 'desc' =&gt; 'Add additional images for this portfolio item.',\n 'id' =&gt; $prefix.'gallery_images',\n 'scope' =&gt; array('your_custom_post_type'),\n 'type' =&gt; 'repeatable_image',\n),\n);\n\n// Add the Meta Box\nfunction add_custom_meta_box()\n{\n $post_types = array('your_custom_post_type', 'page', 'post');\n foreach ($post_types as $post_type) {\n add_meta_box(\n 'custom_meta_box', // $id\n 'Additional Information', // $title\n 'show_custom_meta_box', // $callback\n $post_type,\n 'normal', // $context\n 'high' // $priority\n );\n }\n}\nadd_action('add_meta_boxes', 'add_custom_meta_box');\n// The Callback\nfunction show_custom_meta_box()\n{\n global $custom_meta_fields, $post;\n\n// Use nonce for verification\necho '&lt;input type=\"hidden\" name=\"custom_meta_box_nonce\" value=\"'.wp_create_nonce(basename(__FILE__)).'\" /&gt;';\n// Begin the field table and loop\necho '&lt;table class=\"form-table\"&gt;';\n\n foreach ($custom_meta_fields as $field) {\n //Check if scope matches post type\n$scope = $field[ 'scope' ];\n $field_output = false;\n foreach ($scope as $scopeItem) {\n switch ($scopeItem) {\ndefault: {\nif ($post-&gt;post_type == $scopeItem) {\n $field_output = true;\n}\nbreak;\n}\n}\n if ($field_output) {\n break;\n }\n }\n if ($field_output) {\n // get value of this field if it exists for this post\n$meta = get_post_meta($post-&gt;ID, $field['id'], true);\n $row = 0;\n// begin a table row with\necho '&lt;tr&gt;\n&lt;th&gt;&lt;label for=\"'.$field['id'].'\"&gt;'.$field['label'].'&lt;/label&gt;&lt;/th&gt;\n&lt;td&gt;';\n switch ($field['type']) {\n// text\ncase 'text':\necho '&lt;input type=\"text\" name=\"'.$field['id'].'\" id=\"'.$field['id'].'\" value=\"'.$meta.'\" size=\"30\" /&gt;\n&lt;br /&gt;&lt;span class=\"description\"&gt;'.$field['desc'].'&lt;/span&gt;';\nbreak;\n// repeatable\ncase 'repeatable_image':\n echo '&lt;a class=\"repeatable-add button\" href=\"#\"&gt;+&lt;/a&gt;\n &lt;ul id=\"'.$field['id'].'-repeatable\" class=\"custom_repeatable\"&gt;';\n $i = 0;\n if ($meta) {\n foreach ($meta as $row) {\n echo '&lt;li&gt;&lt;span class=\"sort hndle\"&gt;|||&lt;/span&gt;\n &lt;input type=\"text\" class=\"img_field\" name=\"'.$field['id'].'['.$i.']\" id=\"'.$field['id'].'\" value=\"'.$row.'\" size=\"30\" /&gt;\n &lt;a class=\"repeatable-remove button\" href=\"#\"&gt;-&lt;/a&gt;&lt;/li&gt;';\n ++$i;\n }\n } else {\n echo '&lt;li&gt;&lt;span class=\"sort hndle\"&gt;|||&lt;/span&gt;\n &lt;input class=\"img_field\" type=\"text\" name=\"'.$field['id'].'['.$i.']\" id=\"'.$field['id'].'\" value=\"\" size=\"30\" /&gt;\n &lt;a class=\"repeatable-remove button\" href=\"#\"&gt;-&lt;/a&gt;&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;\n &lt;span class=\"description\"&gt;'.$field['desc'].'&lt;/span&gt;';\nbreak;\n} //end switch\necho '&lt;/td&gt;&lt;/tr&gt;';\n }\n } // end foreach\necho '&lt;/table&gt;'; // end table\n}\n\n// Save the Data\nfunction save_custom_meta($post_id)\n{\n global $custom_meta_fields;\n// verify nonce\nif (!isset($_POST['custom_meta_box_nonce']) || !wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) {\n return $post_id;\n}\n// check autosave\nif (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) {\n return $post_id;\n}\n// check permissions\nif ('page' == $_POST['post_type']) {\n if (!current_user_can('edit_page', $post_id)) {\n return $post_id;\n } elseif (!current_user_can('edit_post', $post_id)) {\n return $post_id;\n }\n}\n// loop through fields and save the data\nforeach ($custom_meta_fields as $field) {\n $old = get_post_meta($post_id, $field['id'], true);\n if (isset($_POST[$field['id']])) {\n $new = $_POST[$field['id']];\n if ($field['type'] === 'repeatable_ad' || $field['type'] === 'repeatable_image') {\n $new = array_values($new);\n }\n }\n if ($new &amp;&amp; $new != $old) {\n update_post_meta($post_id, $field['id'], str_replace('\"', \"'\", $new));\n } elseif ('' == $new &amp;&amp; $old) {\n delete_post_meta($post_id, $field['id'], $old);\n }\n} // end foreach\n}\nadd_action('save_post', 'save_custom_meta');\n</code></pre>\n\n<p>and your js will need to be something like this </p>\n\n<pre><code>jQuery(document).on('click', '.img_field', function(e) {\n\n\n\nvar clicked_field = e.target.name;\n\n\nvar custom_uploader;\n\n\n e.preventDefault();\n\n //If the uploader object has already been created, reopen the dialog\n if (custom_uploader) {\n custom_uploader.open();\n return;\n }\n\n //Extend the wp.media object\n custom_uploader = wp.media.frames.file_frame = wp.media({\n title: 'Select Image',\n button: {\n text: 'Select Image'\n },\n multiple: false\n });\n\n //When a file is selected, grab the URL and set it as the text field's value\n custom_uploader.on('select', function() {\n attachment = custom_uploader.state().get('selection').first().toJSON();\n jQuery('input[name=\"'+ clicked_field +'\"]').val(attachment.url);\n jQuery('.custom_preview_image').attr('src', attachment.url);\n jQuery('.custom_media_image').attr('src',attachment.url);\n });\n\n //Open the uploader dialog\n custom_uploader.open();\n\n});\n\n\njQuery('.repeatable-add').click(function() {\n field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true);\n fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last');\n jQuery('input', field).val('').attr('name', function(index, name) {\n return name.replace(/(\\d+)/, function(fullMatch, n) {\n return Number(n) + 1;\n });\n })\n field.insertAfter(fieldLocation, jQuery(this).closest('td'))\n return false;\n});\n\njQuery('.repeatable-remove').click(function(){\n jQuery(this).parent().remove();\n return false;\n});\n\njQuery('.custom_repeatable').sortable({\n opacity: 0.6,\n revert: true,\n cursor: 'move',\n handle: '.sort'\n});\n</code></pre>\n\n<p>I haven't tested this, so let me know if it doesn't work but it should give you a good head start. Having said all that, it's much easier to use <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow\">ACF</a> or <a href=\"https://github.com/WebDevStudios/CMB2\" rel=\"nofollow\">CMB2</a> to do this sort of thing. Anyway, I hope this helps.</p>\n" }, { "answer_id": 237292, "author": "Unnikrishnan R", "author_id": 101689, "author_profile": "https://wordpress.stackexchange.com/users/101689", "pm_score": 0, "selected": false, "text": "<p>Advanced custom field plugin provides this functionality through an additional add on named acf repeater field <a href=\"https://www.advancedcustomfields.com/resources/repeater/\" rel=\"nofollow\">www.advancedcustomfields.com/resources/repeater</a>\nin which you can add the same field multiple times in a post</p>\n" }, { "answer_id": 237363, "author": "Zkk", "author_id": 94215, "author_profile": "https://wordpress.stackexchange.com/users/94215", "pm_score": 2, "selected": true, "text": "<hr>\n\n<h2> UPDATED</h2>\n\n<p>I got it! I made this way, I created a gallery within the wordpress editor. And with foreach, I took the ID of each image and display in the Loop:</p>\n\n<pre><code>&lt;?php\nglobal $post;\n$gallery = get_post_gallery_images( $post );\n\nforeach( $gallery as $image_url ) {\n?&gt;\n&lt;div class=\"item\"&gt;\n &lt;figure style=\"margin: 0px !important\" itemprop=\"associatedMedia\" itemscope itemtype=\"http://schema.org/ImageObject\"&gt;\n &lt;a href=\"&lt;?php echo $image_url ?&gt;\" itemprop=\"contentUrl\" data-size=\"1800x1200\" data-index=\"0\"&gt;\n &lt;img src=\"&lt;?php echo $image_url ?&gt;\" class=\"image\" itemprop=\"thumbnail\" alt=\"\"&gt;\n &lt;/a&gt;\n &lt;/figure&gt;\n&lt;/div&gt;\n&lt;?php \n}\n?&gt;\n</code></pre>\n" } ]
2016/08/18
[ "https://wordpress.stackexchange.com/questions/236323", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94215/" ]
I have created a `Custom Post Type` to publish multiple images together. --->>> title <<<--- --->>> image default - thumbnail <<<--- --->>> cotent <<<--- --->>>images<<<--- --->>>images<<<--- ..... The first three sections (title, image default and content) is the basics. Is ready. I thought about using `custom metabox` and add each image URL. However, add url by url is nothing intuitive and a lot more work for the user, be it newbie or advanced. Furthermore, the amount will vary pictures can be 1, may be 5 may be 10 and so on.... So, how do I add multiple images within a single post `CPT`? The Dashboard would look like this: --->>> title <<<--- --->>> image default - thumbnail <<<--- --->>> cotent <<<--- --->>> add images<<<--- How can I do this? Be a plugin or direct in `function.php`.
--- UPDATED -------- I got it! I made this way, I created a gallery within the wordpress editor. And with foreach, I took the ID of each image and display in the Loop: ``` <?php global $post; $gallery = get_post_gallery_images( $post ); foreach( $gallery as $image_url ) { ?> <div class="item"> <figure style="margin: 0px !important" itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject"> <a href="<?php echo $image_url ?>" itemprop="contentUrl" data-size="1800x1200" data-index="0"> <img src="<?php echo $image_url ?>" class="image" itemprop="thumbnail" alt=""> </a> </figure> </div> <?php } ?> ```
236,332
<p>When the a loop runs can I have each new post it grabs its own HTML class?</p> <h3>For example</h3> <ul> <li>Loop runs</li> <li>First item gets <code>class="first"</code></li> <li>Second item gets <code>class="second"</code></li> <li>and so on...</li> </ul> <p>Or each post just gets an equivalent numbered <code>class=</code> 1, 2, 3, 4, etc.</p> <p>I've just been using CSS with <code>nth-child()</code> to target each new item. </p> <p><strong>index.php</strong> (here's the loop call and get_template_part pulls content.php with the loop contents)</p> <p>```</p> <pre><code> &lt;?php $the_query = new WP_Query( array('post_type'=&gt;'post', 'post_status'=&gt;'publish', 'posts_per_page'=&gt;5, 'paged'=&gt;$paged) ); ?&gt; &lt;?php if ( $the_query-&gt;have_posts() ) : ?&gt; &lt;?php $counter = 1; ?&gt; &lt;?php while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;?php get_template_part( 'content', get_post_format() ); ?&gt; </code></pre> <p>```</p> <p><strong>content.php</strong> ( Here's the contents start of the loop where I want to add the class )</p> <p>```</p> <pre><code> &lt;?php include(locate_template('index.php')); ?&gt; &lt;?php $counter++; ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class( 'inline-post-' . $counter ); ?&gt;&gt; </code></pre> <p>```</p>
[ { "answer_id": 236325, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>As you rightly note storing URL is inconvenient for users. Also it is inconvenient for code, since it is hard to perform such operations as outputting different size of image when URL is all you have. It is rather challenging to do a <em>generic</em> reversal from image URL to its attachment data.</p>\n\n<p>For storage typical practice is to store attachment IDs. They are friendly for storage, querying, output, and resilient to changes like image sizes being replaced.</p>\n\n<p>Unfortunately natively WP only provides interface to store a single image — featured image aka post thumbnail.</p>\n\n<p>For the structure you describe basic approaches would be:</p>\n\n<ol>\n<li>Store thumbnail as featured image and rest of images in content, using native or plugin-extended gallery functionality. This just works and is convenient/familiar to users, but leaves more space for them to break it.</li>\n<li>Implement a custom meta box with custom interface for images. Core is of little help in this, but there are <em>multiple</em> custom field frameworks around that can be helpful, it's obviously a common use case. This makes development more challenging, but interface more specialized and with less room for user error.</li>\n</ol>\n" }, { "answer_id": 236399, "author": "user53340", "author_id": 98778, "author_profile": "https://wordpress.stackexchange.com/users/98778", "pm_score": 2, "selected": false, "text": "<p>As I understand it, you will need create a meta box with fields and use jQuery to add/remove the image boxes. You can also use jQuery UI to make the fields draggable if you like. </p>\n\n<p>Your meta box code will look something like this </p>\n\n<pre><code>// Fields\n$prefix = 'your_prefix_';\n\n$custom_meta_fields = array(\narray(\n 'label' =&gt; 'Gallery Images',\n 'desc' =&gt; 'Add additional images for this portfolio item.',\n 'id' =&gt; $prefix.'gallery_images',\n 'scope' =&gt; array('your_custom_post_type'),\n 'type' =&gt; 'repeatable_image',\n),\n);\n\n// Add the Meta Box\nfunction add_custom_meta_box()\n{\n $post_types = array('your_custom_post_type', 'page', 'post');\n foreach ($post_types as $post_type) {\n add_meta_box(\n 'custom_meta_box', // $id\n 'Additional Information', // $title\n 'show_custom_meta_box', // $callback\n $post_type,\n 'normal', // $context\n 'high' // $priority\n );\n }\n}\nadd_action('add_meta_boxes', 'add_custom_meta_box');\n// The Callback\nfunction show_custom_meta_box()\n{\n global $custom_meta_fields, $post;\n\n// Use nonce for verification\necho '&lt;input type=\"hidden\" name=\"custom_meta_box_nonce\" value=\"'.wp_create_nonce(basename(__FILE__)).'\" /&gt;';\n// Begin the field table and loop\necho '&lt;table class=\"form-table\"&gt;';\n\n foreach ($custom_meta_fields as $field) {\n //Check if scope matches post type\n$scope = $field[ 'scope' ];\n $field_output = false;\n foreach ($scope as $scopeItem) {\n switch ($scopeItem) {\ndefault: {\nif ($post-&gt;post_type == $scopeItem) {\n $field_output = true;\n}\nbreak;\n}\n}\n if ($field_output) {\n break;\n }\n }\n if ($field_output) {\n // get value of this field if it exists for this post\n$meta = get_post_meta($post-&gt;ID, $field['id'], true);\n $row = 0;\n// begin a table row with\necho '&lt;tr&gt;\n&lt;th&gt;&lt;label for=\"'.$field['id'].'\"&gt;'.$field['label'].'&lt;/label&gt;&lt;/th&gt;\n&lt;td&gt;';\n switch ($field['type']) {\n// text\ncase 'text':\necho '&lt;input type=\"text\" name=\"'.$field['id'].'\" id=\"'.$field['id'].'\" value=\"'.$meta.'\" size=\"30\" /&gt;\n&lt;br /&gt;&lt;span class=\"description\"&gt;'.$field['desc'].'&lt;/span&gt;';\nbreak;\n// repeatable\ncase 'repeatable_image':\n echo '&lt;a class=\"repeatable-add button\" href=\"#\"&gt;+&lt;/a&gt;\n &lt;ul id=\"'.$field['id'].'-repeatable\" class=\"custom_repeatable\"&gt;';\n $i = 0;\n if ($meta) {\n foreach ($meta as $row) {\n echo '&lt;li&gt;&lt;span class=\"sort hndle\"&gt;|||&lt;/span&gt;\n &lt;input type=\"text\" class=\"img_field\" name=\"'.$field['id'].'['.$i.']\" id=\"'.$field['id'].'\" value=\"'.$row.'\" size=\"30\" /&gt;\n &lt;a class=\"repeatable-remove button\" href=\"#\"&gt;-&lt;/a&gt;&lt;/li&gt;';\n ++$i;\n }\n } else {\n echo '&lt;li&gt;&lt;span class=\"sort hndle\"&gt;|||&lt;/span&gt;\n &lt;input class=\"img_field\" type=\"text\" name=\"'.$field['id'].'['.$i.']\" id=\"'.$field['id'].'\" value=\"\" size=\"30\" /&gt;\n &lt;a class=\"repeatable-remove button\" href=\"#\"&gt;-&lt;/a&gt;&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;\n &lt;span class=\"description\"&gt;'.$field['desc'].'&lt;/span&gt;';\nbreak;\n} //end switch\necho '&lt;/td&gt;&lt;/tr&gt;';\n }\n } // end foreach\necho '&lt;/table&gt;'; // end table\n}\n\n// Save the Data\nfunction save_custom_meta($post_id)\n{\n global $custom_meta_fields;\n// verify nonce\nif (!isset($_POST['custom_meta_box_nonce']) || !wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) {\n return $post_id;\n}\n// check autosave\nif (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) {\n return $post_id;\n}\n// check permissions\nif ('page' == $_POST['post_type']) {\n if (!current_user_can('edit_page', $post_id)) {\n return $post_id;\n } elseif (!current_user_can('edit_post', $post_id)) {\n return $post_id;\n }\n}\n// loop through fields and save the data\nforeach ($custom_meta_fields as $field) {\n $old = get_post_meta($post_id, $field['id'], true);\n if (isset($_POST[$field['id']])) {\n $new = $_POST[$field['id']];\n if ($field['type'] === 'repeatable_ad' || $field['type'] === 'repeatable_image') {\n $new = array_values($new);\n }\n }\n if ($new &amp;&amp; $new != $old) {\n update_post_meta($post_id, $field['id'], str_replace('\"', \"'\", $new));\n } elseif ('' == $new &amp;&amp; $old) {\n delete_post_meta($post_id, $field['id'], $old);\n }\n} // end foreach\n}\nadd_action('save_post', 'save_custom_meta');\n</code></pre>\n\n<p>and your js will need to be something like this </p>\n\n<pre><code>jQuery(document).on('click', '.img_field', function(e) {\n\n\n\nvar clicked_field = e.target.name;\n\n\nvar custom_uploader;\n\n\n e.preventDefault();\n\n //If the uploader object has already been created, reopen the dialog\n if (custom_uploader) {\n custom_uploader.open();\n return;\n }\n\n //Extend the wp.media object\n custom_uploader = wp.media.frames.file_frame = wp.media({\n title: 'Select Image',\n button: {\n text: 'Select Image'\n },\n multiple: false\n });\n\n //When a file is selected, grab the URL and set it as the text field's value\n custom_uploader.on('select', function() {\n attachment = custom_uploader.state().get('selection').first().toJSON();\n jQuery('input[name=\"'+ clicked_field +'\"]').val(attachment.url);\n jQuery('.custom_preview_image').attr('src', attachment.url);\n jQuery('.custom_media_image').attr('src',attachment.url);\n });\n\n //Open the uploader dialog\n custom_uploader.open();\n\n});\n\n\njQuery('.repeatable-add').click(function() {\n field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true);\n fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last');\n jQuery('input', field).val('').attr('name', function(index, name) {\n return name.replace(/(\\d+)/, function(fullMatch, n) {\n return Number(n) + 1;\n });\n })\n field.insertAfter(fieldLocation, jQuery(this).closest('td'))\n return false;\n});\n\njQuery('.repeatable-remove').click(function(){\n jQuery(this).parent().remove();\n return false;\n});\n\njQuery('.custom_repeatable').sortable({\n opacity: 0.6,\n revert: true,\n cursor: 'move',\n handle: '.sort'\n});\n</code></pre>\n\n<p>I haven't tested this, so let me know if it doesn't work but it should give you a good head start. Having said all that, it's much easier to use <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow\">ACF</a> or <a href=\"https://github.com/WebDevStudios/CMB2\" rel=\"nofollow\">CMB2</a> to do this sort of thing. Anyway, I hope this helps.</p>\n" }, { "answer_id": 237292, "author": "Unnikrishnan R", "author_id": 101689, "author_profile": "https://wordpress.stackexchange.com/users/101689", "pm_score": 0, "selected": false, "text": "<p>Advanced custom field plugin provides this functionality through an additional add on named acf repeater field <a href=\"https://www.advancedcustomfields.com/resources/repeater/\" rel=\"nofollow\">www.advancedcustomfields.com/resources/repeater</a>\nin which you can add the same field multiple times in a post</p>\n" }, { "answer_id": 237363, "author": "Zkk", "author_id": 94215, "author_profile": "https://wordpress.stackexchange.com/users/94215", "pm_score": 2, "selected": true, "text": "<hr>\n\n<h2> UPDATED</h2>\n\n<p>I got it! I made this way, I created a gallery within the wordpress editor. And with foreach, I took the ID of each image and display in the Loop:</p>\n\n<pre><code>&lt;?php\nglobal $post;\n$gallery = get_post_gallery_images( $post );\n\nforeach( $gallery as $image_url ) {\n?&gt;\n&lt;div class=\"item\"&gt;\n &lt;figure style=\"margin: 0px !important\" itemprop=\"associatedMedia\" itemscope itemtype=\"http://schema.org/ImageObject\"&gt;\n &lt;a href=\"&lt;?php echo $image_url ?&gt;\" itemprop=\"contentUrl\" data-size=\"1800x1200\" data-index=\"0\"&gt;\n &lt;img src=\"&lt;?php echo $image_url ?&gt;\" class=\"image\" itemprop=\"thumbnail\" alt=\"\"&gt;\n &lt;/a&gt;\n &lt;/figure&gt;\n&lt;/div&gt;\n&lt;?php \n}\n?&gt;\n</code></pre>\n" } ]
2016/08/18
[ "https://wordpress.stackexchange.com/questions/236332", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82731/" ]
When the a loop runs can I have each new post it grabs its own HTML class? ### For example * Loop runs * First item gets `class="first"` * Second item gets `class="second"` * and so on... Or each post just gets an equivalent numbered `class=` 1, 2, 3, 4, etc. I've just been using CSS with `nth-child()` to target each new item. **index.php** (here's the loop call and get\_template\_part pulls content.php with the loop contents) ``` ``` <?php $the_query = new WP_Query( array('post_type'=>'post', 'post_status'=>'publish', 'posts_per_page'=>5, 'paged'=>$paged) ); ?> <?php if ( $the_query->have_posts() ) : ?> <?php $counter = 1; ?> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> ``` ``` **content.php** ( Here's the contents start of the loop where I want to add the class ) ``` ``` <?php include(locate_template('index.php')); ?> <?php $counter++; ?> <article id="post-<?php the_ID(); ?>" <?php post_class( 'inline-post-' . $counter ); ?>> ``` ```
--- UPDATED -------- I got it! I made this way, I created a gallery within the wordpress editor. And with foreach, I took the ID of each image and display in the Loop: ``` <?php global $post; $gallery = get_post_gallery_images( $post ); foreach( $gallery as $image_url ) { ?> <div class="item"> <figure style="margin: 0px !important" itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject"> <a href="<?php echo $image_url ?>" itemprop="contentUrl" data-size="1800x1200" data-index="0"> <img src="<?php echo $image_url ?>" class="image" itemprop="thumbnail" alt=""> </a> </figure> </div> <?php } ?> ```
236,335
<p>I have a client who wants to close down access to the entire site, every post, category page, archive etc (while keeping the content), except for three specific pages (Start, about us, contact).</p> <p>None of the membership plugins seem to address this, only logged in roles? I feel like this is the most simple thing ever, but I just can't seem to solve it.</p> <p>Edit: Basically, what I'm saying is "if page x, x or x" continue, "else display message".</p>
[ { "answer_id": 236340, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 3, "selected": true, "text": "<p>If you want to show a message, use this code in your <code>functions.php</code> file-</p>\n\n<pre><code>function se_236335_hide_content( $content ){\n $pages = array( 8, 26, 35 ); // allowed page IDs\n if( ! in_array( get_the_id(), $pages ) ){\n return 'Message here..';\n }\n return $content;\n\n}\nadd_filter( 'the_content', 'se_236335_hide_content' );\n</code></pre>\n\n<p>If you want a page redirection, use this-</p>\n\n<pre><code>function se_236335_redirect(){\n // allowed pages IDs\n $p1 = 9;\n $p2 = 11;\n $p3 = 35;\n // redirect location\n $location = 9;\n\n if( ! is_page( [ $p1, $p2, $p3 ] ) ) {\n wp_redirect( get_permalink( $location ) );\n exit();\n }\n}\nadd_action( 'wp', 'se_236335_redirect' );\n</code></pre>\n" }, { "answer_id": 236358, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 0, "selected": false, "text": "<p>An alternative approach would be to use the <code>$query</code> object to modify the query accordingly</p>\n\n<pre><code>add_action('init', 'wpse_236335_hide_content' );\nfunction wpse_236335_hide_content(){\n\n // Apply hook everywhere for non logged in users except on wp-login.php page\n if( ! is_user_logged_in() &amp;&amp; $GLOBALS['pagenow'] !== 'wp-login.php' )\n add_action( 'pre_get_posts', 'my_permitted_content' );\n\n}\n\n\nfunction my_permitted_content( $query ){\n\n // If we are on any of those pages, by ID, proceed as normal\n if( $query-&gt;is_page( array( 9, 11, 35 ) ) ) {\n return;\n }\n\n // set query so nothing is returned. using trash because trashed post are not shown by design\n $query-&gt;set( 'post_status', 'trash' ); \n\n // if we are not on the blog roll or the home page. redirect to home page.\n if( ! $query-&gt;is_home() || ! $query-&gt;is_front_page() ){\n wp_redirect( site_url() );\n exit;\n } \n\n}\n</code></pre>\n" } ]
2016/08/18
[ "https://wordpress.stackexchange.com/questions/236335", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/32862/" ]
I have a client who wants to close down access to the entire site, every post, category page, archive etc (while keeping the content), except for three specific pages (Start, about us, contact). None of the membership plugins seem to address this, only logged in roles? I feel like this is the most simple thing ever, but I just can't seem to solve it. Edit: Basically, what I'm saying is "if page x, x or x" continue, "else display message".
If you want to show a message, use this code in your `functions.php` file- ``` function se_236335_hide_content( $content ){ $pages = array( 8, 26, 35 ); // allowed page IDs if( ! in_array( get_the_id(), $pages ) ){ return 'Message here..'; } return $content; } add_filter( 'the_content', 'se_236335_hide_content' ); ``` If you want a page redirection, use this- ``` function se_236335_redirect(){ // allowed pages IDs $p1 = 9; $p2 = 11; $p3 = 35; // redirect location $location = 9; if( ! is_page( [ $p1, $p2, $p3 ] ) ) { wp_redirect( get_permalink( $location ) ); exit(); } } add_action( 'wp', 'se_236335_redirect' ); ```
236,370
<p>I'm new to WordPress. I'm including my file using</p> <pre><code>&lt;link rel='stylesheet' href="&lt;?php bloginfo("stylesheet_url")?&gt;"/&gt; </code></pre> <p>But if i enqueue my css file in <code>functions.php</code> it is not working. Why? Where is my mistake?</p> <pre><code>&lt;?php wp_enqueue_style('style',get_template_directory_uri())?&gt; </code></pre> <p>What is the solution for this?</p>
[ { "answer_id": 236372, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 2, "selected": false, "text": "<p>You are calling the function wrong. You have not given your filename, just a directory.</p>\n\n<p>From the <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow\">codex</a></p>\n\n<pre><code>wp_enqueue_style( string $handle, string $src = false, array $deps = array(), string|bool|null $ver = false, string $media = 'all' )\n</code></pre>\n\n<p>so in your case, you should enqueue like so</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_my_style' );\nfunction wpse_my_style(){\n wp_enqueue_style( 'my-style', get_stylesheet_directory_uri() . 'path/to/your/css' );\n} \n</code></pre>\n\n<p>the rest of the parameters are optional</p>\n" }, { "answer_id": 236373, "author": "Rishabh", "author_id": 81621, "author_profile": "https://wordpress.stackexchange.com/users/81621", "pm_score": -1, "selected": false, "text": "<pre><code>function wpdocs_style() {\nwp_enqueue_style( 'style-name', get_stylesheet_uri() ); //This is for getting style.css of current theme\nwp_enqueue_style( 'style-name1', get_teplate_directory_uri() . '/css/custom.css', array('jquery') ); //This is for getting other css file from parent directory \nwp_enqueue_script( 'script-name1', get_teplate_directory_uri() . '/js/custom.js', array('jquery') ); //This is for getting JS file from parent directory \n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_style' );\n OR\n//Or as an laternate you can hook with wp_head also\nadd_action( 'wp_head', 'wpdocs_style' );\n</code></pre>\n\n<p>In order to run the above function need to add <code>&lt;?php wp_enqueue_script(\"jquery\"); ?&gt;</code> (If you use this action <code>add_action( 'wp_enqueue_scripts', 'wpdocs_style' );</code>) in <code>header.php</code> befor <code>&lt;/head&gt;</code>.</p>\n\n<p>You have to assign name to every style (like I assign style-name, style-name1 etc) and name should be unique.\nAnd if you want to qnqueue from child theme's functions.php then you have to use <code>get_stylesheet_directory_uri()</code> instead of <code>get_teplate_directory_uri()</code>.</p>\n" } ]
2016/08/19
[ "https://wordpress.stackexchange.com/questions/236370", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101257/" ]
I'm new to WordPress. I'm including my file using ``` <link rel='stylesheet' href="<?php bloginfo("stylesheet_url")?>"/> ``` But if i enqueue my css file in `functions.php` it is not working. Why? Where is my mistake? ``` <?php wp_enqueue_style('style',get_template_directory_uri())?> ``` What is the solution for this?
You are calling the function wrong. You have not given your filename, just a directory. From the [codex](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) ``` wp_enqueue_style( string $handle, string $src = false, array $deps = array(), string|bool|null $ver = false, string $media = 'all' ) ``` so in your case, you should enqueue like so ``` add_action( 'wp_enqueue_scripts', 'wpse_my_style' ); function wpse_my_style(){ wp_enqueue_style( 'my-style', get_stylesheet_directory_uri() . 'path/to/your/css' ); } ``` the rest of the parameters are optional
236,400
<p>I made HTML/CSS design of a web site, and now I need to convert it to WordPress. The part that I am working on right now is Adding slick slider to show only on my WP front page. It works perfectly in HTML (because there I incorporated javascript which could be found on actual slick slider website and initiated through 3 div elements with images inside.).</p> <p>In WP functions.php I added:</p> <pre><code> //Add slider add_action( 'init', 'create_post_type' ); function create_post_type() { register_post_type( 'slider', array( 'labels' =&gt; array( 'name' =&gt; __( 'Sliders' ), 'singular_name' =&gt; __( 'Slider' ), 'add_new' =&gt; 'Add new slide', ), 'public' =&gt; true, ) ); } ?&gt; </code></pre> <p>I also enqueued scripts and styles like this (in functions.php also):</p> <pre><code> //Enqueue scripts add_action('wp_enqueue_scripts', 'wp_enqueue_all_scripts', 999); function wp_enqueue_all_scripts(){ //add slick slider wp_register_style('slickcss', get_template_directory_uri()."/slick/slick.css" ); wp_register_style('slickcsstheme', get_template_directory_uri()."/slick/slick-theme.css" ); //load slick js wp_register_script('slickslider', get_template_directory_uri()."/slick/slick.min.js", array(jquery), '', true ); ////load slick initiate script wp_register_script( 'slickinit', get_template_directory_uri() . '/assets/js/slick-init.js'); // load slick on homepage if ( is_front_page() ) { wp_enqueue_style( 'slickcss' ); wp_enqueue_style( 'slickcsstheme' ); wp_enqueue_script ('slickslider'); wp_enqueue_script ('slickinit'); } } </code></pre> <p>I added slick.init in js folder and it looks like this:</p> <pre><code> jQuery(document).ready(function($){ $('.featured-image-slider').slick({ //add CSS class of target infinite: true, slidesToShow: 3, slidesToScroll: 1, autoplay: true, autoplaySpeed: 2000, }) }); </code></pre> <p>I made front-page.php and I put the code in there like this:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php // WP_Query arguments $args = array ( 'post_type' =&gt; array( 'slider' ), ); // The Query $query_slider = new WP_Query( $args ); // The Loop if ( $query_slider-&gt;have_posts() ) { echo '&lt;div class="home regular slider"&gt;'; while ( $query_slider-&gt;have_posts() ) { $query_slider-&gt;the_post(); echo '&lt;div&gt; '; the_post_thumbnail(); echo '&lt;/div&gt;'; } echo '&lt;/div&gt;'; } else { // no posts found } // Restore original Post Data wp_reset_postdata(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>When I go to Sliders -> Add new slide in my dashboard, the slide is not showing on my front page. I am going out of my mind and would really appreciate help. How do I resolve this, what am I doing wrong? I am a total newbie and for the life of me I can not resolve it myself. Thank you.</p>
[ { "answer_id": 236407, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 2, "selected": true, "text": "<p>First of all you've written <code>array(jquery)</code> instead of <code>array('jquery')</code>. And also has not defined the <code>slickinit</code> enqueue position. So the right code will be-</p>\n\n<pre><code> //Enqueue scripts\nadd_action('wp_enqueue_scripts', 'wp_enqueue_all_scripts', 999);\n\nfunction wp_enqueue_all_scripts(){\n\n //add slick slider\n wp_register_style('slickcss', get_template_directory_uri() . '/slick/slick.css' );\n wp_register_style('slickcsstheme', get_template_directory_uri() . '/slick/slick-theme.css' );\n\n //load slick js\n wp_register_script('slickslider', get_template_directory_uri() . '/slick/slick.min.js', array('jquery'), '', true );\n\n ////load slick initiate script\n wp_register_script( 'slickinit', get_template_directory_uri() . '/assets/js/slick-init.js', array( 'jquery', 'slickslider' ) );\n\n // load slick on homepage\n if ( is_front_page() ) {\n wp_enqueue_style( 'slickcss' );\n wp_enqueue_style( 'slickcsstheme' );\n wp_enqueue_script ('slickslider');\n wp_enqueue_script ('slickinit');\n }\n}\n</code></pre>\n\n<p>And at your <code>front-page.php</code> try this-</p>\n\n<pre><code>&lt;?php get_header(); ?&gt;\n\n&lt;?php\n\n// WP_Query arguments\n$args = array (\n 'post_type' =&gt; array( 'slider' ),\n);\n\n// The Query\n$query_slider = new WP_Query( $args );\n\n// The Loop\nif ( $query_slider-&gt;have_posts() ) {\n echo '&lt;div class=\"home regular slider\"&gt;';\n while ( $query_slider-&gt;have_posts() ) {\n $query_slider-&gt;the_post();\n echo '&lt;div class=\"featured-image-slider\"&gt; ';\n the_post_thumbnail();\n echo '&lt;/div&gt;';\n }\n echo '&lt;/div&gt;';\n} else {\n // no posts found\n}\n\n// Restore original Post Data\nwp_reset_postdata();\n\n?&gt;\n\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>Hope that thing will be working now.</p>\n" }, { "answer_id": 243700, "author": "Philipp Bammes", "author_id": 48203, "author_profile": "https://wordpress.stackexchange.com/users/48203", "pm_score": 0, "selected": false, "text": "<p>I'm the author of WordPress plugin <a href=\"https://wordpress.org/plugins/slick-slider/\" rel=\"nofollow\">Slick Slider</a>. It turns native WordPress galleries (<code>[gallery ids=\"x,y,z\"]</code>) into sliders utilizing the great <a href=\"https://kenwheeler.github.io/slick/\" rel=\"nofollow\">slick slider</a> written by Ken Wheeler (which you also implement).</p>\n\n<p>Using the plugin you wouldn't have to use custom post types.\nGive it a try.</p>\n" } ]
2016/08/19
[ "https://wordpress.stackexchange.com/questions/236400", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101279/" ]
I made HTML/CSS design of a web site, and now I need to convert it to WordPress. The part that I am working on right now is Adding slick slider to show only on my WP front page. It works perfectly in HTML (because there I incorporated javascript which could be found on actual slick slider website and initiated through 3 div elements with images inside.). In WP functions.php I added: ``` //Add slider add_action( 'init', 'create_post_type' ); function create_post_type() { register_post_type( 'slider', array( 'labels' => array( 'name' => __( 'Sliders' ), 'singular_name' => __( 'Slider' ), 'add_new' => 'Add new slide', ), 'public' => true, ) ); } ?> ``` I also enqueued scripts and styles like this (in functions.php also): ``` //Enqueue scripts add_action('wp_enqueue_scripts', 'wp_enqueue_all_scripts', 999); function wp_enqueue_all_scripts(){ //add slick slider wp_register_style('slickcss', get_template_directory_uri()."/slick/slick.css" ); wp_register_style('slickcsstheme', get_template_directory_uri()."/slick/slick-theme.css" ); //load slick js wp_register_script('slickslider', get_template_directory_uri()."/slick/slick.min.js", array(jquery), '', true ); ////load slick initiate script wp_register_script( 'slickinit', get_template_directory_uri() . '/assets/js/slick-init.js'); // load slick on homepage if ( is_front_page() ) { wp_enqueue_style( 'slickcss' ); wp_enqueue_style( 'slickcsstheme' ); wp_enqueue_script ('slickslider'); wp_enqueue_script ('slickinit'); } } ``` I added slick.init in js folder and it looks like this: ``` jQuery(document).ready(function($){ $('.featured-image-slider').slick({ //add CSS class of target infinite: true, slidesToShow: 3, slidesToScroll: 1, autoplay: true, autoplaySpeed: 2000, }) }); ``` I made front-page.php and I put the code in there like this: ``` <?php get_header(); ?> <?php // WP_Query arguments $args = array ( 'post_type' => array( 'slider' ), ); // The Query $query_slider = new WP_Query( $args ); // The Loop if ( $query_slider->have_posts() ) { echo '<div class="home regular slider">'; while ( $query_slider->have_posts() ) { $query_slider->the_post(); echo '<div> '; the_post_thumbnail(); echo '</div>'; } echo '</div>'; } else { // no posts found } // Restore original Post Data wp_reset_postdata(); ?> <?php get_footer(); ?> ``` When I go to Sliders -> Add new slide in my dashboard, the slide is not showing on my front page. I am going out of my mind and would really appreciate help. How do I resolve this, what am I doing wrong? I am a total newbie and for the life of me I can not resolve it myself. Thank you.
First of all you've written `array(jquery)` instead of `array('jquery')`. And also has not defined the `slickinit` enqueue position. So the right code will be- ``` //Enqueue scripts add_action('wp_enqueue_scripts', 'wp_enqueue_all_scripts', 999); function wp_enqueue_all_scripts(){ //add slick slider wp_register_style('slickcss', get_template_directory_uri() . '/slick/slick.css' ); wp_register_style('slickcsstheme', get_template_directory_uri() . '/slick/slick-theme.css' ); //load slick js wp_register_script('slickslider', get_template_directory_uri() . '/slick/slick.min.js', array('jquery'), '', true ); ////load slick initiate script wp_register_script( 'slickinit', get_template_directory_uri() . '/assets/js/slick-init.js', array( 'jquery', 'slickslider' ) ); // load slick on homepage if ( is_front_page() ) { wp_enqueue_style( 'slickcss' ); wp_enqueue_style( 'slickcsstheme' ); wp_enqueue_script ('slickslider'); wp_enqueue_script ('slickinit'); } } ``` And at your `front-page.php` try this- ``` <?php get_header(); ?> <?php // WP_Query arguments $args = array ( 'post_type' => array( 'slider' ), ); // The Query $query_slider = new WP_Query( $args ); // The Loop if ( $query_slider->have_posts() ) { echo '<div class="home regular slider">'; while ( $query_slider->have_posts() ) { $query_slider->the_post(); echo '<div class="featured-image-slider"> '; the_post_thumbnail(); echo '</div>'; } echo '</div>'; } else { // no posts found } // Restore original Post Data wp_reset_postdata(); ?> <?php get_footer(); ?> ``` Hope that thing will be working now.
236,425
<p>I'm using the Gazette theme which has a jet pack enabled featured posts grid when the front page is set to show latest posts.</p> <p>I would like to use a static page instead of recent posts, but keep the featured posts grid. </p> <hr> <p><strong>UPDATE</strong></p> <p>I was able to figure this out with a little moral support from the community</p> <p>Link to answer - <a href="https://wordpress.stackexchange.com/questions/236425/display-featured-posts-grid-on-static-page-gazette#answer-236518">Display Featured Posts Grid on Static Page (Gazette)</a> </p> <hr> <p>Demo: <a href="https://gazettedemo.wordpress.com/" rel="nofollow noreferrer">https://gazettedemo.wordpress.com/</a></p> <p>Source: <a href="https://public-api.wordpress.com/rest/v1/themes/download/gazette.zip" rel="nofollow noreferrer">https://public-api.wordpress.com/rest/v1/themes/download/gazette.zip</a></p> <p><strong>Code parts associated with the featured posts</strong></p> <p>@ index.php</p> <pre><code>&lt;?php if ( is_home() ) { // Include the featured content template. get_template_part( 'featured-content' ); } ?&gt; &lt;?php if ( have_posts() ) : ?&gt; &lt;?php /* Start the Loop */ ?&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;?php get_template_part( 'content', get_post_format() ); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php the_posts_navigation(); ?&gt; &lt;?php else : ?&gt; &lt;?php get_template_part( 'content', 'none' ); ?&gt; &lt;?php endif; ?&gt; </code></pre> <p>@ functions.php line 197</p> <pre><code>wp_enqueue_script( 'gazette-featured-content', get_template_directory_uri() . '/js/featured-content.js', array( 'jquery' ), '20150507', true ); </code></pre> <p>@ featured-content.php</p> <pre><code>$featured_posts = gazette_get_featured_posts(); if ( empty( $featured_posts ) ) { return; } ?&gt; &lt;?php foreach ( $featured_posts as $post ) { setup_postdata( $post ); // Include the featured content template. get_template_part( 'content', 'featured-post' ); } wp_reset_postdata(); ?&gt; </code></pre> <p>@ content-featured-post.php </p> <pre><code>/** * The template for displaying featured posts on the front page */ &lt;?php // Output the featured image. if ( has_post_thumbnail() ) { the_post_thumbnail( 'gazette-featured-content-thumbnail' ); } ?&gt; </code></pre> <p>@ inc/jetpack.php line 22</p> <pre><code>add_theme_support( 'featured-content', array( 'filter' =&gt; 'gazette_get_featured_posts', 'description' =&gt; __( 'Omitted', 'gazette' ), 'max_posts' =&gt; 6, ) ); </code></pre> <p>@ js/featured-content.js line 24</p> <pre><code>var featuredContent, header, primary; featuredContent = $( '#featured-content' ); header = $( '#masthead' ); primary = $( '#primary' ); if ( ! featuredContent.length ) { return; } </code></pre> <p>@ js/header.js line 24</p> <pre><code>function headerStyle() { var featuredContent, featuredContentHeight; featuredContent = $( '#featured-content' ); featuredContentHeight = 0; if ( featuredContent.length ) { featuredContentHeight = featuredContent.outerHeight(); } if ( $( '.site-branding' ).outerWidth() === 0 ) { $( 'body' ).addClass( 'no-branding' ); } else { $( 'body' ).removeClass( 'no-branding' ); } </code></pre> <p>These are all the references I found to the featured posts grid layout. </p> <p>How can I modify to display the grid on the homepage setup as a static page?</p> <p><strong>Notes</strong></p> <p>I added this to the page.php and it does show up in the source for static, but simply does not display.</p> <pre><code>if ( is_page(35) ) { // Include the featured content template. get_template_part( 'featured-content' ); } </code></pre>
[ { "answer_id": 236428, "author": "user53340", "author_id": 98778, "author_profile": "https://wordpress.stackexchange.com/users/98778", "pm_score": 0, "selected": false, "text": "<p>If I understand your question which is to be honest a little vague, you should be able to change if <code>( is_home() )</code> to if <code>( is_front_page() )</code> This will display the 'featured-content' template part on a static front page (i.e a home page) instead of the blog page. In Wordpress <code>is_home</code> = blog home page and <code>is_front_page</code> = static front page. A little confusing, but if you think WordPress was originally made for blogging, it makes perfect sense. is_home explained <a href=\"https://developer.wordpress.org/reference/functions/is_home/\" rel=\"nofollow\">here</a> is_front_page explained <a href=\"https://codex.wordpress.org/Function_Reference/is_front_page\" rel=\"nofollow\">here</a></p>\n\n<p>EDIT: If you want the featured grid to display everywhere, you should be able to remove the if statement so it just reads <code>get_template_part( 'featured-content' );</code> that's assuming I have understood you correctly, and based on the limited code you have supplied. Hope this helps anyway.</p>\n" }, { "answer_id": 236518, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 1, "selected": false, "text": "<p>Bingo. I added the featured content template (as originally and later suggested by @user53340) to the page.php with a condition so the featured grid would only display on the page I designate.</p>\n\n<p><strong>Add to page.php</strong></p>\n\n<pre><code>if ( is_page(ID) ) {\n // Include the featured content template.\n get_template_part( 'featured-content' );\n}\n</code></pre>\n\n<p>After changing the front page display to my static page I noticed the featured content was being output in the source, however it was not showing up on the page itself.</p>\n\n<p>I realized the body classes determined if this would work or not. All I had to do is add <code>blog</code> to the body class for that page. The front page display sets the body class to <code>page</code> for static page and <code>blog</code> for posts page. </p>\n\n<p>Using the code below I appended the <code>blog</code> class to the body.</p>\n\n<pre><code>function add_blog_to_body_class($classes) {\n $classes[] = 'blog';\n return $classes;\n}\nadd_filter('body_class','add_blog_to_body_class');\n</code></pre>\n\n<p>I am able to set my static page &amp; have my featured posts grid :D</p>\n" } ]
2016/08/19
[ "https://wordpress.stackexchange.com/questions/236425", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44017/" ]
I'm using the Gazette theme which has a jet pack enabled featured posts grid when the front page is set to show latest posts. I would like to use a static page instead of recent posts, but keep the featured posts grid. --- **UPDATE** I was able to figure this out with a little moral support from the community Link to answer - [Display Featured Posts Grid on Static Page (Gazette)](https://wordpress.stackexchange.com/questions/236425/display-featured-posts-grid-on-static-page-gazette#answer-236518) --- Demo: <https://gazettedemo.wordpress.com/> Source: <https://public-api.wordpress.com/rest/v1/themes/download/gazette.zip> **Code parts associated with the featured posts** @ index.php ``` <?php if ( is_home() ) { // Include the featured content template. get_template_part( 'featured-content' ); } ?> <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php the_posts_navigation(); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> ``` @ functions.php line 197 ``` wp_enqueue_script( 'gazette-featured-content', get_template_directory_uri() . '/js/featured-content.js', array( 'jquery' ), '20150507', true ); ``` @ featured-content.php ``` $featured_posts = gazette_get_featured_posts(); if ( empty( $featured_posts ) ) { return; } ?> <?php foreach ( $featured_posts as $post ) { setup_postdata( $post ); // Include the featured content template. get_template_part( 'content', 'featured-post' ); } wp_reset_postdata(); ?> ``` @ content-featured-post.php ``` /** * The template for displaying featured posts on the front page */ <?php // Output the featured image. if ( has_post_thumbnail() ) { the_post_thumbnail( 'gazette-featured-content-thumbnail' ); } ?> ``` @ inc/jetpack.php line 22 ``` add_theme_support( 'featured-content', array( 'filter' => 'gazette_get_featured_posts', 'description' => __( 'Omitted', 'gazette' ), 'max_posts' => 6, ) ); ``` @ js/featured-content.js line 24 ``` var featuredContent, header, primary; featuredContent = $( '#featured-content' ); header = $( '#masthead' ); primary = $( '#primary' ); if ( ! featuredContent.length ) { return; } ``` @ js/header.js line 24 ``` function headerStyle() { var featuredContent, featuredContentHeight; featuredContent = $( '#featured-content' ); featuredContentHeight = 0; if ( featuredContent.length ) { featuredContentHeight = featuredContent.outerHeight(); } if ( $( '.site-branding' ).outerWidth() === 0 ) { $( 'body' ).addClass( 'no-branding' ); } else { $( 'body' ).removeClass( 'no-branding' ); } ``` These are all the references I found to the featured posts grid layout. How can I modify to display the grid on the homepage setup as a static page? **Notes** I added this to the page.php and it does show up in the source for static, but simply does not display. ``` if ( is_page(35) ) { // Include the featured content template. get_template_part( 'featured-content' ); } ```
Bingo. I added the featured content template (as originally and later suggested by @user53340) to the page.php with a condition so the featured grid would only display on the page I designate. **Add to page.php** ``` if ( is_page(ID) ) { // Include the featured content template. get_template_part( 'featured-content' ); } ``` After changing the front page display to my static page I noticed the featured content was being output in the source, however it was not showing up on the page itself. I realized the body classes determined if this would work or not. All I had to do is add `blog` to the body class for that page. The front page display sets the body class to `page` for static page and `blog` for posts page. Using the code below I appended the `blog` class to the body. ``` function add_blog_to_body_class($classes) { $classes[] = 'blog'; return $classes; } add_filter('body_class','add_blog_to_body_class'); ``` I am able to set my static page & have my featured posts grid :D
236,433
<p>I get the same results with these to lines, so what does <code>apply_filters</code> do?</p> <pre><code>Line 1 : echo $instance['title']; Line 2 : echo apply_filters('widget_title', $instance['title']); </code></pre>
[ { "answer_id": 236435, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>If you haven't written a filter using <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow\"><code>add_filter</code></a> obviously nothing will happen if you apply filters.</p>\n\n<p>Try this in your <code>functions.php</code> as an example:</p>\n\n<pre><code>add_filter( 'widget_title', 'wpse236433_invert_string' );\n\nfunction wpse236433_invert_string ($title) {\n return strrev($title);\n }\n</code></pre>\n" }, { "answer_id": 236437, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p><code>apply_filters()</code> allows you to <strong>modify</strong> a value using a hook. Let me explain-</p>\n\n<p><strong>Sample-1</strong>: Consider this code, it'll show <strong>Hello World!</strong>,</p>\n\n<pre><code>$str = 'Hello World!';\necho $str;\n</code></pre>\n\n<p><strong>Sample-2</strong>: The code bellow will show <strong>Hello World!</strong> too, but it will make the string <em>modifiable</em>-</p>\n\n<pre><code>$str = 'Hello World!';\necho apply_filters( 'modify_str', $str );\n</code></pre>\n\n<p><strong>Sample-3</strong>: If you use a filter hook (in a plugin or your functions.php file), the code I wrote in Sample-2 will show <strong>HELLO WORLD!</strong></p>\n\n<pre><code>function modify_hello_world( $str ){\n return strtoupper( $str );\n}\nadd_filter( 'modify_str', 'modify_hello_world' );\n</code></pre>\n\n<p>Hope it makes sense.</p>\n" }, { "answer_id": 236438, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Well, <code>apply_filter</code> creates a global filter hook which can be used dynamically all over the system. Which gives you the ability to filter the content of the <code>$instance['title']</code>, means you can over ride the content as well as can modify the content. Here is the example-</p>\n\n<pre><code>add_filter( 'widget_title', 'widget_title_to_uppercase', 10, 1);\nfunction widget_title_to_uppercase( $content ){\n $content = strtoupper($content);\n return $content;\n}\n</code></pre>\n\n<p>Now all the widget title will be uppercase. So with this filter hook you can filter the <code>widget_title</code> from any where the WordPress system. But with the <code>$instance['title']</code> it is not possible.</p>\n" } ]
2016/08/19
[ "https://wordpress.stackexchange.com/questions/236433", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101071/" ]
I get the same results with these to lines, so what does `apply_filters` do? ``` Line 1 : echo $instance['title']; Line 2 : echo apply_filters('widget_title', $instance['title']); ```
Well, `apply_filter` creates a global filter hook which can be used dynamically all over the system. Which gives you the ability to filter the content of the `$instance['title']`, means you can over ride the content as well as can modify the content. Here is the example- ``` add_filter( 'widget_title', 'widget_title_to_uppercase', 10, 1); function widget_title_to_uppercase( $content ){ $content = strtoupper($content); return $content; } ``` Now all the widget title will be uppercase. So with this filter hook you can filter the `widget_title` from any where the WordPress system. But with the `$instance['title']` it is not possible.
236,434
<p>When using <code>comments_template()</code>, all comments starts with <code>{ Username } says</code>. </p> <p>How can I remove that "<em>says</em>" part? In most solutions that I found, it suggests using CSS like:</p> <pre><code>.says { display: none; } </code></pre> <p>But the string isn't wrapped in a <code>div</code> called <code>says</code>.</p> <p>Any suggestions? Thanks!</p>
[ { "answer_id": 236445, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 2, "selected": false, "text": "<p>Hope this is gonna help. Please try this snippet. Put it in your themes <code>functions.php</code> or you could it load it thorough a plugin or any other way-</p>\n\n<pre><code>function the_dramatist_remove_says_from_comment( $translation, $text, $domain ) {\n //what text you want to have instead of 'says' in comments. For removing 'says' keep this blank\n $new_var = '';\n $translations = &amp;get_translations_for_domain( $domain );\n if ( $text == '&lt;cite class=\"fn\"&gt;%s&lt;/cite&gt; &lt;span class=\"says\"&gt;says:&lt;/span&gt;' ) {\n if($new_var) $new_var = ' '.$new_var; //compensate for the space character\n return $translations-&gt;translate( '&lt;cite class=\"fn\"&gt;%s&lt;/cite&gt;&lt;span class=\"says\"&gt;'.$new_var.':&lt;/span&gt;' );\n } else {\n return $translation; // standard text\n } \n}\nadd_filter('gettext', 'the_dramatist_remove_says_from_comment', 10, 4);\n</code></pre>\n" }, { "answer_id": 236455, "author": "Bryan Willis", "author_id": 38123, "author_profile": "https://wordpress.stackexchange.com/users/38123", "pm_score": 2, "selected": false, "text": "<p>The answer from @the_dramatist is probably the simplest if that's all you want to do, but you can remove it completely and customize everything else as well by creating your own comment template. </p>\n\n<p>As Ethan mentioned in the comment on your question, every theme is different, meaning that most themes have a comment template that is inserting this or are using the default template. If your theme has a custom comment template already, just edit that one otherwise it's using the default <a href=\"https://github.com/WordPress/WordPress/blob/5efc557eb8e7306f1aaae0a7abbb1fab12121626/wp-includes/class-walker-comment.php#L328\" rel=\"nofollow noreferrer\">comment function</a> which includes the comment author says text.</p>\n\n<p>If you have anything else besides that that you'd like to customize you're better off creating your own template or function for this. You can create a [custom callback or custom walker.</p>\n\n<p>Then you'd use wp_list_comments() to output your new comment template.</p>\n\n<blockquote>\n <p>So basically here's the process of doing this with templates:</p>\n</blockquote>\n\n<h2>1) Create your <a href=\"https://wordpress.stackexchange.com/questions/216351/comment-walker-vs-comment-callback\">callback or comment walker</a> in <code>functions.php</code> or similar</h2>\n\n<h2>2) Create a <code>comments.php</code> file and call your new function:</h2>\n\n<p><strong>Walker</strong></p>\n\n<pre><code>&lt;?php\nwp_list_comments( array(\n 'walker' =&gt; new Walker_Comment()\n) );\n</code></pre>\n\n<p><strong>Callback</strong></p>\n\n<pre><code> &lt;?php wp_list_comments('type=comment&amp;callback=format_comment'); ?&gt;\n</code></pre>\n\n<h2>3) Output your comment template on <code>single.php</code></h2>\n\n<pre><code>&lt;?php comments_template(); ?&gt;\n</code></pre>\n" }, { "answer_id": 285708, "author": "Ratan Mia", "author_id": 131385, "author_profile": "https://wordpress.stackexchange.com/users/131385", "pm_score": -1, "selected": false, "text": "<p>You need to add a simple function in your functions.php file that allows you to remove or modify or change “Says” word from WordPress comments. Please insert this code into your functions.php file.</p>\n\n<pre><code>add_filter( 'comment_author_says_text', 'rm_comment_author_says_text' );\nfunction rm_comment_author_says_text() {\n return 'Your Text';\n}\n</code></pre>\n\n<p>You will find full instructions here on my website - <a href=\"http://www.ratanmia.com/remove-modify-says-wordpress-comments/\" rel=\"nofollow noreferrer\">Remove or Modify “Says” From WordPress Comments</a></p>\n" }, { "answer_id": 358058, "author": "ttrusty", "author_id": 182306, "author_profile": "https://wordpress.stackexchange.com/users/182306", "pm_score": 1, "selected": false, "text": "<p>The class-walker-comment.php file is where you will find a span tag with the style '.says'. So as the original poster mentioned, adding .says{display: none;} to your themes css file will remove the word 'says:'. It worked for me in WP 5.3.2.</p>\n" } ]
2016/08/19
[ "https://wordpress.stackexchange.com/questions/236434", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54742/" ]
When using `comments_template()`, all comments starts with `{ Username } says`. How can I remove that "*says*" part? In most solutions that I found, it suggests using CSS like: ``` .says { display: none; } ``` But the string isn't wrapped in a `div` called `says`. Any suggestions? Thanks!
Hope this is gonna help. Please try this snippet. Put it in your themes `functions.php` or you could it load it thorough a plugin or any other way- ``` function the_dramatist_remove_says_from_comment( $translation, $text, $domain ) { //what text you want to have instead of 'says' in comments. For removing 'says' keep this blank $new_var = ''; $translations = &get_translations_for_domain( $domain ); if ( $text == '<cite class="fn">%s</cite> <span class="says">says:</span>' ) { if($new_var) $new_var = ' '.$new_var; //compensate for the space character return $translations->translate( '<cite class="fn">%s</cite><span class="says">'.$new_var.':</span>' ); } else { return $translation; // standard text } } add_filter('gettext', 'the_dramatist_remove_says_from_comment', 10, 4); ```
236,457
<p>i'm having a trouble with Wordpress, with the function <code>update_user_meta()</code></p> <p>I'm trying to update or add a new custom meta value for the user, who already have the custom meta working on the edit profile. But when i do the function <code>update_user_meta()</code> outside the <code>edit-profile.php</code>, just didn't work for me.</p> <p>I have a page like a page of contact where the form will edit the custom metadata of the profile, in the front side of the wordpress like a normal page of wordpress, but when he submit the form, he just don't update, here is my code:</p> <p>when the user submit:</p> <pre><code>function update_termini() { $user = wp_get_current_user(); $userData = array(); $userData['checkbox'] = intval( $_POST['custom_user_fields_checkbox'] ); update_user_meta( $user, 'custom_user_fields', $userData ); } add_action('edit_user_profile', 'update_termini'); </code></pre>
[ { "answer_id": 236458, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": 1, "selected": true, "text": "<p><code>wp_get_current_user()</code> returns an object. <code>update_user_meta( $user_id, $meta_key, $meta_value, $prev_value</code> ) accepts <code>user_id</code> as first parameter. Use the following code to get user ID from <code>wp_get_current_user()</code></p>\n\n<pre><code>update_user_meta( $user-&gt;ID, 'custom_user_fields', $userData );\n</code></pre>\n" }, { "answer_id": 268635, "author": "nyedidikeke", "author_id": 105480, "author_profile": "https://wordpress.stackexchange.com/users/105480", "pm_score": 1, "selected": false, "text": "<p>This is the right way to update user meta so you don't mess up your data; the snippet is commented so as to provide more details:</p>\n\n<pre><code>function update_termini( $user_id ) {\n// print_r( $user_id );\n// exit;\n// $user_id holds the user ID of the actual user's profile page subjected to the edit.\n// That is the right way to do it.\n\n\n// The comment block right below this very block is an ineffective way as it will only work\n// for a current user editing his/her own profile page and why it is not the best way out;\n\n// Using wp_get_current_user() to derive at a user ID as in: $user = wp_get_current_user();\n// then, $user-&gt;ID; will enable you get the user ID of the CURRENT USER and that is going\n// to AFFECT YOUR DATA NEGATIVELY when an administrator for instance edits the profile of\n// a user; what will happen then is that the data of the custom field will actually update\n// the records of the administrator rather than that of the intended user whos profile in\n// being edited by the administrator.\n\n// You can then perform any checks if needed,\n if ( current_user_can( 'edit_user' ) ) {\n// print_r( $_POST );\n// exit;\n\n// And proceed to update the user meta of the actual user's profile page subjected to the edit;\n// it may or may not be the current user.\n// This way, you are sure to update the right field with right information.\n\n// For the purpose of this update, it is assumed the name of our newly added custom field\n// is custom_user_fields_checkbox.\n update_user_meta( $user_id, 'custom_user_fields_checkbox', $_POST['custom_user_fields_checkbox'] );\n }\n}\nadd_action( 'edit_user_profile', 'update_termini' );\n</code></pre>\n" } ]
2016/08/19
[ "https://wordpress.stackexchange.com/questions/236457", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101301/" ]
i'm having a trouble with Wordpress, with the function `update_user_meta()` I'm trying to update or add a new custom meta value for the user, who already have the custom meta working on the edit profile. But when i do the function `update_user_meta()` outside the `edit-profile.php`, just didn't work for me. I have a page like a page of contact where the form will edit the custom metadata of the profile, in the front side of the wordpress like a normal page of wordpress, but when he submit the form, he just don't update, here is my code: when the user submit: ``` function update_termini() { $user = wp_get_current_user(); $userData = array(); $userData['checkbox'] = intval( $_POST['custom_user_fields_checkbox'] ); update_user_meta( $user, 'custom_user_fields', $userData ); } add_action('edit_user_profile', 'update_termini'); ```
`wp_get_current_user()` returns an object. `update_user_meta( $user_id, $meta_key, $meta_value, $prev_value` ) accepts `user_id` as first parameter. Use the following code to get user ID from `wp_get_current_user()` ``` update_user_meta( $user->ID, 'custom_user_fields', $userData ); ```
236,465
<p>I have been searching for hours trying to find a way to test the update process for my plugin before tagging a new release in the repo. I have a function that is called using <code>add_action( 'upgrader_process_complete', 'my_plugin_upgrade_function', 10, 2);</code> and I can't figure out how to test this prior to release.</p> <p>Any help would be awesome!</p>
[ { "answer_id": 236458, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": 1, "selected": true, "text": "<p><code>wp_get_current_user()</code> returns an object. <code>update_user_meta( $user_id, $meta_key, $meta_value, $prev_value</code> ) accepts <code>user_id</code> as first parameter. Use the following code to get user ID from <code>wp_get_current_user()</code></p>\n\n<pre><code>update_user_meta( $user-&gt;ID, 'custom_user_fields', $userData );\n</code></pre>\n" }, { "answer_id": 268635, "author": "nyedidikeke", "author_id": 105480, "author_profile": "https://wordpress.stackexchange.com/users/105480", "pm_score": 1, "selected": false, "text": "<p>This is the right way to update user meta so you don't mess up your data; the snippet is commented so as to provide more details:</p>\n\n<pre><code>function update_termini( $user_id ) {\n// print_r( $user_id );\n// exit;\n// $user_id holds the user ID of the actual user's profile page subjected to the edit.\n// That is the right way to do it.\n\n\n// The comment block right below this very block is an ineffective way as it will only work\n// for a current user editing his/her own profile page and why it is not the best way out;\n\n// Using wp_get_current_user() to derive at a user ID as in: $user = wp_get_current_user();\n// then, $user-&gt;ID; will enable you get the user ID of the CURRENT USER and that is going\n// to AFFECT YOUR DATA NEGATIVELY when an administrator for instance edits the profile of\n// a user; what will happen then is that the data of the custom field will actually update\n// the records of the administrator rather than that of the intended user whos profile in\n// being edited by the administrator.\n\n// You can then perform any checks if needed,\n if ( current_user_can( 'edit_user' ) ) {\n// print_r( $_POST );\n// exit;\n\n// And proceed to update the user meta of the actual user's profile page subjected to the edit;\n// it may or may not be the current user.\n// This way, you are sure to update the right field with right information.\n\n// For the purpose of this update, it is assumed the name of our newly added custom field\n// is custom_user_fields_checkbox.\n update_user_meta( $user_id, 'custom_user_fields_checkbox', $_POST['custom_user_fields_checkbox'] );\n }\n}\nadd_action( 'edit_user_profile', 'update_termini' );\n</code></pre>\n" } ]
2016/08/19
[ "https://wordpress.stackexchange.com/questions/236465", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47422/" ]
I have been searching for hours trying to find a way to test the update process for my plugin before tagging a new release in the repo. I have a function that is called using `add_action( 'upgrader_process_complete', 'my_plugin_upgrade_function', 10, 2);` and I can't figure out how to test this prior to release. Any help would be awesome!
`wp_get_current_user()` returns an object. `update_user_meta( $user_id, $meta_key, $meta_value, $prev_value` ) accepts `user_id` as first parameter. Use the following code to get user ID from `wp_get_current_user()` ``` update_user_meta( $user->ID, 'custom_user_fields', $userData ); ```
236,514
<h3>Objective</h3> <p>As all plugin developer, I want to delete all options that begin with the same prefix.</p> <h3>Backstory</h3> <p>I've developed a plugin that stores data in the options. When the user uninstalls the plugin, the <code>uninstall.php</code> in the plugin executes the following code:</p> <pre><code>if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) { exit; } delete_option( 'myplugin_some_opt_1' ); delete_option( 'myplugin_some_opt_2' ); delete_option( 'myplugin_some_opt_3' ); delete_option( 'myplugin_some_opt_4' ); </code></pre> <p>Since all of the options start with <code>myplugin_</code>, I want to implement a wildcard. Logicall, I assume that it would look something like this:</p> <pre><code>if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) { exit; } delete_option( 'myplugin_*' ); </code></pre>
[ { "answer_id": 236515, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 3, "selected": false, "text": "<p>Replace \"myplugin_\" with your prefix:</p>\n\n<pre><code>global $wpdb;\n\n$plugin_options = $wpdb-&gt;get_results( \"SELECT option_name FROM $wpdb-&gt;options WHERE option_name LIKE 'myplugin_%'\" );\n\nforeach( $plugin_options as $option ) {\n delete_option( $option-&gt;option_name );\n}\n</code></pre>\n" }, { "answer_id": 242906, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 3, "selected": true, "text": "<p>I've found out another alternative by using the <a href=\"https://codex.wordpress.org/Function_Reference/wp_load_alloptions\" rel=\"nofollow\"><code>wp_load_alloptions()</code></a> function to get all of the available options, then <code>delete_option()</code> for every option that has the <code>myplugin_</code> prefix:</p>\n\n<pre><code>foreach ( wp_load_alloptions() as $option =&gt; $value ) {\n if ( strpos( $option, 'myplugin_' ) === 0 ) {\n delete_option( $option );\n }\n}\n</code></pre>\n" } ]
2016/08/20
[ "https://wordpress.stackexchange.com/questions/236514", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98212/" ]
### Objective As all plugin developer, I want to delete all options that begin with the same prefix. ### Backstory I've developed a plugin that stores data in the options. When the user uninstalls the plugin, the `uninstall.php` in the plugin executes the following code: ``` if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) { exit; } delete_option( 'myplugin_some_opt_1' ); delete_option( 'myplugin_some_opt_2' ); delete_option( 'myplugin_some_opt_3' ); delete_option( 'myplugin_some_opt_4' ); ``` Since all of the options start with `myplugin_`, I want to implement a wildcard. Logicall, I assume that it would look something like this: ``` if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) { exit; } delete_option( 'myplugin_*' ); ```
I've found out another alternative by using the [`wp_load_alloptions()`](https://codex.wordpress.org/Function_Reference/wp_load_alloptions) function to get all of the available options, then `delete_option()` for every option that has the `myplugin_` prefix: ``` foreach ( wp_load_alloptions() as $option => $value ) { if ( strpos( $option, 'myplugin_' ) === 0 ) { delete_option( $option ); } } ```
236,530
<p>I am using <code>&lt;!--nextpage--&gt;</code> to break my posts on multiple pages. This is working fine. But I want to further change the page numbering. </p> <p>If you visit <a href="http://mycitymychoice.com/fruit-9-letters/" rel="nofollow">this post</a> you will note the page breaks. I want to change the first page to "Question" while the second page to "Answer" </p> <p>I went through the codex on <a href="https://codex.wordpress.org/Styling_Page-Links#Changing_the_Look_of_Page-Links" rel="nofollow">this page</a> any tried following code in my theme <code>functions.php</code> but it broke my site.</p> <pre><code>&lt;?php wp_link_pages('before=To read this story, &amp;after=. &amp;next_or_number=next &amp;previouspagelink=you can go back to the previous page &amp;nextpagelink= or you can read on to the next page'); ?&gt; </code></pre> <p>Could you please help to get the right code. I do not want to keep more than two pages, if this helps. And if someone can help me to get the shortcode for it will be cherry on top of ice cream :)</p>
[ { "answer_id": 236531, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>The example in the codex has faulty quotation marks. The developer area has more detail on how to use <a href=\"https://developer.wordpress.org/reference/functions/wp_link_pages/\" rel=\"nofollow\"><code>wp_link_pages</code></a>. Example usage:</p>\n\n<pre><code>&lt;?php\n$args = array(\n 'before' =&gt; '&lt;p&gt;' . __( 'To read this story' ),\n 'after' =&gt; '&lt;/p&gt;',\n 'link_before' =&gt; '',\n 'link_after' =&gt; '',\n 'next_or_number' =&gt; 'next',\n 'separator' =&gt; ' ',\n 'nextpagelink' =&gt; __( 'you can go back to the previous page' ),\n 'previouspagelink' =&gt; __( ' or you can read on to the next page' ),\n 'pagelink' =&gt; '%',\n 'echo' =&gt; 1\n );\nwp_link_pages ($args);\n?&gt;\n</code></pre>\n" }, { "answer_id": 236532, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 2, "selected": false, "text": "<p>Put this function in you <code>functions.php</code> -</p>\n\n<pre><code>function the_dramatist_wp_link_pages( $args = '' ) {\n global $page, $numpages, $multipage, $more;\n\n $defaults = array(\n 'before' =&gt; '&lt;p&gt;' . __( 'Pages:' ),\n 'after' =&gt; '&lt;/p&gt;',\n 'link_before' =&gt; '',\n 'link_after' =&gt; '',\n 'next_or_number' =&gt; 'number',\n 'separator' =&gt; ' ',\n 'nextpagelink' =&gt; __( 'Next page' ),\n 'previouspagelink' =&gt; __( 'Previous page' ),\n 'pagelink' =&gt; '%',\n 'echo' =&gt; 1\n );\n\n $params = wp_parse_args( $args, $defaults );\n\n /**\n * Filters the arguments used in retrieving page links for paginated posts.\n *\n * @since 3.0.0\n *\n * @param array $params An array of arguments for page links for paginated posts.\n */\n $r = apply_filters( 'wp_link_pages_args', $params );\n\n $output = '';\n if ( $multipage ) {\n if ( 'number' == $r['next_or_number'] ) {\n $output .= $r['before'];\n for ( $i = 1; $i &lt;= $numpages; $i++ ) {\n if ( $i % 2 == 0) {\n $link = $r['link_before'] . str_replace( '%', 'Answer', $r['pagelink'] ) . $r['link_after'];\n } else {\n $link = $r['link_before'] . str_replace( '%', 'Question', $r['pagelink'] ) . $r['link_after'];\n }\n if ( $i != $page || ! $more &amp;&amp; 1 == $page ) {\n $link = _wp_link_page( $i ) . $link . '&lt;/a&gt;';\n }\n /**\n * Filters the HTML output of individual page number links.\n *\n * @since 3.6.0\n *\n * @param string $link The page number HTML output.\n * @param int $i Page number for paginated posts' page links.\n */\n $link = apply_filters( 'wp_link_pages_link', $link, $i );\n\n // Use the custom links separator beginning with the second link.\n $output .= ( 1 === $i ) ? ' ' : $r['separator'];\n $output .= $link;\n }\n $output .= $r['after'];\n } elseif ( $more ) {\n $output .= $r['before'];\n $prev = $page - 1;\n if ( $prev &gt; 0 ) {\n $link = _wp_link_page( $prev ) . $r['link_before'] . $r['previouspagelink'] . $r['link_after'] . '&lt;/a&gt;';\n\n /** This filter is documented in wp-includes/post-template.php */\n $output .= apply_filters( 'wp_link_pages_link', $link, $prev );\n }\n $next = $page + 1;\n if ( $next &lt;= $numpages ) {\n if ( $prev ) {\n $output .= $r['separator'];\n }\n $link = _wp_link_page( $next ) . $r['link_before'] . $r['nextpagelink'] . $r['link_after'] . '&lt;/a&gt;';\n\n /** This filter is documented in wp-includes/post-template.php */\n $output .= apply_filters( 'wp_link_pages_link', $link, $next );\n }\n $output .= $r['after'];\n }\n }\n\n /**\n * Filters the HTML output of page links for paginated posts.\n *\n * @since 3.6.0\n *\n * @param string $output HTML output of paginated posts' page links.\n * @param array $args An array of arguments.\n */\n $html = apply_filters( 'wp_link_pages', $output, $args );\n\n if ( $r['echo'] ) {\n echo $html;\n }\n return $html;\n}\n</code></pre>\n\n<p>And then go to your theme directory. Search and replace the <code>wp_link_pages</code> function names with <code>the_dramatist_wp_link_pages</code>. And it'll work as you wanted. Usually the <code>wp_link_pages</code> exists in <code>content-{template-name}.php</code>. So if you have any of those files in your theme please look at theme first. Here I've added a screenshot-<a href=\"https://i.stack.imgur.com/Dhkjo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Dhkjo.png\" alt=\"enter image description here\"></a></p>\n\n<p>And after that you do your styling. Have fun.</p>\n\n<p><strong>The function works on odd-even basis. It considers the odd part as 'Question' and the even part as 'Answer'</strong></p>\n" } ]
2016/08/20
[ "https://wordpress.stackexchange.com/questions/236530", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101334/" ]
I am using `<!--nextpage-->` to break my posts on multiple pages. This is working fine. But I want to further change the page numbering. If you visit [this post](http://mycitymychoice.com/fruit-9-letters/) you will note the page breaks. I want to change the first page to "Question" while the second page to "Answer" I went through the codex on [this page](https://codex.wordpress.org/Styling_Page-Links#Changing_the_Look_of_Page-Links) any tried following code in my theme `functions.php` but it broke my site. ``` <?php wp_link_pages('before=To read this story, &after=. &next_or_number=next &previouspagelink=you can go back to the previous page &nextpagelink= or you can read on to the next page'); ?> ``` Could you please help to get the right code. I do not want to keep more than two pages, if this helps. And if someone can help me to get the shortcode for it will be cherry on top of ice cream :)
Put this function in you `functions.php` - ``` function the_dramatist_wp_link_pages( $args = '' ) { global $page, $numpages, $multipage, $more; $defaults = array( 'before' => '<p>' . __( 'Pages:' ), 'after' => '</p>', 'link_before' => '', 'link_after' => '', 'next_or_number' => 'number', 'separator' => ' ', 'nextpagelink' => __( 'Next page' ), 'previouspagelink' => __( 'Previous page' ), 'pagelink' => '%', 'echo' => 1 ); $params = wp_parse_args( $args, $defaults ); /** * Filters the arguments used in retrieving page links for paginated posts. * * @since 3.0.0 * * @param array $params An array of arguments for page links for paginated posts. */ $r = apply_filters( 'wp_link_pages_args', $params ); $output = ''; if ( $multipage ) { if ( 'number' == $r['next_or_number'] ) { $output .= $r['before']; for ( $i = 1; $i <= $numpages; $i++ ) { if ( $i % 2 == 0) { $link = $r['link_before'] . str_replace( '%', 'Answer', $r['pagelink'] ) . $r['link_after']; } else { $link = $r['link_before'] . str_replace( '%', 'Question', $r['pagelink'] ) . $r['link_after']; } if ( $i != $page || ! $more && 1 == $page ) { $link = _wp_link_page( $i ) . $link . '</a>'; } /** * Filters the HTML output of individual page number links. * * @since 3.6.0 * * @param string $link The page number HTML output. * @param int $i Page number for paginated posts' page links. */ $link = apply_filters( 'wp_link_pages_link', $link, $i ); // Use the custom links separator beginning with the second link. $output .= ( 1 === $i ) ? ' ' : $r['separator']; $output .= $link; } $output .= $r['after']; } elseif ( $more ) { $output .= $r['before']; $prev = $page - 1; if ( $prev > 0 ) { $link = _wp_link_page( $prev ) . $r['link_before'] . $r['previouspagelink'] . $r['link_after'] . '</a>'; /** This filter is documented in wp-includes/post-template.php */ $output .= apply_filters( 'wp_link_pages_link', $link, $prev ); } $next = $page + 1; if ( $next <= $numpages ) { if ( $prev ) { $output .= $r['separator']; } $link = _wp_link_page( $next ) . $r['link_before'] . $r['nextpagelink'] . $r['link_after'] . '</a>'; /** This filter is documented in wp-includes/post-template.php */ $output .= apply_filters( 'wp_link_pages_link', $link, $next ); } $output .= $r['after']; } } /** * Filters the HTML output of page links for paginated posts. * * @since 3.6.0 * * @param string $output HTML output of paginated posts' page links. * @param array $args An array of arguments. */ $html = apply_filters( 'wp_link_pages', $output, $args ); if ( $r['echo'] ) { echo $html; } return $html; } ``` And then go to your theme directory. Search and replace the `wp_link_pages` function names with `the_dramatist_wp_link_pages`. And it'll work as you wanted. Usually the `wp_link_pages` exists in `content-{template-name}.php`. So if you have any of those files in your theme please look at theme first. Here I've added a screenshot-[![enter image description here](https://i.stack.imgur.com/Dhkjo.png)](https://i.stack.imgur.com/Dhkjo.png) And after that you do your styling. Have fun. **The function works on odd-even basis. It considers the odd part as 'Question' and the even part as 'Answer'**
236,533
<p>I am trying to write update query where id is not equal to 5</p> <p>i want output like this but not working.</p> <pre><code>UPDATE `wp_messg` SET `is_read` = 1 WHERE `job_id` = 1 AND `biv_id`!=5 $id=5; $wpdb-&gt;update( 'wp_messg', array( 'is_read' =&gt; 1, // string ), array( 'job_id' =&gt; $id,'biv_id' =&gt; $id ), array( '%d', // value1 ), array( '%d' ) ); } </code></pre>
[ { "answer_id": 236554, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>It is not possible to use <code>NOT EQUAL</code> in <code>$wpdb-&gt;update()</code>. Here look the source code of the <code>update</code> method-</p>\n\n<pre><code>public function update( $table, $data, $where, $format = null, $where_format = null ) {\n if ( ! is_array( $data ) || ! is_array( $where ) ) {\n return false;\n }\n\n $data = $this-&gt;process_fields( $table, $data, $format );\n if ( false === $data ) {\n return false;\n }\n $where = $this-&gt;process_fields( $table, $where, $where_format );\n if ( false === $where ) {\n return false;\n }\n\n $fields = $conditions = $values = array();\n foreach ( $data as $field =&gt; $value ) {\n if ( is_null( $value['value'] ) ) {\n $fields[] = \"`$field` = NULL\";\n continue;\n }\n\n $fields[] = \"`$field` = \" . $value['format'];\n $values[] = $value['value'];\n }\n foreach ( $where as $field =&gt; $value ) {\n if ( is_null( $value['value'] ) ) {\n $conditions[] = \"`$field` IS NULL\";\n continue;\n }\n\n $conditions[] = \"`$field` = \" . $value['format'];\n $values[] = $value['value'];\n }\n\n $fields = implode( ', ', $fields );\n $conditions = implode( ' AND ', $conditions );\n\n $sql = \"UPDATE `$table` SET $fields WHERE $conditions\";\n\n $this-&gt;check_current_query = false;\n return $this-&gt;query( $this-&gt;prepare( $sql, $values ) );\n}\n</code></pre>\n\n<p><code>NOT EQUAL</code> has not been handled. So it is not possible to use the <code>NOT EQUAL</code> on <code>$wpdb-&gt;update()</code> method.</p>\n" }, { "answer_id": 236555, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>This is not something <code>$wpdb-&gt;update()</code> method implements.</p>\n\n<p>If you have custom SQL query that cannot be expressed in API you can run it as is with generic <code>$wpdb-&gt;query()</code>.</p>\n" } ]
2016/08/20
[ "https://wordpress.stackexchange.com/questions/236533", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54905/" ]
I am trying to write update query where id is not equal to 5 i want output like this but not working. ``` UPDATE `wp_messg` SET `is_read` = 1 WHERE `job_id` = 1 AND `biv_id`!=5 $id=5; $wpdb->update( 'wp_messg', array( 'is_read' => 1, // string ), array( 'job_id' => $id,'biv_id' => $id ), array( '%d', // value1 ), array( '%d' ) ); } ```
This is not something `$wpdb->update()` method implements. If you have custom SQL query that cannot be expressed in API you can run it as is with generic `$wpdb->query()`.
236,534
<p>I'm currently building a pretty straightforward plugin, but it relies quite extensively on AJAX requests. I'm using the standard <code>admin-ajax</code> endpoint for the requests, but I find that it seems to be massively inconsistent, sometimes the request (for the same data) will take a few hundred milliseconds and then sometimes take a couple of seconds.</p> <p>I am aware that there is <code>heartbeat</code> issue that can be a problem when using <code>admin-ajax</code> which when modified can help improve request speeds when using the endpoint.</p> <p>I suppose I could point the requests directly to a PHP file and use that as an endpoint, but is there anyway I can create an endpoint that uses Wordpress's routing? </p> <p><strong>So my question is; Does Wordpress have support for custom ajax endpoints / url parameters that will fire function calls etc..?</strong></p> <p>I'm also aware that I could use the REST API route callbacks, but I'd like this plugin to be dependency free where possible so it will be supported on version of Wordpress that don't include the REST API.</p> <p>Thanks for any help!</p>
[ { "answer_id": 236552, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>The main problem with native ajax endpoint is that it has to <em>load whole WordPress core</em>. Unless something is causing those slowdowns in <em>your</em> code it's likely something else bogs down that process.</p>\n\n<p>Going through a different endpoint will no help you in this case since you still <em>need to load core</em> and back to square one.</p>\n\n<p>Couple of seconds doesn't sound normal and I would recommend to first figure out <em>where</em> does that delay comes from.</p>\n\n<p>The only practical technique for fast ajax endpoint in WP is custom core load with <code>SHORTINIT</code>, but that is limited to private projects since it cannot be practically coded generic enough to distribute in public solution (though some do and that crap breaks on any install slightly less than dead default).</p>\n" }, { "answer_id": 236630, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p>Use <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\"><code>add_rewrite_rule</code></a> to make your own API and handle the endpoints yourself.</p>\n\n<p>Tools like <a href=\"https://wordpress.org/plugins/monkeyman-rewrite-analyzer/\" rel=\"nofollow\">Monkeyman Rewrite Analyzer</a> will help you understand how your rewrite rules end up working with existing rules.</p>\n\n<hr>\n\n<pre><code>if ( ! class_exists( 'WPSEAPIEndpoint' ) ):\n\n class WPSEAPIEndpoint {\n\n // WordPress hooks\n public function __construct() {\n add_filter( 'query_vars', array ( $this, 'add_query_vars' ), 0 );\n add_action( 'parse_request', array ( $this, 'sniff_requests' ), 0 );\n add_action( 'init', array ( $this, 'add_endpoint' ), 0 );\n }\n\n // Add public query vars\n public function add_query_vars( $vars ) {\n $vars[] = '___my-api';\n $vars[] = 'action';\n return $vars;\n }\n\n // Add API Endpoint\n public function add_endpoint() {\n add_rewrite_rule( '^my-api/v1/([^/]*)/?', 'index.php?___my-api=1&amp;action=$matches[1]', 'top' );\n flush_rewrite_rules( false ); //// &lt;---------- REMOVE THIS WHEN DONE TESTING\n }\n\n // Sniff Requests\n public function sniff_requests( $wp_query ) {\n global $wp;\n\n if ( isset( $wp-&gt;query_vars[ '___my-api' ], $wp-&gt;query_vars[ 'action' ] ) ) {\n wp_die( \"Action requested: \" . $wp-&gt;query_vars[ 'action' ] );\n }\n }\n }\n\n $wptept = new WPSEAPIEndpoint();\n\nendif; // WPSEAPIEndpoint\n</code></pre>\n\n<p>There are 3 main parts to this; add your custom query vars, add your custom endpoint, and handle the request when you see your custom query vars.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow\"><code>flush_rewrite_rules()</code></a> really only needs to occur once after you've added the new rules but it makes testing much faster to put it inline like I've shown. Just remove it when you're done. Or remove it early and flush the rewrite rules by saving your permalinks in the settings menu.</p>\n" } ]
2016/08/20
[ "https://wordpress.stackexchange.com/questions/236534", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85542/" ]
I'm currently building a pretty straightforward plugin, but it relies quite extensively on AJAX requests. I'm using the standard `admin-ajax` endpoint for the requests, but I find that it seems to be massively inconsistent, sometimes the request (for the same data) will take a few hundred milliseconds and then sometimes take a couple of seconds. I am aware that there is `heartbeat` issue that can be a problem when using `admin-ajax` which when modified can help improve request speeds when using the endpoint. I suppose I could point the requests directly to a PHP file and use that as an endpoint, but is there anyway I can create an endpoint that uses Wordpress's routing? **So my question is; Does Wordpress have support for custom ajax endpoints / url parameters that will fire function calls etc..?** I'm also aware that I could use the REST API route callbacks, but I'd like this plugin to be dependency free where possible so it will be supported on version of Wordpress that don't include the REST API. Thanks for any help!
Use [`add_rewrite_rule`](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule) to make your own API and handle the endpoints yourself. Tools like [Monkeyman Rewrite Analyzer](https://wordpress.org/plugins/monkeyman-rewrite-analyzer/) will help you understand how your rewrite rules end up working with existing rules. --- ``` if ( ! class_exists( 'WPSEAPIEndpoint' ) ): class WPSEAPIEndpoint { // WordPress hooks public function __construct() { add_filter( 'query_vars', array ( $this, 'add_query_vars' ), 0 ); add_action( 'parse_request', array ( $this, 'sniff_requests' ), 0 ); add_action( 'init', array ( $this, 'add_endpoint' ), 0 ); } // Add public query vars public function add_query_vars( $vars ) { $vars[] = '___my-api'; $vars[] = 'action'; return $vars; } // Add API Endpoint public function add_endpoint() { add_rewrite_rule( '^my-api/v1/([^/]*)/?', 'index.php?___my-api=1&action=$matches[1]', 'top' ); flush_rewrite_rules( false ); //// <---------- REMOVE THIS WHEN DONE TESTING } // Sniff Requests public function sniff_requests( $wp_query ) { global $wp; if ( isset( $wp->query_vars[ '___my-api' ], $wp->query_vars[ 'action' ] ) ) { wp_die( "Action requested: " . $wp->query_vars[ 'action' ] ); } } } $wptept = new WPSEAPIEndpoint(); endif; // WPSEAPIEndpoint ``` There are 3 main parts to this; add your custom query vars, add your custom endpoint, and handle the request when you see your custom query vars. [`flush_rewrite_rules()`](https://codex.wordpress.org/Function_Reference/flush_rewrite_rules) really only needs to occur once after you've added the new rules but it makes testing much faster to put it inline like I've shown. Just remove it when you're done. Or remove it early and flush the rewrite rules by saving your permalinks in the settings menu.
236,539
<p>I need help with WP custom taxonomy and custom post types. I never find a working solution so far. Please accept my apologies if this has a simple solution. I tried my best to find solution everywhere first.</p> <p>Explanation of issue -</p> <ol> <li>I have one taxonomy called <strong>"department"</strong>.</li> <li>I have 3 CPT called <strong>"course", "faculty", "library"</strong>.</li> </ol> <p>All 3 CPT will use same taxonomy <strong>"department"</strong>. I have all setup successfully and assigned the "department" taxonomy to all 3 CPT.</p> <p>Now I am trying to show posts (all 3 CPT posts) by "department" taxonomy <em>terms</em> (for instance, I have terms "x","y","z" for the taxonomy "department"). I have a template file called <strong>"taxonomy-department.php"</strong>, which has simple loop -</p> <pre><code>&lt;?php if (have_posts()) : ?&gt; &lt;ul&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;li&gt; &lt;?php the_title(); ?&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; &lt;?php else : ?&gt; &lt;p&gt;&lt;?php _e('Sorry, no posts matched your criteria.'); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre> <p>The above loop inside the taxonomy template, is not working and showing no posts. Just going to else statement. I am not sure how to achieve this.</p> <p>If I fetch posts successfully (with your help), is it also possible to filter posts by CPT? (in the taxonomy template file)</p> <p>Any help is much appreciated.</p>
[ { "answer_id": 236546, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>Please try this-</p>\n\n<pre><code>$post_type = array('course', 'faculty', 'library');\n$terms = array( 'x-tax-slug', 'y-tax-slug', 'z-tax-slug' );\n$args = array(\n 'post_type' =&gt; $post_type,\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'department',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $terms,\n ),\n ),\n);\n$query = new WP_Query( $args );\n\n&lt;?php if (have_posts()) : ?&gt;\n\n &lt;ul&gt; \n\n &lt;?php while ($query-&gt;have_posts()) : $query-&gt;the_post(); ?&gt; \n &lt;li&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/li&gt;\n &lt;?php endwhile; ?&gt;\n\n &lt;/ul&gt;\n &lt;?php else : ?&gt;\n\n &lt;p&gt;&lt;?php _e('Sorry, no posts matched your criteria.'); ?&gt;&lt;/p&gt;\n\n&lt;?php endif; ?&gt;\n\n&lt;?php wp_reset_postdata(); // reset the query ?&gt;\n</code></pre>\n\n<p>So here we are running a custom query based on your <code>department</code> taxonomy and there custom post type. And at last we are resetting the query.</p>\n" }, { "answer_id": 236549, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>WP defaults to showing normal native Posts in archives. It won't automagically pick up <em>which</em> post types you want in your archive.</p>\n\n<p>You will have to adjust main query for it to explain that to it, with something like:</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( WP_Query $query ) {\n\n if ( $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_tax( 'department' ) ) {\n $query-&gt;set( 'post_type', [ 'course', 'faculty', 'library' ] );\n }\n} );\n</code></pre>\n" }, { "answer_id": 236598, "author": "Amit", "author_id": 65847, "author_profile": "https://wordpress.stackexchange.com/users/65847", "pm_score": 1, "selected": false, "text": "<p>I like to Thank @Rarst for his contribution to the answer. Here is the final piece of code -</p>\n\n<pre><code>add_action( 'pre_get_posts', 'my_tax_query' );\n\nfunction my_tax_query($query){\n\n if ( !is_admin() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_tax( 'department' ) ) {\n $query-&gt;set( 'post_type', array( 'course', 'faculty', 'library' ) );\n }\n};\n</code></pre>\n\n<p>Place the code inside of the <code>functions.php</code> file.\nThis will grab all posts (for the term page) from for all post types that you have.</p>\n\n<p>For example - if your term page is <code>http://domain-name.com/taxonomy/term1/</code>\nYou will get all posts for \"<code>term1</code>\" for all post types. </p>\n\n<p>Now, can we filter posts by \"post types\" ? Is there a way to do that?\nThanks!</p>\n" } ]
2016/08/20
[ "https://wordpress.stackexchange.com/questions/236539", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65847/" ]
I need help with WP custom taxonomy and custom post types. I never find a working solution so far. Please accept my apologies if this has a simple solution. I tried my best to find solution everywhere first. Explanation of issue - 1. I have one taxonomy called **"department"**. 2. I have 3 CPT called **"course", "faculty", "library"**. All 3 CPT will use same taxonomy **"department"**. I have all setup successfully and assigned the "department" taxonomy to all 3 CPT. Now I am trying to show posts (all 3 CPT posts) by "department" taxonomy *terms* (for instance, I have terms "x","y","z" for the taxonomy "department"). I have a template file called **"taxonomy-department.php"**, which has simple loop - ``` <?php if (have_posts()) : ?> <ul> <?php while (have_posts()) : the_post(); ?> <li> <?php the_title(); ?> </li> <?php endwhile; ?> </ul> <?php else : ?> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?> ``` The above loop inside the taxonomy template, is not working and showing no posts. Just going to else statement. I am not sure how to achieve this. If I fetch posts successfully (with your help), is it also possible to filter posts by CPT? (in the taxonomy template file) Any help is much appreciated.
WP defaults to showing normal native Posts in archives. It won't automagically pick up *which* post types you want in your archive. You will have to adjust main query for it to explain that to it, with something like: ``` add_action( 'pre_get_posts', function ( WP_Query $query ) { if ( $query->is_main_query() && $query->is_tax( 'department' ) ) { $query->set( 'post_type', [ 'course', 'faculty', 'library' ] ); } } ); ```
236,576
<p>I have a simple two columns website (one sidebar + one maincoulmn). In the sidebar area I use this code to show some post thumbnails:</p> <pre><code>&lt;?php the_post_thumbnail('custom-size-small' ,array('class' =&gt; 'image', 'title' =&gt; strip_tags(get_the_title()), 'itemprop' =&gt; 'image')); ?&gt; </code></pre> <p>My website is responsive and on smaller devices the sidebar drops underneath the main column and when this happens the sidebar becomes as wide as the main column. My 'custom-size-small' is '300px' and you can imagine when the sidebar places under the column, if the viewer is still larger than 300px, the quality of the images suffers. That made me think of this relatively new feature on WP in which srcset is used. But the problem is that the way I want to make use of it is quite the opposite we normally do, is that, bigger images for smaller screens and vice versa.</p> <p>Can we make WP use the 'custom-size-small' on desktops and the bigger 'custom-size-big' which is twice as big, on smaller screens?</p> <p>/* I'm not a coder, I can only tamper with the codes. */</p> <p>That would be great if you could tell me what changes I should make to this?</p> <pre><code>&lt;?php the_post_thumbnail('custom-size-small' ,array('class' =&gt; 'image', 'title' =&gt; strip_tags(get_the_title()), 'itemprop' =&gt; 'image')); ?&gt; </code></pre>
[ { "answer_id": 236579, "author": "Ladislav Janeček", "author_id": 50964, "author_profile": "https://wordpress.stackexchange.com/users/50964", "pm_score": -1, "selected": false, "text": "<p>You can add to CSS this code:</p>\n\n<pre><code>.image {\n max-width: 100%;\n width: auto;\n height: auto;\n}\n</code></pre>\n\n<p>and it will be responsive!</p>\n" }, { "answer_id": 236608, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>This is mostly off-topic, but your assumption that <code>srcset</code> is somehow related to going desktop => mobile is just false. the <code>srcset</code> attribute notifies the browser about alternative images and sizes and it is <strong>the browser that selects which image to use</strong> based on whatever criteria it wants. Therefor there is most likely nothing wrong with your code if it outputs the <code>srcset</code> attribute and you see a non optimal fit of the image because the browser decided it is the best thing to do, for example if it has already an image in its cache it might prefer not to load a new one. Since the <code>srcset</code> attribute is designed to leave control in the hands of the browsers, there is not much you can do about on wordpress side.</p>\n" } ]
2016/08/21
[ "https://wordpress.stackexchange.com/questions/236576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101351/" ]
I have a simple two columns website (one sidebar + one maincoulmn). In the sidebar area I use this code to show some post thumbnails: ``` <?php the_post_thumbnail('custom-size-small' ,array('class' => 'image', 'title' => strip_tags(get_the_title()), 'itemprop' => 'image')); ?> ``` My website is responsive and on smaller devices the sidebar drops underneath the main column and when this happens the sidebar becomes as wide as the main column. My 'custom-size-small' is '300px' and you can imagine when the sidebar places under the column, if the viewer is still larger than 300px, the quality of the images suffers. That made me think of this relatively new feature on WP in which srcset is used. But the problem is that the way I want to make use of it is quite the opposite we normally do, is that, bigger images for smaller screens and vice versa. Can we make WP use the 'custom-size-small' on desktops and the bigger 'custom-size-big' which is twice as big, on smaller screens? /\* I'm not a coder, I can only tamper with the codes. \*/ That would be great if you could tell me what changes I should make to this? ``` <?php the_post_thumbnail('custom-size-small' ,array('class' => 'image', 'title' => strip_tags(get_the_title()), 'itemprop' => 'image')); ?> ```
This is mostly off-topic, but your assumption that `srcset` is somehow related to going desktop => mobile is just false. the `srcset` attribute notifies the browser about alternative images and sizes and it is **the browser that selects which image to use** based on whatever criteria it wants. Therefor there is most likely nothing wrong with your code if it outputs the `srcset` attribute and you see a non optimal fit of the image because the browser decided it is the best thing to do, for example if it has already an image in its cache it might prefer not to load a new one. Since the `srcset` attribute is designed to leave control in the hands of the browsers, there is not much you can do about on wordpress side.
236,591
<p>Can anyone tell me what the correct syntax is for the following?</p> <pre><code>&lt;?php if (function_exists('z_taxonomy_image')) : ?&gt; &lt;img alt="" src="&lt;?php if (function_exists('z_taxonomy_image_url')) echo z_taxonomy_image_url($child-&gt;term_id);?&gt;" /&gt; &lt;?php else : ?&gt; echo '&lt;img alt="'. esc_html( get_the_title() ) .'" src="'. esc_url( get_template_directory_uri() . '/assets/images/blank325_170.png' ) .'"&gt;'; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 236579, "author": "Ladislav Janeček", "author_id": 50964, "author_profile": "https://wordpress.stackexchange.com/users/50964", "pm_score": -1, "selected": false, "text": "<p>You can add to CSS this code:</p>\n\n<pre><code>.image {\n max-width: 100%;\n width: auto;\n height: auto;\n}\n</code></pre>\n\n<p>and it will be responsive!</p>\n" }, { "answer_id": 236608, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>This is mostly off-topic, but your assumption that <code>srcset</code> is somehow related to going desktop => mobile is just false. the <code>srcset</code> attribute notifies the browser about alternative images and sizes and it is <strong>the browser that selects which image to use</strong> based on whatever criteria it wants. Therefor there is most likely nothing wrong with your code if it outputs the <code>srcset</code> attribute and you see a non optimal fit of the image because the browser decided it is the best thing to do, for example if it has already an image in its cache it might prefer not to load a new one. Since the <code>srcset</code> attribute is designed to leave control in the hands of the browsers, there is not much you can do about on wordpress side.</p>\n" } ]
2016/08/21
[ "https://wordpress.stackexchange.com/questions/236591", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68414/" ]
Can anyone tell me what the correct syntax is for the following? ``` <?php if (function_exists('z_taxonomy_image')) : ?> <img alt="" src="<?php if (function_exists('z_taxonomy_image_url')) echo z_taxonomy_image_url($child->term_id);?>" /> <?php else : ?> echo '<img alt="'. esc_html( get_the_title() ) .'" src="'. esc_url( get_template_directory_uri() . '/assets/images/blank325_170.png' ) .'">'; <?php endif; ?> ```
This is mostly off-topic, but your assumption that `srcset` is somehow related to going desktop => mobile is just false. the `srcset` attribute notifies the browser about alternative images and sizes and it is **the browser that selects which image to use** based on whatever criteria it wants. Therefor there is most likely nothing wrong with your code if it outputs the `srcset` attribute and you see a non optimal fit of the image because the browser decided it is the best thing to do, for example if it has already an image in its cache it might prefer not to load a new one. Since the `srcset` attribute is designed to leave control in the hands of the browsers, there is not much you can do about on wordpress side.
236,600
<p>I have a custom post type called event. The URL structure looks like this. </p> <blockquote> <p><a href="http://my-url.com/events/2016/08/21/workshop" rel="nofollow">http://my-url.com/events/2016/08/21/workshop</a></p> </blockquote> <p>Where "workshop" is the name of the event. Right now the template will show different data depending on the query string. For example this URL:</p> <blockquote> <p><a href="http://my-url.com/events/2016/08/21/workshop?sub=files" rel="nofollow">http://my-url.com/events/2016/08/21/workshop?sub=files</a></p> </blockquote> <p>Will loop out some files. I'm adding the query string so i can do that in the same template. </p> <pre><code>&lt;?php $sub = isset( $_GET['sub'] ) ? $_GET['sub'] : null; switch ( $sub ) { case "files": echo "TODO: Loop out files"; break; case "participants": echo "TODO: Loop out participants"; break; case "agenda": echo "TODO: Write out the agenda!"; break; &lt;!-- etc --&gt; } ?&gt; </code></pre> <p>But i don't like this URL structure! I'd like the URL to be:</p> <blockquote> <p><a href="http://my-url.com/events/2016/08/21/workshop/files" rel="nofollow">http://my-url.com/events/2016/08/21/workshop/files</a></p> </blockquote> <p>So that i in the "Event" template (<code>/workshop/</code>) can look at the URL structure instead of the query string. The problem is that adding <code>/files</code>to the URL will make wordpress look for a page that doesn't exist and give a 404.</p> <p>Is it possible to do some URL wizardry so the template (and post data) of this url:</p> <blockquote> <p><a href="http://my-url.com/events/2016/08/21/workshop/" rel="nofollow">http://my-url.com/events/2016/08/21/workshop/</a></p> </blockquote> <p>Also kicks in with this URL:</p> <blockquote> <p><a href="http://my-url.com/events/2016/08/21/workshop/agenda/" rel="nofollow">http://my-url.com/events/2016/08/21/workshop/agenda/</a></p> </blockquote>
[ { "answer_id": 236612, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 2, "selected": false, "text": "<p>Put this code in your <code>functions.php</code>-</p>\n\n<pre><code>function the_dramatist_url_rewrite() {\n global $wp_rewrite;\n add_rewrite_tag('%sub%', '([^&amp;]+)');\n add_rewrite_rule(\n '^events/%year%/%monthnum%/%day%/%postname%/?', \n 'index.php/events/%year%/%monthnum%/%day%/%postname%?sub=$matches[1]', \n 'top'\n );\n}\nadd_action('init', 'the_dramatist_url_rewrite', 10, 0);\n</code></pre>\n\n<p>The go to the permalinks page in the settings menu at dashboard and hit <code>Save Changes</code> button. Hope this is gonna help.</p>\n" }, { "answer_id": 242679, "author": "Johan B", "author_id": 16567, "author_profile": "https://wordpress.stackexchange.com/users/16567", "pm_score": 2, "selected": true, "text": "<p>I ended up using <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">end points</a>. This is my final (but simplified) code. In functions i added this.</p>\n\n<pre><code>add_action('init', 'jbenjaminsson_add_endpoints');\nfunction jbenjaminsson_add_endpoints()\n{\n add_rewrite_endpoint( 'files', EP_PERMALINK );\n add_rewrite_endpoint( 'participants', EP_PERMALINK );\n add_rewrite_endpoint( 'agenda', EP_PERMALINK );\n}\n\nadd_filter( 'request', 'jbenjaminsson_filter_request' );\nfunction jbenjaminsson_filter_request( $vars )\n{\n if( isset( $vars['files'] ) ) $vars['files'] = true;\n if( isset( $vars['participants'] ) ) $vars['participants'] = true;\n if( isset( $vars['agenda'] ) ) $vars['agenda'] = true;\n return $vars;\n}\n</code></pre>\n\n<p>And on the template i did this:</p>\n\n<pre><code>if ( get_query_var( 'files' ) ) {\n get_template_part( '/template-parts/event', 'files' );\n} elseif ( get_query_var( 'participants' ) ) {\n get_template_part( '/template-parts/event', 'participants' );\n} elseif ( get_query_var( 'agenda' ) ) {\n get_template_part( '/template-parts/event', 'agenda' );\n}\n</code></pre>\n" } ]
2016/08/21
[ "https://wordpress.stackexchange.com/questions/236600", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16567/" ]
I have a custom post type called event. The URL structure looks like this. > > <http://my-url.com/events/2016/08/21/workshop> > > > Where "workshop" is the name of the event. Right now the template will show different data depending on the query string. For example this URL: > > <http://my-url.com/events/2016/08/21/workshop?sub=files> > > > Will loop out some files. I'm adding the query string so i can do that in the same template. ``` <?php $sub = isset( $_GET['sub'] ) ? $_GET['sub'] : null; switch ( $sub ) { case "files": echo "TODO: Loop out files"; break; case "participants": echo "TODO: Loop out participants"; break; case "agenda": echo "TODO: Write out the agenda!"; break; <!-- etc --> } ?> ``` But i don't like this URL structure! I'd like the URL to be: > > <http://my-url.com/events/2016/08/21/workshop/files> > > > So that i in the "Event" template (`/workshop/`) can look at the URL structure instead of the query string. The problem is that adding `/files`to the URL will make wordpress look for a page that doesn't exist and give a 404. Is it possible to do some URL wizardry so the template (and post data) of this url: > > <http://my-url.com/events/2016/08/21/workshop/> > > > Also kicks in with this URL: > > <http://my-url.com/events/2016/08/21/workshop/agenda/> > > >
I ended up using [end points](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint). This is my final (but simplified) code. In functions i added this. ``` add_action('init', 'jbenjaminsson_add_endpoints'); function jbenjaminsson_add_endpoints() { add_rewrite_endpoint( 'files', EP_PERMALINK ); add_rewrite_endpoint( 'participants', EP_PERMALINK ); add_rewrite_endpoint( 'agenda', EP_PERMALINK ); } add_filter( 'request', 'jbenjaminsson_filter_request' ); function jbenjaminsson_filter_request( $vars ) { if( isset( $vars['files'] ) ) $vars['files'] = true; if( isset( $vars['participants'] ) ) $vars['participants'] = true; if( isset( $vars['agenda'] ) ) $vars['agenda'] = true; return $vars; } ``` And on the template i did this: ``` if ( get_query_var( 'files' ) ) { get_template_part( '/template-parts/event', 'files' ); } elseif ( get_query_var( 'participants' ) ) { get_template_part( '/template-parts/event', 'participants' ); } elseif ( get_query_var( 'agenda' ) ) { get_template_part( '/template-parts/event', 'agenda' ); } ```
236,626
<p>I have used the following code to display the featured image for each post, but nothing is showing:</p> <pre><code> &lt;div class="thumbnail-img"&gt; &lt;?php $lastBlog = new WP_Query('type=post&amp;posts_per_page=2&amp;offset=1'); if ($lastBlog-&gt;has_post_thumbnail()) { while($lastBlog-&gt;has_post_thumbnail()) { $lastBlog-&gt;the_post_thumbnail(); } ?&gt; &lt;?php get_template_part('content-image', get_the_post_thumbnail()); } ?&gt; &lt;/div&gt; &lt;br&gt; &lt;?php if( $lastBlog-&gt;have_posts()): while($lastBlog-&gt;have_posts()): $lastBlog-&gt;the_post(); ?&gt; &lt;?php get_template_part('content-title', get_post_format()); ?&gt; &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; &lt;/div&gt; </code></pre> <p>How do I resolve this? </p>
[ { "answer_id": 236629, "author": "Ali Basheer", "author_id": 93545, "author_profile": "https://wordpress.stackexchange.com/users/93545", "pm_score": 1, "selected": false, "text": "<p>I use this way:</p>\n\n<pre><code>$args = array ( 'post_type' =&gt; 'slider');\n$slides = get_posts( $args );\n\nforeach($slides as $row){ \n $image = wp_get_attachment_image_src(get_post_thumbnail_id($row-&gt;ID),\"full\");\n echo $image[0];\n}\n</code></pre>\n" }, { "answer_id": 236640, "author": "Omar", "author_id": 83743, "author_profile": "https://wordpress.stackexchange.com/users/83743", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;div class=\"thumbnail-img\"&gt;\n&lt;?php \n $lastBlog = new WP_Query('post_type=post&amp;posts_per_page=2');\n if ($lastBlog-&gt;have_posts()) {\n while($lastBlog-&gt;have_posts()) {\n $lastBlog-&gt;the_post();\n if(has_post_thumbnail()){\n the_post_thumbnail();\n }\n }\n }\n ?&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>-> Try Like This</p>\n" } ]
2016/08/21
[ "https://wordpress.stackexchange.com/questions/236626", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101377/" ]
I have used the following code to display the featured image for each post, but nothing is showing: ``` <div class="thumbnail-img"> <?php $lastBlog = new WP_Query('type=post&posts_per_page=2&offset=1'); if ($lastBlog->has_post_thumbnail()) { while($lastBlog->has_post_thumbnail()) { $lastBlog->the_post_thumbnail(); } ?> <?php get_template_part('content-image', get_the_post_thumbnail()); } ?> </div> <br> <?php if( $lastBlog->have_posts()): while($lastBlog->have_posts()): $lastBlog->the_post(); ?> <?php get_template_part('content-title', get_post_format()); ?> <?php endwhile; endif; wp_reset_postdata(); ?> </div> ``` How do I resolve this?
``` <div class="thumbnail-img"> <?php $lastBlog = new WP_Query('post_type=post&posts_per_page=2'); if ($lastBlog->have_posts()) { while($lastBlog->have_posts()) { $lastBlog->the_post(); if(has_post_thumbnail()){ the_post_thumbnail(); } } } ?> </div> ``` -> Try Like This
236,646
<p>In plugin development, how to fetch data from database of particular data in dropdown list?</p> <pre><code>global $wpdb; $id = 'parent_id'; $data = $wpdb-&gt;get_results("SELECT * FROM wp_postmeta WHERE meta_key = $id"); echo $data; </code></pre> <p>i get results as array how can i get all values in dropdown list? Can you please help?</p>
[ { "answer_id": 236629, "author": "Ali Basheer", "author_id": 93545, "author_profile": "https://wordpress.stackexchange.com/users/93545", "pm_score": 1, "selected": false, "text": "<p>I use this way:</p>\n\n<pre><code>$args = array ( 'post_type' =&gt; 'slider');\n$slides = get_posts( $args );\n\nforeach($slides as $row){ \n $image = wp_get_attachment_image_src(get_post_thumbnail_id($row-&gt;ID),\"full\");\n echo $image[0];\n}\n</code></pre>\n" }, { "answer_id": 236640, "author": "Omar", "author_id": 83743, "author_profile": "https://wordpress.stackexchange.com/users/83743", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;div class=\"thumbnail-img\"&gt;\n&lt;?php \n $lastBlog = new WP_Query('post_type=post&amp;posts_per_page=2');\n if ($lastBlog-&gt;have_posts()) {\n while($lastBlog-&gt;have_posts()) {\n $lastBlog-&gt;the_post();\n if(has_post_thumbnail()){\n the_post_thumbnail();\n }\n }\n }\n ?&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>-> Try Like This</p>\n" } ]
2016/08/22
[ "https://wordpress.stackexchange.com/questions/236646", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101387/" ]
In plugin development, how to fetch data from database of particular data in dropdown list? ``` global $wpdb; $id = 'parent_id'; $data = $wpdb->get_results("SELECT * FROM wp_postmeta WHERE meta_key = $id"); echo $data; ``` i get results as array how can i get all values in dropdown list? Can you please help?
``` <div class="thumbnail-img"> <?php $lastBlog = new WP_Query('post_type=post&posts_per_page=2'); if ($lastBlog->have_posts()) { while($lastBlog->have_posts()) { $lastBlog->the_post(); if(has_post_thumbnail()){ the_post_thumbnail(); } } } ?> </div> ``` -> Try Like This
236,705
<p>How to remove this from WP head:</p> <pre><code>&lt;link rel='dns-prefetch' href='//maps.google.com'&gt; </code></pre> <p>I had this also:</p> <pre><code>&lt;link rel='dns-prefetch' href='//s.w.org'&gt; </code></pre> <p>But, I removed it with this code inside my functions.php</p> <pre><code>add_filter( 'emoji_svg_url', '__return_false' ); </code></pre> <p>Probably, this is added by one plugin <a href="https://wordpress.org/plugins/thesography/" rel="nofollow">exifografy</a>, which can show map of location where image is taken. But, there is just few posts with map, so having this on all URL-s is just one more line of not used HTML code.</p>
[ { "answer_id": 236708, "author": "wpclevel", "author_id": 92212, "author_profile": "https://wordpress.stackexchange.com/users/92212", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/\" rel=\"noreferrer\">Resource Hints</a> is a smart feature added to WordPress version 4.6. I think it might improve your site speed. But if you want to disable it, try this:</p>\n\n<pre><code>remove_action('wp_head', 'wp_resource_hints', 2);\n</code></pre>\n\n<hr>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/default-filters.php#L232\" rel=\"noreferrer\">wp_head resource hints</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_resource_hints/\" rel=\"noreferrer\">wp_resource_hints filter</a></li>\n</ul>\n" }, { "answer_id": 307766, "author": "Chris Panayotoff", "author_id": 64077, "author_profile": "https://wordpress.stackexchange.com/users/64077", "pm_score": 1, "selected": false, "text": "<pre><code>/*\n * Removes &lt;link rel=\"prefetch\" for WP assets not used in the theme\n * */\nfunction remove_dns_prefetch($hints, $relation_type)\n{\n if ('dns-prefetch' === $relation_type) {\n return array_diff(wp_dependencies_unique_hosts(), $hints);\n }\n return $hints;\n}\n\nadd_filter('wp_resource_hints', 'remove_dns_prefetch', 10, 2);\n</code></pre>\n\n<p>I would suggest to remove it only if not used in the theme, this is the helper function I'm using </p>\n" }, { "answer_id": 385954, "author": "lucrp", "author_id": 161235, "author_profile": "https://wordpress.stackexchange.com/users/161235", "pm_score": 1, "selected": false, "text": "<p>I did this by using wp_resource_hints filter and preg_match :</p>\n<pre><code> /**\n * Removes dns-prefetchs links in header\n */\n public function remove_prefetchs($urls) {\n foreach ($urls as $key =&gt; $url) {\n if(preg_match('/google.com|code.jquery.com$/', $url) === 1) {\n unset( $urls[ $key ] );\n }\n }\n return $urls;\n }\n</code></pre>\n<pre><code>add_filter( 'wp_resource_hints', array( $this, 'remove_prefetchs' ), 10, 2);\n</code></pre>\n" } ]
2016/08/22
[ "https://wordpress.stackexchange.com/questions/236705", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25053/" ]
How to remove this from WP head: ``` <link rel='dns-prefetch' href='//maps.google.com'> ``` I had this also: ``` <link rel='dns-prefetch' href='//s.w.org'> ``` But, I removed it with this code inside my functions.php ``` add_filter( 'emoji_svg_url', '__return_false' ); ``` Probably, this is added by one plugin [exifografy](https://wordpress.org/plugins/thesography/), which can show map of location where image is taken. But, there is just few posts with map, so having this on all URL-s is just one more line of not used HTML code.
[Resource Hints](https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/) is a smart feature added to WordPress version 4.6. I think it might improve your site speed. But if you want to disable it, try this: ``` remove_action('wp_head', 'wp_resource_hints', 2); ``` --- **References** * [wp\_head resource hints](https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/default-filters.php#L232) * [wp\_resource\_hints filter](https://developer.wordpress.org/reference/hooks/wp_resource_hints/)
236,718
<p>I was developing website on <code>test.example.com</code> on a separate server. Meanwhile, the working server was <code>example.com</code> at GoDaddy.</p> <p>The WordPress website was working fine on both servers. But then I changed the registrar and decided to change the WordPress on <code>test.example.com</code> to <code>example.com</code> inside of the <code>wp-config.php</code>. If I'm entering <code>example.com/wp-admin</code> - it opens without problem. However, when I try <code>example.com</code> it redirects to <code>test.example.com</code>.</p> <p>Can't figure out why it's happening.</p>
[ { "answer_id": 236708, "author": "wpclevel", "author_id": 92212, "author_profile": "https://wordpress.stackexchange.com/users/92212", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/\" rel=\"noreferrer\">Resource Hints</a> is a smart feature added to WordPress version 4.6. I think it might improve your site speed. But if you want to disable it, try this:</p>\n\n<pre><code>remove_action('wp_head', 'wp_resource_hints', 2);\n</code></pre>\n\n<hr>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/default-filters.php#L232\" rel=\"noreferrer\">wp_head resource hints</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_resource_hints/\" rel=\"noreferrer\">wp_resource_hints filter</a></li>\n</ul>\n" }, { "answer_id": 307766, "author": "Chris Panayotoff", "author_id": 64077, "author_profile": "https://wordpress.stackexchange.com/users/64077", "pm_score": 1, "selected": false, "text": "<pre><code>/*\n * Removes &lt;link rel=\"prefetch\" for WP assets not used in the theme\n * */\nfunction remove_dns_prefetch($hints, $relation_type)\n{\n if ('dns-prefetch' === $relation_type) {\n return array_diff(wp_dependencies_unique_hosts(), $hints);\n }\n return $hints;\n}\n\nadd_filter('wp_resource_hints', 'remove_dns_prefetch', 10, 2);\n</code></pre>\n\n<p>I would suggest to remove it only if not used in the theme, this is the helper function I'm using </p>\n" }, { "answer_id": 385954, "author": "lucrp", "author_id": 161235, "author_profile": "https://wordpress.stackexchange.com/users/161235", "pm_score": 1, "selected": false, "text": "<p>I did this by using wp_resource_hints filter and preg_match :</p>\n<pre><code> /**\n * Removes dns-prefetchs links in header\n */\n public function remove_prefetchs($urls) {\n foreach ($urls as $key =&gt; $url) {\n if(preg_match('/google.com|code.jquery.com$/', $url) === 1) {\n unset( $urls[ $key ] );\n }\n }\n return $urls;\n }\n</code></pre>\n<pre><code>add_filter( 'wp_resource_hints', array( $this, 'remove_prefetchs' ), 10, 2);\n</code></pre>\n" } ]
2016/08/22
[ "https://wordpress.stackexchange.com/questions/236718", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101428/" ]
I was developing website on `test.example.com` on a separate server. Meanwhile, the working server was `example.com` at GoDaddy. The WordPress website was working fine on both servers. But then I changed the registrar and decided to change the WordPress on `test.example.com` to `example.com` inside of the `wp-config.php`. If I'm entering `example.com/wp-admin` - it opens without problem. However, when I try `example.com` it redirects to `test.example.com`. Can't figure out why it's happening.
[Resource Hints](https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/) is a smart feature added to WordPress version 4.6. I think it might improve your site speed. But if you want to disable it, try this: ``` remove_action('wp_head', 'wp_resource_hints', 2); ``` --- **References** * [wp\_head resource hints](https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/default-filters.php#L232) * [wp\_resource\_hints filter](https://developer.wordpress.org/reference/hooks/wp_resource_hints/)
236,723
<p>I'm new to wordpress/php and I'm trying to create new posts dynamically through a xml file.</p> <p>The xml I'm working with is this <a href="http://videos.oneupsports.com/oneup-sports-national/rss.xml" rel="nofollow">one</a>.</p> <p>The file get updated periodically during the day in a FILO fashion (new item are added at the top and the bottom one get push out) and right now we have someone manually creating new posts every few hours by grabbing a few value in each items.</p> <p>So what I'm wondering is if I can automate this process?</p> <p>Whenever this file is updated. Wordpress will create a new post with the new item only.</p> <p>I'm able to pull values out of the xml file, but I'm having trouble creating a post dynamically and also set it so it will only create the new items, so I won't have any duplicates.</p> <p>Also I'm not sure if this will effect much of the code, but I'm using the <a href="https://www.advancedcustomfields.com/" rel="nofollow">ACF</a> plugin, so there are some custom fields in the post as well.</p> <p>Thanks in advance.</p>
[ { "answer_id": 236708, "author": "wpclevel", "author_id": 92212, "author_profile": "https://wordpress.stackexchange.com/users/92212", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/\" rel=\"noreferrer\">Resource Hints</a> is a smart feature added to WordPress version 4.6. I think it might improve your site speed. But if you want to disable it, try this:</p>\n\n<pre><code>remove_action('wp_head', 'wp_resource_hints', 2);\n</code></pre>\n\n<hr>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/default-filters.php#L232\" rel=\"noreferrer\">wp_head resource hints</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_resource_hints/\" rel=\"noreferrer\">wp_resource_hints filter</a></li>\n</ul>\n" }, { "answer_id": 307766, "author": "Chris Panayotoff", "author_id": 64077, "author_profile": "https://wordpress.stackexchange.com/users/64077", "pm_score": 1, "selected": false, "text": "<pre><code>/*\n * Removes &lt;link rel=\"prefetch\" for WP assets not used in the theme\n * */\nfunction remove_dns_prefetch($hints, $relation_type)\n{\n if ('dns-prefetch' === $relation_type) {\n return array_diff(wp_dependencies_unique_hosts(), $hints);\n }\n return $hints;\n}\n\nadd_filter('wp_resource_hints', 'remove_dns_prefetch', 10, 2);\n</code></pre>\n\n<p>I would suggest to remove it only if not used in the theme, this is the helper function I'm using </p>\n" }, { "answer_id": 385954, "author": "lucrp", "author_id": 161235, "author_profile": "https://wordpress.stackexchange.com/users/161235", "pm_score": 1, "selected": false, "text": "<p>I did this by using wp_resource_hints filter and preg_match :</p>\n<pre><code> /**\n * Removes dns-prefetchs links in header\n */\n public function remove_prefetchs($urls) {\n foreach ($urls as $key =&gt; $url) {\n if(preg_match('/google.com|code.jquery.com$/', $url) === 1) {\n unset( $urls[ $key ] );\n }\n }\n return $urls;\n }\n</code></pre>\n<pre><code>add_filter( 'wp_resource_hints', array( $this, 'remove_prefetchs' ), 10, 2);\n</code></pre>\n" } ]
2016/08/22
[ "https://wordpress.stackexchange.com/questions/236723", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101431/" ]
I'm new to wordpress/php and I'm trying to create new posts dynamically through a xml file. The xml I'm working with is this [one](http://videos.oneupsports.com/oneup-sports-national/rss.xml). The file get updated periodically during the day in a FILO fashion (new item are added at the top and the bottom one get push out) and right now we have someone manually creating new posts every few hours by grabbing a few value in each items. So what I'm wondering is if I can automate this process? Whenever this file is updated. Wordpress will create a new post with the new item only. I'm able to pull values out of the xml file, but I'm having trouble creating a post dynamically and also set it so it will only create the new items, so I won't have any duplicates. Also I'm not sure if this will effect much of the code, but I'm using the [ACF](https://www.advancedcustomfields.com/) plugin, so there are some custom fields in the post as well. Thanks in advance.
[Resource Hints](https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/) is a smart feature added to WordPress version 4.6. I think it might improve your site speed. But if you want to disable it, try this: ``` remove_action('wp_head', 'wp_resource_hints', 2); ``` --- **References** * [wp\_head resource hints](https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/default-filters.php#L232) * [wp\_resource\_hints filter](https://developer.wordpress.org/reference/hooks/wp_resource_hints/)
236,734
<p>I've done this many times before, and yet I'm not managing to do this again for some unknown reason. Tried endless solutions. Everything I've tried results in an endless redirect loop. </p> <p>What is the best option for doing this?</p> <p><strong>Update 1</strong> Here are a few of the things tried;</p> <pre><code>RewriteCond %{HTTP_HOST} ^website\.co\.uk [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.website.co.uk/$1 [R,L] </code></pre> <p>And;</p> <pre><code>RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.website.co.uk$1 [R,L] </code></pre> <p>Tested in different browsers to prevent caching issues. Still nothing, just getting continual redirect loop. </p>
[ { "answer_id": 236851, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 5, "selected": true, "text": "<p>I see, when you enter a link to your page other than your home, example:</p>\n\n<ul>\n<li><code>http://www.michaelcropper.co.uk/contact-me</code></li>\n<li><code>www.michaelcropper.co.uk/contact-me</code></li>\n<li><code>michaelcropper.co.uk/contact-me</code></li>\n</ul>\n\n<p>If <code>https://</code> is not in the prefix, the HTTP link loads instead. Add the following into your <code>.htaccess</code> in between the <code>&lt;IfModule mod_rewrite.c&gt;</code> tag:</p>\n\n<pre><code>RewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n</code></pre>\n\n<p>If there were no additional modifications done to your <code>.htaccess</code>, it should look like the following:</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n# Rewrite HTTP to HTTPS\nRewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n\n<p>Let me know how it goes.</p>\n" }, { "answer_id": 304626, "author": "zihadul", "author_id": 121562, "author_profile": "https://wordpress.stackexchange.com/users/121562", "pm_score": 0, "selected": false, "text": "<p>Just Add this in your .htaccess file</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\n\nRewriteCond %{HTTPS} !=on\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n" }, { "answer_id": 308977, "author": "Chris Sprague", "author_id": 140665, "author_profile": "https://wordpress.stackexchange.com/users/140665", "pm_score": 0, "selected": false, "text": "<p>If you are using W3 Total Cache the answer from @Ethan Jinks O'Sullivan will only work if you place the redirect before the W3 Total Cache mods in .htaccess as shown below</p>\n\n<pre><code>#BEGIN Rewrite HTTP to HTTPS\n&lt;IfModule mod_rewrite.c&gt;\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n#END Rewrite HTTP to HTTPS\n\n# BEGIN GZIP COMPRESSION\n...\n# END GZIP COMPRESSION\n\n# BEGIN DEFLATE COMPRESSION\n...\n# END DEFLATE COMPRESSION\n\n# BEGIN W3TC Browser Cache\n...\n# END W3TC Browser Cache\n\n# BEGIN W3TC Page Cache core\n...\n# END W3TC Page Cache core\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n RewriteRule ^index\\.php$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 313890, "author": "Iggy", "author_id": 32150, "author_profile": "https://wordpress.stackexchange.com/users/32150", "pm_score": 2, "selected": false, "text": "<p>You can set header in .htaccess</p>\n\n<pre><code>&lt;IfModule mod_headers.c&gt;\n Header always set Strict-Transport-Security \"max-age=31536000; includeSubDomains\" env=HTTPS\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 314604, "author": "Jasom Dotnet", "author_id": 50021, "author_profile": "https://wordpress.stackexchange.com/users/50021", "pm_score": 2, "selected": false, "text": "<p>try this in your <code>.htaccess</code>:</p>\n\n<pre><code>RewriteCond %{HTTP:X-Forwarded-Proto} !=https\nRewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 328976, "author": "Siddharth Shukla", "author_id": 141854, "author_profile": "https://wordpress.stackexchange.com/users/141854", "pm_score": 3, "selected": false, "text": "<p>Add code within a .htaccess file </p>\n\n<pre><code> &lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n\n RewriteCond %{HTTPS} !=on\n RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\n # BEGIN WordPress\n RewriteRule ^index\\.php$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n &lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 341789, "author": "user3469142", "author_id": 170968, "author_profile": "https://wordpress.stackexchange.com/users/170968", "pm_score": -1, "selected": false, "text": "<p>Toke me 10 minutes to fix the issue</p>\n\n<p>Add a conf file for your domain.</p>\n\n<p>Go to centos 7 at <code>/etc/httpd/conf.d/</code>, then create a conf file called <code>anything.conf</code>.</p>\n\n<p>Put the following code on it:</p>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n ServerName domain.com\n ServerAlias www.domain.com\n ServerAdmin [email protected]\n DocumentRoot /var/www/html\n\n &lt;Directory /var/www/html&gt;\n Options -Indexes +FollowSymLinks\n AllowOverride All\n &lt;/Directory&gt;\n\n ErrorLog /var/log/httpd/example.com-error.log\n CustomLog /var/log/httpd/example.com-access.log combined\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>Replace <code>example.com</code> with your domain.<br>\nThen add the https rewrite code on .htaccess its will work. :)</p>\n" }, { "answer_id": 345004, "author": "vvvvv", "author_id": 173420, "author_profile": "https://wordpress.stackexchange.com/users/173420", "pm_score": -1, "selected": false, "text": "<pre><code>#BEGIN Rewrite HTTP to HTTPS\n&lt;IfModule mod_rewrite.c&gt;\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n#END Rewrite HTTP to HTTPS\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n RewriteRule ^index\\.php$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 351986, "author": "vin decode", "author_id": 177922, "author_profile": "https://wordpress.stackexchange.com/users/177922", "pm_score": 0, "selected": false, "text": "<p>If you don't want to change anything on .htaccess you may try this out</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', 'redirect_core', 50);\nadd_action('init', 'redirect_core', 50);\nadd_action('wp_loaded', 'redirect_core', 50);\nfunction redirect_core(){\n if (!is_ssl()) {\n wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301);\n exit();\n }\n}\n</code></pre>\n\n<p>Or try this plugin: <a href=\"https://github.com/vindecodex/wp-https-redirect/blob/master/https-redirect.php\" rel=\"nofollow noreferrer\">HTTPS Redirect</a></p>\n" } ]
2016/08/22
[ "https://wordpress.stackexchange.com/questions/236734", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91911/" ]
I've done this many times before, and yet I'm not managing to do this again for some unknown reason. Tried endless solutions. Everything I've tried results in an endless redirect loop. What is the best option for doing this? **Update 1** Here are a few of the things tried; ``` RewriteCond %{HTTP_HOST} ^website\.co\.uk [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.website.co.uk/$1 [R,L] ``` And; ``` RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.website.co.uk$1 [R,L] ``` Tested in different browsers to prevent caching issues. Still nothing, just getting continual redirect loop.
I see, when you enter a link to your page other than your home, example: * `http://www.michaelcropper.co.uk/contact-me` * `www.michaelcropper.co.uk/contact-me` * `michaelcropper.co.uk/contact-me` If `https://` is not in the prefix, the HTTP link loads instead. Add the following into your `.htaccess` in between the `<IfModule mod_rewrite.c>` tag: ``` RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] ``` If there were no additional modifications done to your `.htaccess`, it should look like the following: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # Rewrite HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] </IfModule> # END WordPress ``` Let me know how it goes.
236,739
<p>After severall search, maybe without the right english terms, I come here to find an answer to my problem.</p> <p>I have a theme that I created on my website, everything is working perfectly for the last 6 months.</p> <p>I also have a custom post type to add some twitch channel on my website and display them.</p> <p>Yesterday, I created a new custom post type to write some fast news so just the minimal content : title, content, author and revisions.</p> <p>But when I add this one to my website, the Posts, Streams, News and Pages list become empty with a "not found" message even when there is some content with this post type.</p> <p>Like this : <a href="https://i.stack.imgur.com/tpZOn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tpZOn.png" alt="Empty list"></a></p> <p>I think I already had this bug a long time ago but I can't remember how to fix it.</p> <p>I tried to desactivate my every plugin one by one but the bug was still there.</p> <p>Here is the code of my Custom Post Type (created with GenerateWP to save a lot of time) : </p> <pre><code>if ( ! function_exists('news_post') ) { function news_post() { $labels = array( 'name' =&gt; _x( 'News', 'Post Type General Name', 'text_domain' ), 'singular_name' =&gt; _x( 'News', 'Post Type Singular Name', 'text_domain' ), 'menu_name' =&gt; __( 'News', 'text_domain' ), 'name_admin_bar' =&gt; __( 'News', 'text_domain' ), 'archives' =&gt; __( 'Item Archives', 'text_domain' ), 'parent_item_colon' =&gt; __( 'Parent News:', 'text_domain' ), 'all_items' =&gt; __( 'All News', 'text_domain' ), 'add_new_item' =&gt; __( 'Add New News', 'text_domain' ), 'add_new' =&gt; __( 'Add News', 'text_domain' ), 'new_item' =&gt; __( 'New News', 'text_domain' ), 'edit_item' =&gt; __( 'Edit News', 'text_domain' ), 'update_item' =&gt; __( 'Update News', 'text_domain' ), 'view_item' =&gt; __( 'View News', 'text_domain' ), 'search_items' =&gt; __( 'Search News', 'text_domain' ), 'not_found' =&gt; __( 'Not found', 'text_domain' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'text_domain' ), 'featured_image' =&gt; __( 'Featured Image', 'text_domain' ), 'set_featured_image' =&gt; __( 'Set featured image', 'text_domain' ), 'remove_featured_image' =&gt; __( 'Remove featured image', 'text_domain' ), 'use_featured_image' =&gt; __( 'Use as featured image', 'text_domain' ), 'insert_into_item' =&gt; __( 'Insert into News', 'text_domain' ), 'uploaded_to_this_item' =&gt; __( 'Uploaded to this News', 'text_domain' ), 'items_list' =&gt; __( 'News list', 'text_domain' ), 'items_list_navigation' =&gt; __( 'News list navigation', 'text_domain' ), 'filter_items_list' =&gt; __( 'Filter News list', 'text_domain' ), ); $args = array( 'label' =&gt; __( 'News', 'text_domain' ), 'description' =&gt; __( 'News Post Type', 'text_domain' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'editor', 'author', 'revisions', ), 'hierarchical' =&gt; false, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 5, 'show_in_admin_bar' =&gt; true, 'show_in_nav_menus' =&gt; true, 'can_export' =&gt; true, 'has_archive' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'capability_type' =&gt; 'post', ); register_post_type( 'post_type', $args ); } add_action( 'init', 'news_post', 0 ); } </code></pre> <p>Any idea about how to fix that?</p>
[ { "answer_id": 236851, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 5, "selected": true, "text": "<p>I see, when you enter a link to your page other than your home, example:</p>\n\n<ul>\n<li><code>http://www.michaelcropper.co.uk/contact-me</code></li>\n<li><code>www.michaelcropper.co.uk/contact-me</code></li>\n<li><code>michaelcropper.co.uk/contact-me</code></li>\n</ul>\n\n<p>If <code>https://</code> is not in the prefix, the HTTP link loads instead. Add the following into your <code>.htaccess</code> in between the <code>&lt;IfModule mod_rewrite.c&gt;</code> tag:</p>\n\n<pre><code>RewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n</code></pre>\n\n<p>If there were no additional modifications done to your <code>.htaccess</code>, it should look like the following:</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n# Rewrite HTTP to HTTPS\nRewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n\n<p>Let me know how it goes.</p>\n" }, { "answer_id": 304626, "author": "zihadul", "author_id": 121562, "author_profile": "https://wordpress.stackexchange.com/users/121562", "pm_score": 0, "selected": false, "text": "<p>Just Add this in your .htaccess file</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\n\nRewriteCond %{HTTPS} !=on\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n" }, { "answer_id": 308977, "author": "Chris Sprague", "author_id": 140665, "author_profile": "https://wordpress.stackexchange.com/users/140665", "pm_score": 0, "selected": false, "text": "<p>If you are using W3 Total Cache the answer from @Ethan Jinks O'Sullivan will only work if you place the redirect before the W3 Total Cache mods in .htaccess as shown below</p>\n\n<pre><code>#BEGIN Rewrite HTTP to HTTPS\n&lt;IfModule mod_rewrite.c&gt;\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n#END Rewrite HTTP to HTTPS\n\n# BEGIN GZIP COMPRESSION\n...\n# END GZIP COMPRESSION\n\n# BEGIN DEFLATE COMPRESSION\n...\n# END DEFLATE COMPRESSION\n\n# BEGIN W3TC Browser Cache\n...\n# END W3TC Browser Cache\n\n# BEGIN W3TC Page Cache core\n...\n# END W3TC Page Cache core\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n RewriteRule ^index\\.php$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 313890, "author": "Iggy", "author_id": 32150, "author_profile": "https://wordpress.stackexchange.com/users/32150", "pm_score": 2, "selected": false, "text": "<p>You can set header in .htaccess</p>\n\n<pre><code>&lt;IfModule mod_headers.c&gt;\n Header always set Strict-Transport-Security \"max-age=31536000; includeSubDomains\" env=HTTPS\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 314604, "author": "Jasom Dotnet", "author_id": 50021, "author_profile": "https://wordpress.stackexchange.com/users/50021", "pm_score": 2, "selected": false, "text": "<p>try this in your <code>.htaccess</code>:</p>\n\n<pre><code>RewriteCond %{HTTP:X-Forwarded-Proto} !=https\nRewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 328976, "author": "Siddharth Shukla", "author_id": 141854, "author_profile": "https://wordpress.stackexchange.com/users/141854", "pm_score": 3, "selected": false, "text": "<p>Add code within a .htaccess file </p>\n\n<pre><code> &lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n\n RewriteCond %{HTTPS} !=on\n RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\n # BEGIN WordPress\n RewriteRule ^index\\.php$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n &lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 341789, "author": "user3469142", "author_id": 170968, "author_profile": "https://wordpress.stackexchange.com/users/170968", "pm_score": -1, "selected": false, "text": "<p>Toke me 10 minutes to fix the issue</p>\n\n<p>Add a conf file for your domain.</p>\n\n<p>Go to centos 7 at <code>/etc/httpd/conf.d/</code>, then create a conf file called <code>anything.conf</code>.</p>\n\n<p>Put the following code on it:</p>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n ServerName domain.com\n ServerAlias www.domain.com\n ServerAdmin [email protected]\n DocumentRoot /var/www/html\n\n &lt;Directory /var/www/html&gt;\n Options -Indexes +FollowSymLinks\n AllowOverride All\n &lt;/Directory&gt;\n\n ErrorLog /var/log/httpd/example.com-error.log\n CustomLog /var/log/httpd/example.com-access.log combined\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>Replace <code>example.com</code> with your domain.<br>\nThen add the https rewrite code on .htaccess its will work. :)</p>\n" }, { "answer_id": 345004, "author": "vvvvv", "author_id": 173420, "author_profile": "https://wordpress.stackexchange.com/users/173420", "pm_score": -1, "selected": false, "text": "<pre><code>#BEGIN Rewrite HTTP to HTTPS\n&lt;IfModule mod_rewrite.c&gt;\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n#END Rewrite HTTP to HTTPS\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n RewriteRule ^index\\.php$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 351986, "author": "vin decode", "author_id": 177922, "author_profile": "https://wordpress.stackexchange.com/users/177922", "pm_score": 0, "selected": false, "text": "<p>If you don't want to change anything on .htaccess you may try this out</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', 'redirect_core', 50);\nadd_action('init', 'redirect_core', 50);\nadd_action('wp_loaded', 'redirect_core', 50);\nfunction redirect_core(){\n if (!is_ssl()) {\n wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301);\n exit();\n }\n}\n</code></pre>\n\n<p>Or try this plugin: <a href=\"https://github.com/vindecodex/wp-https-redirect/blob/master/https-redirect.php\" rel=\"nofollow noreferrer\">HTTPS Redirect</a></p>\n" } ]
2016/08/22
[ "https://wordpress.stackexchange.com/questions/236739", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101437/" ]
After severall search, maybe without the right english terms, I come here to find an answer to my problem. I have a theme that I created on my website, everything is working perfectly for the last 6 months. I also have a custom post type to add some twitch channel on my website and display them. Yesterday, I created a new custom post type to write some fast news so just the minimal content : title, content, author and revisions. But when I add this one to my website, the Posts, Streams, News and Pages list become empty with a "not found" message even when there is some content with this post type. Like this : [![Empty list](https://i.stack.imgur.com/tpZOn.png)](https://i.stack.imgur.com/tpZOn.png) I think I already had this bug a long time ago but I can't remember how to fix it. I tried to desactivate my every plugin one by one but the bug was still there. Here is the code of my Custom Post Type (created with GenerateWP to save a lot of time) : ``` if ( ! function_exists('news_post') ) { function news_post() { $labels = array( 'name' => _x( 'News', 'Post Type General Name', 'text_domain' ), 'singular_name' => _x( 'News', 'Post Type Singular Name', 'text_domain' ), 'menu_name' => __( 'News', 'text_domain' ), 'name_admin_bar' => __( 'News', 'text_domain' ), 'archives' => __( 'Item Archives', 'text_domain' ), 'parent_item_colon' => __( 'Parent News:', 'text_domain' ), 'all_items' => __( 'All News', 'text_domain' ), 'add_new_item' => __( 'Add New News', 'text_domain' ), 'add_new' => __( 'Add News', 'text_domain' ), 'new_item' => __( 'New News', 'text_domain' ), 'edit_item' => __( 'Edit News', 'text_domain' ), 'update_item' => __( 'Update News', 'text_domain' ), 'view_item' => __( 'View News', 'text_domain' ), 'search_items' => __( 'Search News', 'text_domain' ), 'not_found' => __( 'Not found', 'text_domain' ), 'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ), 'featured_image' => __( 'Featured Image', 'text_domain' ), 'set_featured_image' => __( 'Set featured image', 'text_domain' ), 'remove_featured_image' => __( 'Remove featured image', 'text_domain' ), 'use_featured_image' => __( 'Use as featured image', 'text_domain' ), 'insert_into_item' => __( 'Insert into News', 'text_domain' ), 'uploaded_to_this_item' => __( 'Uploaded to this News', 'text_domain' ), 'items_list' => __( 'News list', 'text_domain' ), 'items_list_navigation' => __( 'News list navigation', 'text_domain' ), 'filter_items_list' => __( 'Filter News list', 'text_domain' ), ); $args = array( 'label' => __( 'News', 'text_domain' ), 'description' => __( 'News Post Type', 'text_domain' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'author', 'revisions', ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'post', ); register_post_type( 'post_type', $args ); } add_action( 'init', 'news_post', 0 ); } ``` Any idea about how to fix that?
I see, when you enter a link to your page other than your home, example: * `http://www.michaelcropper.co.uk/contact-me` * `www.michaelcropper.co.uk/contact-me` * `michaelcropper.co.uk/contact-me` If `https://` is not in the prefix, the HTTP link loads instead. Add the following into your `.htaccess` in between the `<IfModule mod_rewrite.c>` tag: ``` RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] ``` If there were no additional modifications done to your `.htaccess`, it should look like the following: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # Rewrite HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] </IfModule> # END WordPress ``` Let me know how it goes.
236,745
<p>I'm trying to move a Wordpress installation in a web hosting to a localhost installation for development. I followed <a href="http://www.wpbeginner.com/wp-tutorials/how-to-move-live-wordpress-site-to-local-server/" rel="nofollow">this tutorial</a> (Section <em>Manually Move a Live WordPress Site to Local Server</em>, for now I'm not allowed to install plugins, so I must do it manually).</p> <p>I'm using <a href="https://www.mamp.info/en/" rel="nofollow">MAMP Free edition</a> and followed all the steps in the aforementioned tutorial. But when I tried to open the site in the local installation I got the message (In Safari):</p> <blockquote> <p>Safari cannot open the page "localhost/sitename" because cannot be connected to server "localhost"</p> </blockquote> <p>MAMP load sites in <code>localhost:8888/&lt;site-name&gt;</code> so i executed:</p> <pre><code>UPDATE wp_options SET option_value = replace(option_value, 'http://www.thesite.com', 'http://localhost:8888/localsite') WHERE option_name = 'home' OR option_name = 'siteurl'; </code></pre> <p>where <code>thesite</code> is the name in the web hosting and <code>localsite</code> is the name of the folder in <code>MAMP/htdocs/</code> where I moved the site's files.</p> <p>The only weird thing I noted is that the exported DB from the live site does not have a <code>home</code> option in <code>wp_options</code>. I don't know if it's a required row, but the online site was working without it.</p> <p>What am I missing here? If I followed the tutorial correctly, it should load the site.</p> <p>If you need some more info about the problem just let me know. Thanks in advance for your answers.</p>
[ { "answer_id": 236851, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 5, "selected": true, "text": "<p>I see, when you enter a link to your page other than your home, example:</p>\n\n<ul>\n<li><code>http://www.michaelcropper.co.uk/contact-me</code></li>\n<li><code>www.michaelcropper.co.uk/contact-me</code></li>\n<li><code>michaelcropper.co.uk/contact-me</code></li>\n</ul>\n\n<p>If <code>https://</code> is not in the prefix, the HTTP link loads instead. Add the following into your <code>.htaccess</code> in between the <code>&lt;IfModule mod_rewrite.c&gt;</code> tag:</p>\n\n<pre><code>RewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n</code></pre>\n\n<p>If there were no additional modifications done to your <code>.htaccess</code>, it should look like the following:</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n# Rewrite HTTP to HTTPS\nRewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n\n<p>Let me know how it goes.</p>\n" }, { "answer_id": 304626, "author": "zihadul", "author_id": 121562, "author_profile": "https://wordpress.stackexchange.com/users/121562", "pm_score": 0, "selected": false, "text": "<p>Just Add this in your .htaccess file</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\n\nRewriteCond %{HTTPS} !=on\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n" }, { "answer_id": 308977, "author": "Chris Sprague", "author_id": 140665, "author_profile": "https://wordpress.stackexchange.com/users/140665", "pm_score": 0, "selected": false, "text": "<p>If you are using W3 Total Cache the answer from @Ethan Jinks O'Sullivan will only work if you place the redirect before the W3 Total Cache mods in .htaccess as shown below</p>\n\n<pre><code>#BEGIN Rewrite HTTP to HTTPS\n&lt;IfModule mod_rewrite.c&gt;\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n#END Rewrite HTTP to HTTPS\n\n# BEGIN GZIP COMPRESSION\n...\n# END GZIP COMPRESSION\n\n# BEGIN DEFLATE COMPRESSION\n...\n# END DEFLATE COMPRESSION\n\n# BEGIN W3TC Browser Cache\n...\n# END W3TC Browser Cache\n\n# BEGIN W3TC Page Cache core\n...\n# END W3TC Page Cache core\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n RewriteRule ^index\\.php$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 313890, "author": "Iggy", "author_id": 32150, "author_profile": "https://wordpress.stackexchange.com/users/32150", "pm_score": 2, "selected": false, "text": "<p>You can set header in .htaccess</p>\n\n<pre><code>&lt;IfModule mod_headers.c&gt;\n Header always set Strict-Transport-Security \"max-age=31536000; includeSubDomains\" env=HTTPS\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 314604, "author": "Jasom Dotnet", "author_id": 50021, "author_profile": "https://wordpress.stackexchange.com/users/50021", "pm_score": 2, "selected": false, "text": "<p>try this in your <code>.htaccess</code>:</p>\n\n<pre><code>RewriteCond %{HTTP:X-Forwarded-Proto} !=https\nRewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 328976, "author": "Siddharth Shukla", "author_id": 141854, "author_profile": "https://wordpress.stackexchange.com/users/141854", "pm_score": 3, "selected": false, "text": "<p>Add code within a .htaccess file </p>\n\n<pre><code> &lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n\n RewriteCond %{HTTPS} !=on\n RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\n # BEGIN WordPress\n RewriteRule ^index\\.php$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n &lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 341789, "author": "user3469142", "author_id": 170968, "author_profile": "https://wordpress.stackexchange.com/users/170968", "pm_score": -1, "selected": false, "text": "<p>Toke me 10 minutes to fix the issue</p>\n\n<p>Add a conf file for your domain.</p>\n\n<p>Go to centos 7 at <code>/etc/httpd/conf.d/</code>, then create a conf file called <code>anything.conf</code>.</p>\n\n<p>Put the following code on it:</p>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n ServerName domain.com\n ServerAlias www.domain.com\n ServerAdmin [email protected]\n DocumentRoot /var/www/html\n\n &lt;Directory /var/www/html&gt;\n Options -Indexes +FollowSymLinks\n AllowOverride All\n &lt;/Directory&gt;\n\n ErrorLog /var/log/httpd/example.com-error.log\n CustomLog /var/log/httpd/example.com-access.log combined\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>Replace <code>example.com</code> with your domain.<br>\nThen add the https rewrite code on .htaccess its will work. :)</p>\n" }, { "answer_id": 345004, "author": "vvvvv", "author_id": 173420, "author_profile": "https://wordpress.stackexchange.com/users/173420", "pm_score": -1, "selected": false, "text": "<pre><code>#BEGIN Rewrite HTTP to HTTPS\n&lt;IfModule mod_rewrite.c&gt;\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n#END Rewrite HTTP to HTTPS\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteBase /\n RewriteRule ^index\\.php$ - [L]\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 351986, "author": "vin decode", "author_id": 177922, "author_profile": "https://wordpress.stackexchange.com/users/177922", "pm_score": 0, "selected": false, "text": "<p>If you don't want to change anything on .htaccess you may try this out</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', 'redirect_core', 50);\nadd_action('init', 'redirect_core', 50);\nadd_action('wp_loaded', 'redirect_core', 50);\nfunction redirect_core(){\n if (!is_ssl()) {\n wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301);\n exit();\n }\n}\n</code></pre>\n\n<p>Or try this plugin: <a href=\"https://github.com/vindecodex/wp-https-redirect/blob/master/https-redirect.php\" rel=\"nofollow noreferrer\">HTTPS Redirect</a></p>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236745", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100952/" ]
I'm trying to move a Wordpress installation in a web hosting to a localhost installation for development. I followed [this tutorial](http://www.wpbeginner.com/wp-tutorials/how-to-move-live-wordpress-site-to-local-server/) (Section *Manually Move a Live WordPress Site to Local Server*, for now I'm not allowed to install plugins, so I must do it manually). I'm using [MAMP Free edition](https://www.mamp.info/en/) and followed all the steps in the aforementioned tutorial. But when I tried to open the site in the local installation I got the message (In Safari): > > Safari cannot open the page "localhost/sitename" because cannot be connected to server "localhost" > > > MAMP load sites in `localhost:8888/<site-name>` so i executed: ``` UPDATE wp_options SET option_value = replace(option_value, 'http://www.thesite.com', 'http://localhost:8888/localsite') WHERE option_name = 'home' OR option_name = 'siteurl'; ``` where `thesite` is the name in the web hosting and `localsite` is the name of the folder in `MAMP/htdocs/` where I moved the site's files. The only weird thing I noted is that the exported DB from the live site does not have a `home` option in `wp_options`. I don't know if it's a required row, but the online site was working without it. What am I missing here? If I followed the tutorial correctly, it should load the site. If you need some more info about the problem just let me know. Thanks in advance for your answers.
I see, when you enter a link to your page other than your home, example: * `http://www.michaelcropper.co.uk/contact-me` * `www.michaelcropper.co.uk/contact-me` * `michaelcropper.co.uk/contact-me` If `https://` is not in the prefix, the HTTP link loads instead. Add the following into your `.htaccess` in between the `<IfModule mod_rewrite.c>` tag: ``` RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] ``` If there were no additional modifications done to your `.htaccess`, it should look like the following: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # Rewrite HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] </IfModule> # END WordPress ``` Let me know how it goes.
236,761
<p>I've tried </p> <pre><code>&lt;?php $trimmed = wp_trim_words( get_the_content(), 55, "" ); ?&gt; &lt;?php echo $trimmed; ?&gt; </code></pre> <p>and </p> <pre><code>&lt;?php $trimmed = wp_trim_words( the_content(), 55, "" ); ?&gt; &lt;?php echo $trimmed; ?&gt; </code></pre> <p>the second option with <code>the_content</code> does not work as expected.</p> <p>Some posts have a video in the content and when the formatting is stripped the embed code shows. </p> <p>EDIT: I'll try to be more clear, the author has written posts with images, links to external images, videos, text, formatted wysiwyg text, etc. all in the main content field of a normal post. So all those things I just mentioned exist in the_content. </p> <p>What the author has NOT done is used the excerpt field, or the tag and created really long posts. So I'm trying to create a page of those posts that are trimmed. </p>
[ { "answer_id": 236775, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 1, "selected": false, "text": "<p>Well, as far I understood you want to remove all the HTML tags from the trimmed <code>the_content</code>. Right??? </p>\n\n<p>Try <code>wp_filter_nohtml_kses</code> function. Hope that's going to work. Here is the full code-</p>\n\n<pre><code>&lt;?php $trimmed = wp_filter_nohtml_kses( wp_trim_words( get_the_content(), 55, \"\" ) ); ?&gt;\n&lt;?php echo $trimmed; ?&gt;\n</code></pre>\n" }, { "answer_id": 412755, "author": "Hayder Hossain", "author_id": 226249, "author_profile": "https://wordpress.stackexchange.com/users/226249", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php echo force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 40 ) ) ); ?&gt;\n</code></pre>\n<p>This code working for me to Trim content without stripping formatting</p>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236761", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82731/" ]
I've tried ``` <?php $trimmed = wp_trim_words( get_the_content(), 55, "" ); ?> <?php echo $trimmed; ?> ``` and ``` <?php $trimmed = wp_trim_words( the_content(), 55, "" ); ?> <?php echo $trimmed; ?> ``` the second option with `the_content` does not work as expected. Some posts have a video in the content and when the formatting is stripped the embed code shows. EDIT: I'll try to be more clear, the author has written posts with images, links to external images, videos, text, formatted wysiwyg text, etc. all in the main content field of a normal post. So all those things I just mentioned exist in the\_content. What the author has NOT done is used the excerpt field, or the tag and created really long posts. So I'm trying to create a page of those posts that are trimmed.
Well, as far I understood you want to remove all the HTML tags from the trimmed `the_content`. Right??? Try `wp_filter_nohtml_kses` function. Hope that's going to work. Here is the full code- ``` <?php $trimmed = wp_filter_nohtml_kses( wp_trim_words( get_the_content(), 55, "" ) ); ?> <?php echo $trimmed; ?> ```
236,804
<p>I am adding the below code for the email notification when my wordpress site fas fatal error or other. But I am not getting the email when I rename the load.php file(i.e when fatal error occurs)</p> <pre><code>do_action( 'shutdown', $array ); function action_shutdown($array) { $err = error_get_last(); if ( !$err) { return; } $fatals = array( E_USER_ERROR =&gt; 'Fatal Error', E_ERROR =&gt; 'Fatal Error', E_PARSE =&gt; 'Parse Error', E_CORE_ERROR =&gt; 'Core Error', E_CORE_WARNING =&gt; 'Core Warning', E_COMPILE_ERROR =&gt; 'Compile Error', E_COMPILE_WARNING =&gt; 'Compile Warning' ); if (isset($fatals[$err['type']])) { $msg = $fatals[$err['type']] . ': ' . $err['message'] . ' in '; $msg.= $err['file'] . ' on line ' . $err['line']; $headers = "From: [email protected]\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; error_log($msg, 1, "[email protected]", $headers); } } add_action( 'shutdown', 'action_shutdown', 10, 1 ); </code></pre> <p>I am adding this code in function.php file of theme. when error occurs on site it will not go inside the called function. but if running without error it is entering the called function. please tell me where i am wrong or using correct function.</p>
[ { "answer_id": 236825, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>I think you are misusing <code>shutdown</code> hook. WP attaches it to use with <code>register_shutdown_function()</code> and it's meant to process end of script execution, not log/process errors.</p>\n\n<p>If you want to handle errors in a custom way you are better off using generic PHP <code>set_error_handler()</code> which is meant for that.</p>\n" }, { "answer_id": 236829, "author": "Xavier Serrano", "author_id": 24921, "author_profile": "https://wordpress.stackexchange.com/users/24921", "pm_score": 0, "selected": false, "text": "<p>there are a couple errors/questions with your code.</p>\n\n<ol>\n<li>why are you using two do_actions( 'shutdown')? </li>\n<li>why does the action have an argument $array? </li>\n<li>where is the argument $array being set? </li>\n<li>why are the actions right next to your function on the functions.php file at that point you can simply add and call the function?</li>\n</ol>\n\n<p>do_actions are hooks meant to give someone a way to hook into the WordPress event driven process in order to perform actions or alter current actions. meaning where ever you see a do_action() you can hook into and execute code. the arguments are meant to be able to do/alter something using those arguments. the arguments are passed by the do_action to the add_action callback function. </p>\n" }, { "answer_id": 299828, "author": "Jack Arturo", "author_id": 77576, "author_profile": "https://wordpress.stackexchange.com/users/77576", "pm_score": 0, "selected": false, "text": "<p>For anyone interested, I've released a plugin that does this, at <a href=\"https://wordpress.org/plugins/fatal-error-notify/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/fatal-error-notify/</a>. It hooks into PHP's <code>register_shutdown_function()</code> to handle the notifications. Check out <code>/includes/class-public.php</code> to see how it works.</p>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101207/" ]
I am adding the below code for the email notification when my wordpress site fas fatal error or other. But I am not getting the email when I rename the load.php file(i.e when fatal error occurs) ``` do_action( 'shutdown', $array ); function action_shutdown($array) { $err = error_get_last(); if ( !$err) { return; } $fatals = array( E_USER_ERROR => 'Fatal Error', E_ERROR => 'Fatal Error', E_PARSE => 'Parse Error', E_CORE_ERROR => 'Core Error', E_CORE_WARNING => 'Core Warning', E_COMPILE_ERROR => 'Compile Error', E_COMPILE_WARNING => 'Compile Warning' ); if (isset($fatals[$err['type']])) { $msg = $fatals[$err['type']] . ': ' . $err['message'] . ' in '; $msg.= $err['file'] . ' on line ' . $err['line']; $headers = "From: [email protected]\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; error_log($msg, 1, "[email protected]", $headers); } } add_action( 'shutdown', 'action_shutdown', 10, 1 ); ``` I am adding this code in function.php file of theme. when error occurs on site it will not go inside the called function. but if running without error it is entering the called function. please tell me where i am wrong or using correct function.
I think you are misusing `shutdown` hook. WP attaches it to use with `register_shutdown_function()` and it's meant to process end of script execution, not log/process errors. If you want to handle errors in a custom way you are better off using generic PHP `set_error_handler()` which is meant for that.
236,812
<p>I just put my website on the Web and noticed that the menu is not really working.Nothing happens when I click on it and when Inspect the element s I actually don't see the scripts. All works perfectly in the localhost though.</p> <p>Here my function.php:</p> <pre><code>function scentology_scripts() { wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' ); wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); // wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true ); wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/menu.js', array('jquery')); wp_enqueue_script( 'scentology-menu'); wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true ); wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true ); if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'scentology_scripts' ); </code></pre> <p>and my jquery code:</p> <pre><code>(function( $ ){ $(".burguer-nav").on("click", function() { $("header nav ul").toggleClass("open"); }); })(jQuery); </code></pre> <p>Is there another way for me to load the scripts?</p>
[ { "answer_id": 236819, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": -1, "selected": false, "text": "<p>You need to add your jquery.js file first and then enqueue rest of the JS file.</p>\n\n<p>Updated code : </p>\n\n<pre><code>function scentology_scripts() {\n\n wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' ); \n\n wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );\n\n wp_enqueue_style( 'scentology-style', get_stylesheet_uri() );\n\n wp_enqueue_script( 'jquery' ); \n\n // wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true );\n\n wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/menu.js', array('jquery'));\n wp_enqueue_script( 'scentology-menu');\n wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );\n wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'scentology_scripts' );\n</code></pre>\n" }, { "answer_id": 236824, "author": "Rituparna sonowal", "author_id": 71232, "author_profile": "https://wordpress.stackexchange.com/users/71232", "pm_score": 0, "selected": false, "text": "<pre><code>function scentology_scripts() {\n wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' );\n wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); \n\n wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); \n\n wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/menu.js', array('jquery'), '20151215', true);\n\n wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true );\n\n wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' ); \n }\n}\nadd_action( 'wp_enqueue_scripts', 'scentology_scripts' );\n</code></pre>\n<p>Now add your custom jquery code in navigation.js (or may be a different js file).</p>\n<h1>1 You don't need to enqueue jquery separately.</h1>\n<h1>2 I guess you have confused between <a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\">wp_register_script</a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a>. Read about these two functions to clear your confusion.</h1>\n" }, { "answer_id": 236831, "author": "Xavier Serrano", "author_id": 24921, "author_profile": "https://wordpress.stackexchange.com/users/24921", "pm_score": 0, "selected": false, "text": "<p>it is worth mentioning that you may want to enable the WP_DEBUG constant on the wp-config.php on your local to true. </p>\n\n<p>Also get_template_dir_uri() will work as long as it is the parent theme and not a child, the child theme needs to use get_stylesheet_directory_uri() for scripts present in the child theme folder. finally make sure your sources are where they are supposed to be and for good practice remove any http: https: from hardcoded url sources such as //maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css.</p>\n\n<p>as far as i can tell check your console and check how the scripts are being printed in the footer. there may also be some jquery errors or conflicts. Looks like you are using parts of bootstrap so make sure you are including all the needed scripts for those components to work</p>\n" }, { "answer_id": 237096, "author": "user agent", "author_id": 99178, "author_profile": "https://wordpress.stackexchange.com/users/99178", "pm_score": 1, "selected": false, "text": "<p>I dont really see anything wrong on what I did previously. But in any case I changed the name of the file to navbar.js and then my functions.php looked like this:</p>\n\n<pre><code>function scentology_scripts() {\n wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' );\n wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); \n\n wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); \n\n wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/navbar.js', array('jquery'), '20151215', true);\n\n wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true );\n\n// wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true );\n\n wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' ); \n }\n}\nadd_action( 'wp_enqueue_scripts', 'scentology_scripts' );\n</code></pre>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236812", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99178/" ]
I just put my website on the Web and noticed that the menu is not really working.Nothing happens when I click on it and when Inspect the element s I actually don't see the scripts. All works perfectly in the localhost though. Here my function.php: ``` function scentology_scripts() { wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' ); wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); // wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true ); wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/menu.js', array('jquery')); wp_enqueue_script( 'scentology-menu'); wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true ); wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'scentology_scripts' ); ``` and my jquery code: ``` (function( $ ){ $(".burguer-nav").on("click", function() { $("header nav ul").toggleClass("open"); }); })(jQuery); ``` Is there another way for me to load the scripts?
I dont really see anything wrong on what I did previously. But in any case I changed the name of the file to navbar.js and then my functions.php looked like this: ``` function scentology_scripts() { wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' ); wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/navbar.js', array('jquery'), '20151215', true); wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true ); // wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true ); wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20151215', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'scentology_scripts' ); ```
236,814
<p>I wonder how can finde html/php source to change , word name from Read More to just More.</p> <p><a href="http://www.wyprawykulturowe.pl/2016/08/17/tropikalna-wyspa/" rel="nofollow">http://www.wyprawykulturowe.pl/2016/08/17/tropikalna-wyspa/</a></p> <p>This is the site this image block on bottom have some description and of end of it is Read More that i wanna change to just More . How can i do it?</p> <p>THanks!</p>
[ { "answer_id": 236819, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": -1, "selected": false, "text": "<p>You need to add your jquery.js file first and then enqueue rest of the JS file.</p>\n\n<p>Updated code : </p>\n\n<pre><code>function scentology_scripts() {\n\n wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' ); \n\n wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );\n\n wp_enqueue_style( 'scentology-style', get_stylesheet_uri() );\n\n wp_enqueue_script( 'jquery' ); \n\n // wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true );\n\n wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/menu.js', array('jquery'));\n wp_enqueue_script( 'scentology-menu');\n wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );\n wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'scentology_scripts' );\n</code></pre>\n" }, { "answer_id": 236824, "author": "Rituparna sonowal", "author_id": 71232, "author_profile": "https://wordpress.stackexchange.com/users/71232", "pm_score": 0, "selected": false, "text": "<pre><code>function scentology_scripts() {\n wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' );\n wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); \n\n wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); \n\n wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/menu.js', array('jquery'), '20151215', true);\n\n wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true );\n\n wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' ); \n }\n}\nadd_action( 'wp_enqueue_scripts', 'scentology_scripts' );\n</code></pre>\n<p>Now add your custom jquery code in navigation.js (or may be a different js file).</p>\n<h1>1 You don't need to enqueue jquery separately.</h1>\n<h1>2 I guess you have confused between <a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\">wp_register_script</a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a>. Read about these two functions to clear your confusion.</h1>\n" }, { "answer_id": 236831, "author": "Xavier Serrano", "author_id": 24921, "author_profile": "https://wordpress.stackexchange.com/users/24921", "pm_score": 0, "selected": false, "text": "<p>it is worth mentioning that you may want to enable the WP_DEBUG constant on the wp-config.php on your local to true. </p>\n\n<p>Also get_template_dir_uri() will work as long as it is the parent theme and not a child, the child theme needs to use get_stylesheet_directory_uri() for scripts present in the child theme folder. finally make sure your sources are where they are supposed to be and for good practice remove any http: https: from hardcoded url sources such as //maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css.</p>\n\n<p>as far as i can tell check your console and check how the scripts are being printed in the footer. there may also be some jquery errors or conflicts. Looks like you are using parts of bootstrap so make sure you are including all the needed scripts for those components to work</p>\n" }, { "answer_id": 237096, "author": "user agent", "author_id": 99178, "author_profile": "https://wordpress.stackexchange.com/users/99178", "pm_score": 1, "selected": false, "text": "<p>I dont really see anything wrong on what I did previously. But in any case I changed the name of the file to navbar.js and then my functions.php looked like this:</p>\n\n<pre><code>function scentology_scripts() {\n wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' );\n wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); \n\n wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); \n\n wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/navbar.js', array('jquery'), '20151215', true);\n\n wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true );\n\n// wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true );\n\n wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' ); \n }\n}\nadd_action( 'wp_enqueue_scripts', 'scentology_scripts' );\n</code></pre>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236814", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93972/" ]
I wonder how can finde html/php source to change , word name from Read More to just More. <http://www.wyprawykulturowe.pl/2016/08/17/tropikalna-wyspa/> This is the site this image block on bottom have some description and of end of it is Read More that i wanna change to just More . How can i do it? THanks!
I dont really see anything wrong on what I did previously. But in any case I changed the name of the file to navbar.js and then my functions.php looked like this: ``` function scentology_scripts() { wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' ); wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/navbar.js', array('jquery'), '20151215', true); wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true ); // wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true ); wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20151215', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'scentology_scripts' ); ```
236,816
<p>I want to add the currenty category to the body class.</p> <p>How do I need to modify my current code, to add also the current category as a body class to the <code>is_singular( 'knowledgebase' )</code> section?</p> <p>My current code looks like this:</p> <pre><code>function add_body_class( $classes ) { global $pakb; if( is_page( $pakb-&gt;get( 'kb_page' ) ) &amp;&amp; ! is_null( $pakb-&gt;get( 'kb_page' ) ) ) { $classes[] = 'pakb-main'; } elseif ( is_tax( 'knowledgebase_category' ) ) { $classes[] = 'pakb-category'; } elseif ( is_singular( 'knowledgebase' ) ) { $classes[] = 'pakb-single'; } return $classes; } </code></pre>
[ { "answer_id": 236819, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": -1, "selected": false, "text": "<p>You need to add your jquery.js file first and then enqueue rest of the JS file.</p>\n\n<p>Updated code : </p>\n\n<pre><code>function scentology_scripts() {\n\n wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' ); \n\n wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );\n\n wp_enqueue_style( 'scentology-style', get_stylesheet_uri() );\n\n wp_enqueue_script( 'jquery' ); \n\n // wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true );\n\n wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/menu.js', array('jquery'));\n wp_enqueue_script( 'scentology-menu');\n wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );\n wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'scentology_scripts' );\n</code></pre>\n" }, { "answer_id": 236824, "author": "Rituparna sonowal", "author_id": 71232, "author_profile": "https://wordpress.stackexchange.com/users/71232", "pm_score": 0, "selected": false, "text": "<pre><code>function scentology_scripts() {\n wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' );\n wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); \n\n wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); \n\n wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/menu.js', array('jquery'), '20151215', true);\n\n wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true );\n\n wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' ); \n }\n}\nadd_action( 'wp_enqueue_scripts', 'scentology_scripts' );\n</code></pre>\n<p>Now add your custom jquery code in navigation.js (or may be a different js file).</p>\n<h1>1 You don't need to enqueue jquery separately.</h1>\n<h1>2 I guess you have confused between <a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\">wp_register_script</a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a>. Read about these two functions to clear your confusion.</h1>\n" }, { "answer_id": 236831, "author": "Xavier Serrano", "author_id": 24921, "author_profile": "https://wordpress.stackexchange.com/users/24921", "pm_score": 0, "selected": false, "text": "<p>it is worth mentioning that you may want to enable the WP_DEBUG constant on the wp-config.php on your local to true. </p>\n\n<p>Also get_template_dir_uri() will work as long as it is the parent theme and not a child, the child theme needs to use get_stylesheet_directory_uri() for scripts present in the child theme folder. finally make sure your sources are where they are supposed to be and for good practice remove any http: https: from hardcoded url sources such as //maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css.</p>\n\n<p>as far as i can tell check your console and check how the scripts are being printed in the footer. there may also be some jquery errors or conflicts. Looks like you are using parts of bootstrap so make sure you are including all the needed scripts for those components to work</p>\n" }, { "answer_id": 237096, "author": "user agent", "author_id": 99178, "author_profile": "https://wordpress.stackexchange.com/users/99178", "pm_score": 1, "selected": false, "text": "<p>I dont really see anything wrong on what I did previously. But in any case I changed the name of the file to navbar.js and then my functions.php looked like this:</p>\n\n<pre><code>function scentology_scripts() {\n wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' );\n wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); \n\n wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); \n\n wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/navbar.js', array('jquery'), '20151215', true);\n\n wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true );\n\n// wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true );\n\n wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' ); \n }\n}\nadd_action( 'wp_enqueue_scripts', 'scentology_scripts' );\n</code></pre>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101477/" ]
I want to add the currenty category to the body class. How do I need to modify my current code, to add also the current category as a body class to the `is_singular( 'knowledgebase' )` section? My current code looks like this: ``` function add_body_class( $classes ) { global $pakb; if( is_page( $pakb->get( 'kb_page' ) ) && ! is_null( $pakb->get( 'kb_page' ) ) ) { $classes[] = 'pakb-main'; } elseif ( is_tax( 'knowledgebase_category' ) ) { $classes[] = 'pakb-category'; } elseif ( is_singular( 'knowledgebase' ) ) { $classes[] = 'pakb-single'; } return $classes; } ```
I dont really see anything wrong on what I did previously. But in any case I changed the name of the file to navbar.js and then my functions.php looked like this: ``` function scentology_scripts() { wp_enqueue_style( 'scentology-local-fonts', get_template_directory_uri() . '/fonts/raleway.css' ); wp_enqueue_style( 'scentology-style-fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); wp_enqueue_style( 'scentology-style', get_stylesheet_uri() ); wp_enqueue_script( 'scentology-menu', get_template_directory_uri() . '/js/navbar.js', array('jquery'), '20151215', true); wp_enqueue_script( 'scentology-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true ); // wp_enqueue_script( 'scentology-style', get_template_directory_uri() . '/js/scrollspy.js', array(jquery), '20151215', true ); wp_enqueue_script( 'scentology-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20151215', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'scentology_scripts' ); ```
236,834
<p>I'm looking to create a very simple contact for that I can output with a shortcode. I have the following code, but it doesn't seem to validate properly and even lets you submit the form without inputting any details. Any chance someone could explain how to validate the form please. I would also like to add a honey pot trap as these are better than captures imo but I'm pretty new to PHP. Any help would be great thanks. </p> <pre><code> function html_form_code() { echo '&lt;form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post"&gt;'; echo '&lt;p&gt;'; echo 'Your Name (required) &lt;br /&gt;'; echo '&lt;input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : '' ) . '" size="40" /&gt;'; echo '&lt;/p&gt;'; echo '&lt;p&gt;'; echo 'Your Email (required) &lt;br /&gt;'; echo '&lt;input type="email" name="cf-email" value="' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : '' ) . '" size="40" /&gt;'; echo '&lt;/p&gt;'; echo '&lt;p&gt;'; echo 'Your Message (required) &lt;br /&gt;'; echo '&lt;textarea rows="10" cols="35" name="cf-message"&gt;' . ( isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : '' ) . '&lt;/textarea&gt;'; echo '&lt;/p&gt;'; echo '&lt;input type="text" name="content" id="content" value="" class="hpot" /&gt;'; echo '&lt;p&gt;&lt;input type="submit" name="cf-submitted" value="Send"/&gt;&lt;/p&gt;'; echo '&lt;/form&gt;'; } function deliver_mail() { $errors = new WP_Error(); if ( isset( $_POST[ 'content' ] ) &amp;&amp; $_POST[ 'content' ] !== '' ) { $errors-&gt;add( 'cheater', 'Sorry, this field should not be filled. Are you trying to cheat?' ); } if ( isset( $_POST[ 'cf-name' ] ) &amp;&amp; $_POST[ 'cf-name' ] == '' ) { $errors-&gt;add('error', 'Please fill in a valid name.' ); } if ( isset( $_POST[ 'cf-email' ] ) &amp;&amp; $_POST[ 'cf-email' ] == '' ) { $errors-&gt;add('error', 'Please fill in a valid email.' ); } if ( isset( $_POST[ 'cf-message' ] ) &amp;&amp; $_POST[ 'cf-message' ] == '' ) { $errors-&gt;add('error', 'Please fill in a valid message.' ); } if ( empty( $errors-&gt;errors ) ){ deliver_mail(); } else { echo 'Please fill the required fields'; } // if the submit button is clicked, send the email if ( isset( $_POST['cf-submitted'] ) ) { // sanitize form values $name = sanitize_text_field( $_POST["cf-name"] ); $email = sanitize_email( $_POST["cf-email"] ); $message = esc_textarea( $_POST["cf-message"] ); // get the administrator's email address $to = get_option( 'admin_email' ); $headers = "From: $name &lt;$email&gt;" . "\r\n"; // If email has been process for sending, display a success message if ( wp_mail( $to, $message, $headers ) ) { echo '&lt;div class=cf-success&gt;'; echo '&lt;p&gt;Thank you for contacting us '. $name .', a member of our team will be in touch with you shortly.&lt;/p&gt;'; echo '&lt;/div&gt;'; } else { echo '&lt;div class=cf-error&gt;'; echo '&lt;p&gt;An unexpected error occurred&lt;/p&gt;'; echo '&lt;/div&gt;'; } } } function cf_contact_form() { ob_start(); deliver_mail(); html_form_code(); return ob_get_clean(); } add_shortcode( 'contact_form', 'cf_contact_form' ); </code></pre> <p>So would it be like the above? Thanks </p> <p>I also receive this error when trying to run the field checks.</p> <pre><code>Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in /Applications/MAMP/htdocs/centenary-framework/wp-content/themes/cent_framework/assets/inc/core/contact-form.php on line 147 Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in /Applications/MAMP/htdocs/centenary-framework/wp-includes/load.php on line 671 </code></pre> <p>I'm not to sure what this means. =(</p> <p>EDIT </p> <p>These issues have now been fixed. I'm pasting the working code below in the hope it will help someone in the future. Many thanks to everyone that helped!!</p> <pre><code>// Form markup function html_form_code() { ?&gt; &lt;form action="&lt;?php esc_url($_SERVER['REQUEST_URI']); ?&gt;" method="post"&gt; &lt;p&gt;Your Name (required)&lt;br /&gt; &lt;input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="&lt;?php isset($_POST['cf-name']) ? esc_attr($_POST['cf-name']) : ''; ?&gt;" size="40" /&gt; &lt;/p&gt; &lt;p&gt;Your Email (required)&lt;br /&gt; &lt;input type="email" name="cf-email" value="&lt;?php isset($_POST['cf-email']) ? esc_attr($_POST['cf-email']) : ''; ?&gt;" size="40" /&gt; &lt;/p&gt; &lt;p&gt;Your Message (required)&lt;br /&gt; &lt;textarea rows="10" cols="35" name="cf-message"&gt;&lt;?php isset($_POST['cf-message']) ? esc_attr($_POST['cf-message']) : ''; ?&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;p&gt;&lt;input type="submit" name="cf-submitted" value="Send"/&gt;&lt;/p&gt; &lt;/form&gt; &lt;?php } // Form validation function my_validate_form() { $errors = new WP_Error(); if (isset($_POST[ 'content' ]) &amp;&amp; $_POST[ 'content' ] !== '') { $errors-&gt;add('cheater', 'Sorry, this field should not be filled. Are you trying to cheat?'); } if (isset($_POST[ 'cf-name' ]) &amp;&amp; $_POST[ 'cf-name' ] == '') { $errors-&gt;add('name_error', 'Please fill in a valid name.'); } if (isset($_POST[ 'cf-email' ]) &amp;&amp; $_POST[ 'cf-email' ] == '') { $errors-&gt;add('email_error', 'Please fill in a valid email.'); } if (isset($_POST[ 'cf-message' ]) &amp;&amp; $_POST[ 'cf-message' ] == '') { $errors-&gt;add('message_error', 'Please fill in a valid message.'); } return $errors; } // Form delivery function deliver_mail($args = array()) { // This $default array is a way to initialize some default values that will be overwritten by our $args array. // We could add more keys as we see fit and it's a nice way to see what parameter we are using in our function. // It will only be overwritten with the values of our $args array if the keys are present in $args. // This uses WP wp_parse_args() function. $defaults = array( 'name' =&gt; '', 'email' =&gt; '', 'message' =&gt; '', 'to' =&gt; get_option('admin_email'), // get the administrator's email address ); $args = wp_parse_args($args, $defaults); $headers = "From: {$args['name']} &lt;{$args['email']}&gt;"."\r\n"; // Send email returns true on success, false otherwise if (wp_mail($args['to'], $args['message'], $headers)) { return; } else { return false; } } // Form sanitize function my_sanitize_field($input) { return trim(stripslashes(sanitize_text_field($input))); } // Form succsess message function my_form_message() { global $errors; if (is_wp_error($errors) &amp;&amp; empty($errors-&gt;errors)) { echo '&lt;div class="cf-success"&gt;'; echo '&lt;p&gt;Thank you for contacting us '.$_POST['cf-name'].', a member of our team will be in touch with you shortly.&lt;/p&gt;'; echo '&lt;/div&gt;'; //Empty $_POST because we already sent email $_POST = ''; } else { if (is_wp_error($errors) &amp;&amp; !empty($errors-&gt;errors)) { $error_messages = $errors-&gt;get_error_messages(); foreach ($error_messages as $k =&gt; $message) { echo '&lt;div class="cf-error '.$k.'"&gt;'; echo '&lt;p&gt;'.$message.'&lt;/p&gt;'; echo '&lt;/div&gt;'; } } } } // Form shortcode add_shortcode('contact_form', 'cf_contact_form'); function cf_contact_form() { ob_start(); my_form_message(); html_form_code(); return ob_get_clean(); } // Error validation add_action('init', 'my_cf_form'); function my_cf_form() { if (isset($_POST['cf-submitted'])) { global $errors; $errors = my_validate_form(); if (empty($errors-&gt;errors)) { $args = array( 'name' =&gt; my_sanitize_field($_POST['cf-name']), 'email' =&gt; my_sanitize_field($_POST['cf-email']), 'message' =&gt; my_sanitize_field($_POST['cf-message']), ); deliver_mail($args); } else { return $errors; } } } </code></pre>
[ { "answer_id": 236836, "author": "Greg McMullen", "author_id": 36028, "author_profile": "https://wordpress.stackexchange.com/users/36028", "pm_score": 0, "selected": false, "text": "<p>Since you are somewhat new to PHP, here's a nice example of a <a href=\"http://devgrow.com/simple-php-honey-pot/\" rel=\"nofollow\">simple server side honeypot</a>.</p>\n\n<p>What you'll do is setup a hidden text field in your form and check if it's not empty to catch the spam.</p>\n\n<h2>Form HTML</h2>\n\n<pre><code>&lt;label for=\"honeypot\" class=\"bot\"&gt;Leave blank if you are human&lt;/label&gt;\n&lt;input type=\"text\" id=\"honeypot\" name=\"honeypot\" class=\"bot\" /&gt;\n</code></pre>\n\n<h2>CSS</h2>\n\n<pre><code>.bot { display:none }\n</code></pre>\n\n<h2>PHP (simplified)</h2>\n\n<pre><code> if ( $_POST() ) {\n $name = strip_tags(urldecode(trim($_POST['name'])));\n // OR\n $name = test_input($_POST['name']; \n $honeypot = $_POST('honeypot');\n // Only checks IF something is in it.\n if ($honeypot){\n $msg = \"You are a bot\";\n } else {\n $msg = \"Success\";\n // Additional processing\n if ($name){\n mail(...)\n }\n }\n echo $msg;\n }\n</code></pre>\n\n<p>After a brief search I also found this function that you could use.</p>\n\n<pre><code>function test_input($data) {\n $data = trim($data);\n $data = stripslashes($data);\n $data = htmlspecialchars($data);\n return $data;\n}\n</code></pre>\n" }, { "answer_id": 236839, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<p>You don't have any validation mechanism. </p>\n\n<p>Your logic should be somewhat along those lines</p>\n\n<ul>\n<li>Submit form</li>\n<li>Check submitted fields ($_POST) against expected values</li>\n<li>If all looks good send</li>\n<li>If something is not as expected, log error ( you can use WP_Error() ) and rebuild form showing error message (and maybe repopulating fields with previous \"good\" values).</li>\n</ul>\n\n<p>All I see here is you sanitize the inputs, but you don't actually validate if your inputs have the values you expect (i.e. valid email, phone, length of name, etc.).</p>\n\n<p>You send your email regardless if your fields have the expected values. Your <em>else</em> will output an error <strong>ONLY</strong> if <code>wp_mail()</code> fails, not if your actual fields have validated values or not.</p>\n\n<p>To add an honey pot, you simply need to add an hidden field in your form that you expect to be empty.</p>\n\n<p>For instance, in your HTML</p>\n\n<pre><code>&lt;input type=\"text\" name=\"content\" id=\"content\" value=\"\" class=\"hpot\" /&gt;\n</code></pre>\n\n<p>Then when you validate your form input, you expect that field to be empty.</p>\n\n<p>using <a href=\"https://codex.wordpress.org/Class_Reference/WP_Error\" rel=\"nofollow\"><code>WP_Error</code></a> class you can add errors to the object for later using them to inform the user or whatnot.</p>\n\n<pre><code>$errors = new WP_Error();\nif ( isset( $_POST[ 'content' ] ) &amp;&amp; $_POST[ 'content' ] !== '' ) {\n $errors-&gt;add( 'cheater', 'Sorry, this field should not be filled. Are you trying to cheat?' );\n}\n</code></pre>\n\n<p>So the PHP check above is a way that you could use to validate your form. You simply add some <code>if</code> statements with expected values of your form (of course this can be expanded to function validating your input). Then, if you use WP_Error class, by adding to the object if errors are found, you just have to do a final check before sending.</p>\n\n<pre><code>if ( empty( $errors-&gt;errors ) ){\n deliver_mail();\n}\nelse {\n // Here you can use your $_POST variable to repopulate the form with accepted \n // form value (you would have to update your html_form_code() to accept an argument) \n // or just reload the contact page displaying an error message.\n}\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>Ok so here's a more complete example</p>\n\n<p><strong>CSS</strong></p>\n\n<p>add this to your css so the field is actually not displayed in the browser</p>\n\n<pre><code>.hpot {\n display: none;\n}\n</code></pre>\n\n<p><strong>PHP</strong></p>\n\n<p>Here's another way of writing your html function, it's just easier to read</p>\n\n<pre><code>function html_form_code() { ?&gt;\n\n&lt;form action=\"&lt;?php esc_url( $_SERVER['REQUEST_URI'] ); ?&gt;\" method=\"post\"&gt;\n &lt;p&gt;Your Name (required)&lt;br /&gt;\n &lt;input type=\"text\" name=\"cf-name\" pattern=\"[a-zA-Z0-9 ]+\" value=\"&lt;?php isset( $_POST[\"cf-name\"] ) ? esc_attr( $_POST[\"cf-name\"] ) : ''; ?&gt;\" size=\"40\" /&gt;\n &lt;/p&gt;\n &lt;p&gt;Your Email (required)&lt;br /&gt;\n &lt;input type=\"email\" name=\"cf-email\" value=\"&lt;?php isset( $_POST[\"cf-email\"] ) ? esc_attr( $_POST[\"cf-email\"] ) : ''; ?&gt;\" size=\"40\" /&gt;\n &lt;/p&gt;\n &lt;p&gt;Your Message (required)&lt;br /&gt;\n &lt;textarea rows=\"10\" cols=\"35\" name=\"cf-message\"&gt;&lt;?php isset( $_POST[\"cf-message\"] ) ? esc_attr( $_POST[\"cf-message\"] ) : ''; ?&gt;&lt;/textarea&gt;\n &lt;/p&gt;\n &lt;p&gt;&lt;input type=\"submit\" name=\"cf-submitted\" value=\"Send\"/&gt;&lt;/p&gt;\n&lt;/form&gt;\n\n&lt;?php } \n</code></pre>\n\n<p>Your deliver_mail function should not listen for <code>$_POST</code> and should not sanitize. On a side note, using the forms user email as a <em>from</em> header could cause some issues with some ISP, because the email is sent from <strong>your</strong> domain and now an email is sent from your domain but with non matching domain in the <em>from</em> address (could be seen as spam). Use an address from your domain here (like [email protected]) and set the user's email in the body of the email (in the message). You could also set it as a <code>reply-to</code> field for convenience of use.</p>\n\n<pre><code>function deliver_mail( $args = array() ) {\n\n // This $default array is a way to initialize some default values that will be overwritten by our $args array.\n // We could add more keys as we see fit and it's a nice way to see what parameter we are using in our function.\n // It will only be overwritten with the values of our $args array if the keys are present in $args.\n // This uses WP wp_parse_args() function.\n $defaults = array(\n 'name' =&gt; '',\n 'email' =&gt; '',\n 'message' =&gt; '',\n 'to' =&gt; get_option( 'admin_email' ), // get the administrator's email address\n );\n\n $args = wp_parse_args( $args, $defaults );\n\n $headers = \"From: {$args['name']} &lt;{$args['email']}&gt;\" . \"\\r\\n\";\n\n // Send email returns true on success, false otherwise\n if( wp_mail( $args['to'], $args['message'], $headers ) ) {\n return;\n }\n else {\n return false;\n }\n}\n</code></pre>\n\n<p>Your validation function</p>\n\n<pre><code>function my_validate_form() {\n\n $errors = new WP_Error();\n\n if ( isset( $_POST[ 'content' ] ) &amp;&amp; $_POST[ 'content' ] !== '' ) {\n $errors-&gt;add( 'cheater', 'Sorry, this field should not be filled. Are you trying to cheat?' );\n }\n\n if ( isset( $_POST[ 'cf-name' ] ) &amp;&amp; $_POST[ 'cf-name' ] == '' ) {\n $errors-&gt;add('name_error', 'Please fill in a valid name.' );\n }\n\n if ( isset( $_POST[ 'cf-email' ] ) &amp;&amp; $_POST[ 'cf-email' ] == '' ) {\n $errors-&gt;add('email_error', 'Please fill in a valid email.' );\n }\n\n if ( isset( $_POST[ 'cf-message' ] ) &amp;&amp; $_POST[ 'cf-message' ] == '' ) {\n $errors-&gt;add('message_error', 'Please fill in a valid message.' );\n }\n\n return $errors;\n}\n</code></pre>\n\n<p>Your sanitization function. Here is a general sanitization function trimming white spaces and escaping html, but this could be more complex depending on the input fields you have. But I think for your purpose it's enough</p>\n\n<pre><code>function my_sanitize_field( $input ){\n\n return trim( stripslashes( sanitize_text_field ( $input ) ) );\n\n}\n</code></pre>\n\n<p>Displaying your success/error message, you could use this to retrieve the WP_Error object</p>\n\n<pre><code>function my_form_message(){\n\n global $errors;\n if( is_wp_errors( $errors ) &amp;&amp; empty( $errors-&gt;errors ) ){\n\n echo '&lt;div class=\"cf-success\"&gt;';\n echo '&lt;p&gt;Thank you for contacting us '. $_POST['cf-name'] .', a member of our team will be in touch with you shortly.&lt;/p&gt;';\n echo '&lt;/div&gt;';\n\n //Empty $_POST because we already sent email\n $_POST = '';\n\n }\n else {\n\n if( is_wp_errors( $errors ) &amp;&amp; ! empty( $errors-&gt;errors ) ){\n\n $error_messages = $errors-&gt;get_error_messages(); \n foreach( $error_messages as $k =&gt; $message ){\n echo '&lt;div class=\"cf-error ' . $k . '\"&gt;';\n echo '&lt;p&gt;' . $message . '&lt;/p&gt;';\n echo '&lt;/div&gt;';\n\n }\n\n }\n\n}\n</code></pre>\n\n<p>Finally your shortcode function</p>\n\n<pre><code>add_shortcode( 'contact_form', 'cf_contact_form' );\nfunction cf_contact_form() {\n\n ob_start();\n\n my_form_message();\n html_form_code();\n\n return ob_get_clean();\n}\n</code></pre>\n\n<p>And hooking to <code>init</code> to listen for <code>$_POST</code> before we render our form and output the <code>$errors</code> if we find some or send if all is ok.</p>\n\n<pre><code>add_action( 'init', 'my_cf_form');\nfunction my_cf_form(){\n\n if( isset( $_POST['cf-submitted'] ) ) {\n\n global $errors;\n $errors = my_validate_form(); \n if( empty( $errors-&gt;errors ) ){\n\n $args = array(\n 'name' =&gt; my_sanitize_field( $_POST['cf-name'] ),\n 'email' =&gt; my_sanitize_field( $_POST['cf-email'] ),\n 'message' =&gt; my_sanitize_field( $_POST['cf-message'] ),\n );\n deliver_mail( $args );\n }\n else {\n return $errors;\n } \n }\n}\n</code></pre>\n\n<p>Remember to always prefix your functions so you don't conflict with other plugins function names.</p>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236834", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98778/" ]
I'm looking to create a very simple contact for that I can output with a shortcode. I have the following code, but it doesn't seem to validate properly and even lets you submit the form without inputting any details. Any chance someone could explain how to validate the form please. I would also like to add a honey pot trap as these are better than captures imo but I'm pretty new to PHP. Any help would be great thanks. ``` function html_form_code() { echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">'; echo '<p>'; echo 'Your Name (required) <br />'; echo '<input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : '' ) . '" size="40" />'; echo '</p>'; echo '<p>'; echo 'Your Email (required) <br />'; echo '<input type="email" name="cf-email" value="' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : '' ) . '" size="40" />'; echo '</p>'; echo '<p>'; echo 'Your Message (required) <br />'; echo '<textarea rows="10" cols="35" name="cf-message">' . ( isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : '' ) . '</textarea>'; echo '</p>'; echo '<input type="text" name="content" id="content" value="" class="hpot" />'; echo '<p><input type="submit" name="cf-submitted" value="Send"/></p>'; echo '</form>'; } function deliver_mail() { $errors = new WP_Error(); if ( isset( $_POST[ 'content' ] ) && $_POST[ 'content' ] !== '' ) { $errors->add( 'cheater', 'Sorry, this field should not be filled. Are you trying to cheat?' ); } if ( isset( $_POST[ 'cf-name' ] ) && $_POST[ 'cf-name' ] == '' ) { $errors->add('error', 'Please fill in a valid name.' ); } if ( isset( $_POST[ 'cf-email' ] ) && $_POST[ 'cf-email' ] == '' ) { $errors->add('error', 'Please fill in a valid email.' ); } if ( isset( $_POST[ 'cf-message' ] ) && $_POST[ 'cf-message' ] == '' ) { $errors->add('error', 'Please fill in a valid message.' ); } if ( empty( $errors->errors ) ){ deliver_mail(); } else { echo 'Please fill the required fields'; } // if the submit button is clicked, send the email if ( isset( $_POST['cf-submitted'] ) ) { // sanitize form values $name = sanitize_text_field( $_POST["cf-name"] ); $email = sanitize_email( $_POST["cf-email"] ); $message = esc_textarea( $_POST["cf-message"] ); // get the administrator's email address $to = get_option( 'admin_email' ); $headers = "From: $name <$email>" . "\r\n"; // If email has been process for sending, display a success message if ( wp_mail( $to, $message, $headers ) ) { echo '<div class=cf-success>'; echo '<p>Thank you for contacting us '. $name .', a member of our team will be in touch with you shortly.</p>'; echo '</div>'; } else { echo '<div class=cf-error>'; echo '<p>An unexpected error occurred</p>'; echo '</div>'; } } } function cf_contact_form() { ob_start(); deliver_mail(); html_form_code(); return ob_get_clean(); } add_shortcode( 'contact_form', 'cf_contact_form' ); ``` So would it be like the above? Thanks I also receive this error when trying to run the field checks. ``` Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in /Applications/MAMP/htdocs/centenary-framework/wp-content/themes/cent_framework/assets/inc/core/contact-form.php on line 147 Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in /Applications/MAMP/htdocs/centenary-framework/wp-includes/load.php on line 671 ``` I'm not to sure what this means. =( EDIT These issues have now been fixed. I'm pasting the working code below in the hope it will help someone in the future. Many thanks to everyone that helped!! ``` // Form markup function html_form_code() { ?> <form action="<?php esc_url($_SERVER['REQUEST_URI']); ?>" method="post"> <p>Your Name (required)<br /> <input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="<?php isset($_POST['cf-name']) ? esc_attr($_POST['cf-name']) : ''; ?>" size="40" /> </p> <p>Your Email (required)<br /> <input type="email" name="cf-email" value="<?php isset($_POST['cf-email']) ? esc_attr($_POST['cf-email']) : ''; ?>" size="40" /> </p> <p>Your Message (required)<br /> <textarea rows="10" cols="35" name="cf-message"><?php isset($_POST['cf-message']) ? esc_attr($_POST['cf-message']) : ''; ?></textarea> </p> <p><input type="submit" name="cf-submitted" value="Send"/></p> </form> <?php } // Form validation function my_validate_form() { $errors = new WP_Error(); if (isset($_POST[ 'content' ]) && $_POST[ 'content' ] !== '') { $errors->add('cheater', 'Sorry, this field should not be filled. Are you trying to cheat?'); } if (isset($_POST[ 'cf-name' ]) && $_POST[ 'cf-name' ] == '') { $errors->add('name_error', 'Please fill in a valid name.'); } if (isset($_POST[ 'cf-email' ]) && $_POST[ 'cf-email' ] == '') { $errors->add('email_error', 'Please fill in a valid email.'); } if (isset($_POST[ 'cf-message' ]) && $_POST[ 'cf-message' ] == '') { $errors->add('message_error', 'Please fill in a valid message.'); } return $errors; } // Form delivery function deliver_mail($args = array()) { // This $default array is a way to initialize some default values that will be overwritten by our $args array. // We could add more keys as we see fit and it's a nice way to see what parameter we are using in our function. // It will only be overwritten with the values of our $args array if the keys are present in $args. // This uses WP wp_parse_args() function. $defaults = array( 'name' => '', 'email' => '', 'message' => '', 'to' => get_option('admin_email'), // get the administrator's email address ); $args = wp_parse_args($args, $defaults); $headers = "From: {$args['name']} <{$args['email']}>"."\r\n"; // Send email returns true on success, false otherwise if (wp_mail($args['to'], $args['message'], $headers)) { return; } else { return false; } } // Form sanitize function my_sanitize_field($input) { return trim(stripslashes(sanitize_text_field($input))); } // Form succsess message function my_form_message() { global $errors; if (is_wp_error($errors) && empty($errors->errors)) { echo '<div class="cf-success">'; echo '<p>Thank you for contacting us '.$_POST['cf-name'].', a member of our team will be in touch with you shortly.</p>'; echo '</div>'; //Empty $_POST because we already sent email $_POST = ''; } else { if (is_wp_error($errors) && !empty($errors->errors)) { $error_messages = $errors->get_error_messages(); foreach ($error_messages as $k => $message) { echo '<div class="cf-error '.$k.'">'; echo '<p>'.$message.'</p>'; echo '</div>'; } } } } // Form shortcode add_shortcode('contact_form', 'cf_contact_form'); function cf_contact_form() { ob_start(); my_form_message(); html_form_code(); return ob_get_clean(); } // Error validation add_action('init', 'my_cf_form'); function my_cf_form() { if (isset($_POST['cf-submitted'])) { global $errors; $errors = my_validate_form(); if (empty($errors->errors)) { $args = array( 'name' => my_sanitize_field($_POST['cf-name']), 'email' => my_sanitize_field($_POST['cf-email']), 'message' => my_sanitize_field($_POST['cf-message']), ); deliver_mail($args); } else { return $errors; } } } ```
You don't have any validation mechanism. Your logic should be somewhat along those lines * Submit form * Check submitted fields ($\_POST) against expected values * If all looks good send * If something is not as expected, log error ( you can use WP\_Error() ) and rebuild form showing error message (and maybe repopulating fields with previous "good" values). All I see here is you sanitize the inputs, but you don't actually validate if your inputs have the values you expect (i.e. valid email, phone, length of name, etc.). You send your email regardless if your fields have the expected values. Your *else* will output an error **ONLY** if `wp_mail()` fails, not if your actual fields have validated values or not. To add an honey pot, you simply need to add an hidden field in your form that you expect to be empty. For instance, in your HTML ``` <input type="text" name="content" id="content" value="" class="hpot" /> ``` Then when you validate your form input, you expect that field to be empty. using [`WP_Error`](https://codex.wordpress.org/Class_Reference/WP_Error) class you can add errors to the object for later using them to inform the user or whatnot. ``` $errors = new WP_Error(); if ( isset( $_POST[ 'content' ] ) && $_POST[ 'content' ] !== '' ) { $errors->add( 'cheater', 'Sorry, this field should not be filled. Are you trying to cheat?' ); } ``` So the PHP check above is a way that you could use to validate your form. You simply add some `if` statements with expected values of your form (of course this can be expanded to function validating your input). Then, if you use WP\_Error class, by adding to the object if errors are found, you just have to do a final check before sending. ``` if ( empty( $errors->errors ) ){ deliver_mail(); } else { // Here you can use your $_POST variable to repopulate the form with accepted // form value (you would have to update your html_form_code() to accept an argument) // or just reload the contact page displaying an error message. } ``` **EDIT** Ok so here's a more complete example **CSS** add this to your css so the field is actually not displayed in the browser ``` .hpot { display: none; } ``` **PHP** Here's another way of writing your html function, it's just easier to read ``` function html_form_code() { ?> <form action="<?php esc_url( $_SERVER['REQUEST_URI'] ); ?>" method="post"> <p>Your Name (required)<br /> <input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="<?php isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : ''; ?>" size="40" /> </p> <p>Your Email (required)<br /> <input type="email" name="cf-email" value="<?php isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : ''; ?>" size="40" /> </p> <p>Your Message (required)<br /> <textarea rows="10" cols="35" name="cf-message"><?php isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : ''; ?></textarea> </p> <p><input type="submit" name="cf-submitted" value="Send"/></p> </form> <?php } ``` Your deliver\_mail function should not listen for `$_POST` and should not sanitize. On a side note, using the forms user email as a *from* header could cause some issues with some ISP, because the email is sent from **your** domain and now an email is sent from your domain but with non matching domain in the *from* address (could be seen as spam). Use an address from your domain here (like [email protected]) and set the user's email in the body of the email (in the message). You could also set it as a `reply-to` field for convenience of use. ``` function deliver_mail( $args = array() ) { // This $default array is a way to initialize some default values that will be overwritten by our $args array. // We could add more keys as we see fit and it's a nice way to see what parameter we are using in our function. // It will only be overwritten with the values of our $args array if the keys are present in $args. // This uses WP wp_parse_args() function. $defaults = array( 'name' => '', 'email' => '', 'message' => '', 'to' => get_option( 'admin_email' ), // get the administrator's email address ); $args = wp_parse_args( $args, $defaults ); $headers = "From: {$args['name']} <{$args['email']}>" . "\r\n"; // Send email returns true on success, false otherwise if( wp_mail( $args['to'], $args['message'], $headers ) ) { return; } else { return false; } } ``` Your validation function ``` function my_validate_form() { $errors = new WP_Error(); if ( isset( $_POST[ 'content' ] ) && $_POST[ 'content' ] !== '' ) { $errors->add( 'cheater', 'Sorry, this field should not be filled. Are you trying to cheat?' ); } if ( isset( $_POST[ 'cf-name' ] ) && $_POST[ 'cf-name' ] == '' ) { $errors->add('name_error', 'Please fill in a valid name.' ); } if ( isset( $_POST[ 'cf-email' ] ) && $_POST[ 'cf-email' ] == '' ) { $errors->add('email_error', 'Please fill in a valid email.' ); } if ( isset( $_POST[ 'cf-message' ] ) && $_POST[ 'cf-message' ] == '' ) { $errors->add('message_error', 'Please fill in a valid message.' ); } return $errors; } ``` Your sanitization function. Here is a general sanitization function trimming white spaces and escaping html, but this could be more complex depending on the input fields you have. But I think for your purpose it's enough ``` function my_sanitize_field( $input ){ return trim( stripslashes( sanitize_text_field ( $input ) ) ); } ``` Displaying your success/error message, you could use this to retrieve the WP\_Error object ``` function my_form_message(){ global $errors; if( is_wp_errors( $errors ) && empty( $errors->errors ) ){ echo '<div class="cf-success">'; echo '<p>Thank you for contacting us '. $_POST['cf-name'] .', a member of our team will be in touch with you shortly.</p>'; echo '</div>'; //Empty $_POST because we already sent email $_POST = ''; } else { if( is_wp_errors( $errors ) && ! empty( $errors->errors ) ){ $error_messages = $errors->get_error_messages(); foreach( $error_messages as $k => $message ){ echo '<div class="cf-error ' . $k . '">'; echo '<p>' . $message . '</p>'; echo '</div>'; } } } ``` Finally your shortcode function ``` add_shortcode( 'contact_form', 'cf_contact_form' ); function cf_contact_form() { ob_start(); my_form_message(); html_form_code(); return ob_get_clean(); } ``` And hooking to `init` to listen for `$_POST` before we render our form and output the `$errors` if we find some or send if all is ok. ``` add_action( 'init', 'my_cf_form'); function my_cf_form(){ if( isset( $_POST['cf-submitted'] ) ) { global $errors; $errors = my_validate_form(); if( empty( $errors->errors ) ){ $args = array( 'name' => my_sanitize_field( $_POST['cf-name'] ), 'email' => my_sanitize_field( $_POST['cf-email'] ), 'message' => my_sanitize_field( $_POST['cf-message'] ), ); deliver_mail( $args ); } else { return $errors; } } } ``` Remember to always prefix your functions so you don't conflict with other plugins function names.
236,841
<p>I want to do a small game for the users of my WP site. The game itself will <em>only</em> use the authentication system from WP, but all of its other logic is entirely external.</p> <p>Right now, if I use a standard WordPress page with a custom template (embedding my game's PHP script) it loads, but seems to load too slowly for my users. My game script uses the same database with WP and it is fast. For tests I turned it off (just test output left), but even this "empty" page in WP is too slow.</p> <p>Is it possible to bypass WordPress entirely (i.e. forgo the template system and everything <em>except</em> for the authentication flows) and load my game directly? My first guess would be to host a separate script in the root of my site's installation, but I can't figure out how to use <em>just</em> the authentication components of WordPress - is it possible to use just a single component from the WordPress engine in this way?</p> <p>Maybe there's an alternative way to speed up the page hosting my game's script...</p>
[ { "answer_id": 237848, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 2, "selected": false, "text": "<p>Not sure, but currently in my mind the first solution. Do you need the data from WordPress for the authentication. If you include the <code>wp-load.php</code> you have access to WordPress and his functions, maybe to identifier. But the file to include as static path is not really great and solid.</p>\n\n<pre><code>define( 'WP_USE_THEMES', FALSE );\nrequire( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );\n</code></pre>\n\n<h2>Query and redirect</h2>\n\n<p>You can change the query with a custom value and if this value is existent you can redirect via hook to your game. After this redirect you access to all wp functions, also to check the users. This idea works only in front-end, no solution to change pages in the back-end, only as hint.</p>\n\n<p>The follow source is only an example to enhance the query with a custom string to identifier and redirect to your custom code.</p>\n\n<pre><code>add_filter( 'query_vars', 'fb_plugin_add_trigger', 10, 1 );\nfunction fb_plugin_add_trigger( $vars ) {\n\n $vars[] = 'fb_plugin_trigger';\n return $vars;\n}\n\nadd_action('template_redirect', 'fb_plugin_trigger_check');\nfunction fb_plugin_trigger_check() {\n\n if ( (int) get_query_var('fb_plugin_trigger') === 1 ) {\n\n // Here is your custom code.\n exit();\n }\n}\n</code></pre>\n\n<p>The URL for this trigger is as example <code>example.com/?fb_plugin_trigger=1</code>.</p>\n\n<h2>Custom endpoint</h2>\n\n<p>Also a option there you should try. Add a <a href=\"http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">custom endpoint</a>.</p>\n\n<pre><code>add_action( 'init', 'fb_my_endpoint' );\nfunction fb_my_endpoint() {\n\n add_rewrite_endpoint( 'fb_plugin_trigger', EP_ROOT );\n}\n</code></pre>\n\n<p>After this you will find the value in the url, like <code>example.com/fb_plugin_trigger/</code>. </p>\n\n<p>Small hint, flush the rewrite rules after adding of the endpoint. Also a hint, if you don't use the permalinks, use the function <code>add_query_arg()</code> to add parameters in the url to identifier.</p>\n\n<p>Now you can also parse this value in the query and include your game source.</p>\n\n<pre><code>add_action( 'parse_query', 'fb_parse_query' );\nfunction fb_parse_query( $query ) {\n\n if ( isset( $query-&gt;query_vars['my_api'] ) ) {\n include( plugin_dir_path( __FILE__ ) . 'game/index.php');\n exit;\n }\n}\n</code></pre>\n" }, { "answer_id": 238017, "author": "Jeremy Ross", "author_id": 102007, "author_profile": "https://wordpress.stackexchange.com/users/102007", "pm_score": 1, "selected": false, "text": "<p>I would think the cause of the slowdown would be related to all of the scripts WordPress is loading in wp_head(). If you're running any number of plugins, or any js/css that is render blocking, you'll see a big performance hit.</p>\n\n<p>Try a loading a custom header file like header-mygame.php and replace the <code>get_header()</code> in your template file with <code>get_header('mygame')</code>.</p>\n\n<p>In header-mygame.php, remove wp_head() and anything else that's not needed to run your game. Add back only the dependancies that you need manually with <code>&lt;script&gt;</code> and <code>&lt;link&gt;</code> tags.</p>\n\n<p>You can do the same with <code>get_footer()</code> as WordPress may be enqueuing scripts there as well.</p>\n\n<p>Obviously this is not enqueuing assets in the 'WordPress way' but it seems that the WordPress way is already being circumvented, so...</p>\n" }, { "answer_id": 238381, "author": "Sunny Luthra", "author_id": 33708, "author_profile": "https://wordpress.stackexchange.com/users/33708", "pm_score": 1, "selected": false, "text": "<p>Here are the steps which you can follow to use WP just for Authentication.</p>\n\n<ol>\n<li>Create a separate folder in the root for your code.</li>\n<li>Copy wp-config.php in a separate file and remove <code>require_once ABSPATH . 'wp-settings.php';</code></li>\n<li>Include copied wp-config file in your code</li>\n<li><p>Code a helper function to invoke WP:</p>\n\n<pre><code>function i_need_wp() { \n global $table_prefix;\n require_once ABSPATH . 'wp-settings.php';\n}\n</code></pre></li>\n<li><p>Call <code>i_need_wp()</code> before using WP authentication. </p></li>\n</ol>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101488/" ]
I want to do a small game for the users of my WP site. The game itself will *only* use the authentication system from WP, but all of its other logic is entirely external. Right now, if I use a standard WordPress page with a custom template (embedding my game's PHP script) it loads, but seems to load too slowly for my users. My game script uses the same database with WP and it is fast. For tests I turned it off (just test output left), but even this "empty" page in WP is too slow. Is it possible to bypass WordPress entirely (i.e. forgo the template system and everything *except* for the authentication flows) and load my game directly? My first guess would be to host a separate script in the root of my site's installation, but I can't figure out how to use *just* the authentication components of WordPress - is it possible to use just a single component from the WordPress engine in this way? Maybe there's an alternative way to speed up the page hosting my game's script...
Not sure, but currently in my mind the first solution. Do you need the data from WordPress for the authentication. If you include the `wp-load.php` you have access to WordPress and his functions, maybe to identifier. But the file to include as static path is not really great and solid. ``` define( 'WP_USE_THEMES', FALSE ); require( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' ); ``` Query and redirect ------------------ You can change the query with a custom value and if this value is existent you can redirect via hook to your game. After this redirect you access to all wp functions, also to check the users. This idea works only in front-end, no solution to change pages in the back-end, only as hint. The follow source is only an example to enhance the query with a custom string to identifier and redirect to your custom code. ``` add_filter( 'query_vars', 'fb_plugin_add_trigger', 10, 1 ); function fb_plugin_add_trigger( $vars ) { $vars[] = 'fb_plugin_trigger'; return $vars; } add_action('template_redirect', 'fb_plugin_trigger_check'); function fb_plugin_trigger_check() { if ( (int) get_query_var('fb_plugin_trigger') === 1 ) { // Here is your custom code. exit(); } } ``` The URL for this trigger is as example `example.com/?fb_plugin_trigger=1`. Custom endpoint --------------- Also a option there you should try. Add a [custom endpoint](http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint). ``` add_action( 'init', 'fb_my_endpoint' ); function fb_my_endpoint() { add_rewrite_endpoint( 'fb_plugin_trigger', EP_ROOT ); } ``` After this you will find the value in the url, like `example.com/fb_plugin_trigger/`. Small hint, flush the rewrite rules after adding of the endpoint. Also a hint, if you don't use the permalinks, use the function `add_query_arg()` to add parameters in the url to identifier. Now you can also parse this value in the query and include your game source. ``` add_action( 'parse_query', 'fb_parse_query' ); function fb_parse_query( $query ) { if ( isset( $query->query_vars['my_api'] ) ) { include( plugin_dir_path( __FILE__ ) . 'game/index.php'); exit; } } ```
236,866
<p>I tried use wp-cli theme install with option url from my dropbox link. But unfortunately, I got this problem:</p> <p>PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature</p> <p>This mean my zip file is corrupt. But I tried upload it through wordpress dashboard and it's work good. I tried again with free theme in wordpress.org/themes and it's work good too, so maybe the problem in my vps setting?</p> <p>Maybe someone meet this problem, has resolved it and help me sort it out?</p> <p>Reference: <a href="http://wp-cli.org/commands/theme/install/" rel="nofollow">http://wp-cli.org/commands/theme/install/</a></p>
[ { "answer_id": 237848, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 2, "selected": false, "text": "<p>Not sure, but currently in my mind the first solution. Do you need the data from WordPress for the authentication. If you include the <code>wp-load.php</code> you have access to WordPress and his functions, maybe to identifier. But the file to include as static path is not really great and solid.</p>\n\n<pre><code>define( 'WP_USE_THEMES', FALSE );\nrequire( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );\n</code></pre>\n\n<h2>Query and redirect</h2>\n\n<p>You can change the query with a custom value and if this value is existent you can redirect via hook to your game. After this redirect you access to all wp functions, also to check the users. This idea works only in front-end, no solution to change pages in the back-end, only as hint.</p>\n\n<p>The follow source is only an example to enhance the query with a custom string to identifier and redirect to your custom code.</p>\n\n<pre><code>add_filter( 'query_vars', 'fb_plugin_add_trigger', 10, 1 );\nfunction fb_plugin_add_trigger( $vars ) {\n\n $vars[] = 'fb_plugin_trigger';\n return $vars;\n}\n\nadd_action('template_redirect', 'fb_plugin_trigger_check');\nfunction fb_plugin_trigger_check() {\n\n if ( (int) get_query_var('fb_plugin_trigger') === 1 ) {\n\n // Here is your custom code.\n exit();\n }\n}\n</code></pre>\n\n<p>The URL for this trigger is as example <code>example.com/?fb_plugin_trigger=1</code>.</p>\n\n<h2>Custom endpoint</h2>\n\n<p>Also a option there you should try. Add a <a href=\"http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">custom endpoint</a>.</p>\n\n<pre><code>add_action( 'init', 'fb_my_endpoint' );\nfunction fb_my_endpoint() {\n\n add_rewrite_endpoint( 'fb_plugin_trigger', EP_ROOT );\n}\n</code></pre>\n\n<p>After this you will find the value in the url, like <code>example.com/fb_plugin_trigger/</code>. </p>\n\n<p>Small hint, flush the rewrite rules after adding of the endpoint. Also a hint, if you don't use the permalinks, use the function <code>add_query_arg()</code> to add parameters in the url to identifier.</p>\n\n<p>Now you can also parse this value in the query and include your game source.</p>\n\n<pre><code>add_action( 'parse_query', 'fb_parse_query' );\nfunction fb_parse_query( $query ) {\n\n if ( isset( $query-&gt;query_vars['my_api'] ) ) {\n include( plugin_dir_path( __FILE__ ) . 'game/index.php');\n exit;\n }\n}\n</code></pre>\n" }, { "answer_id": 238017, "author": "Jeremy Ross", "author_id": 102007, "author_profile": "https://wordpress.stackexchange.com/users/102007", "pm_score": 1, "selected": false, "text": "<p>I would think the cause of the slowdown would be related to all of the scripts WordPress is loading in wp_head(). If you're running any number of plugins, or any js/css that is render blocking, you'll see a big performance hit.</p>\n\n<p>Try a loading a custom header file like header-mygame.php and replace the <code>get_header()</code> in your template file with <code>get_header('mygame')</code>.</p>\n\n<p>In header-mygame.php, remove wp_head() and anything else that's not needed to run your game. Add back only the dependancies that you need manually with <code>&lt;script&gt;</code> and <code>&lt;link&gt;</code> tags.</p>\n\n<p>You can do the same with <code>get_footer()</code> as WordPress may be enqueuing scripts there as well.</p>\n\n<p>Obviously this is not enqueuing assets in the 'WordPress way' but it seems that the WordPress way is already being circumvented, so...</p>\n" }, { "answer_id": 238381, "author": "Sunny Luthra", "author_id": 33708, "author_profile": "https://wordpress.stackexchange.com/users/33708", "pm_score": 1, "selected": false, "text": "<p>Here are the steps which you can follow to use WP just for Authentication.</p>\n\n<ol>\n<li>Create a separate folder in the root for your code.</li>\n<li>Copy wp-config.php in a separate file and remove <code>require_once ABSPATH . 'wp-settings.php';</code></li>\n<li>Include copied wp-config file in your code</li>\n<li><p>Code a helper function to invoke WP:</p>\n\n<pre><code>function i_need_wp() { \n global $table_prefix;\n require_once ABSPATH . 'wp-settings.php';\n}\n</code></pre></li>\n<li><p>Call <code>i_need_wp()</code> before using WP authentication. </p></li>\n</ol>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236866", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57367/" ]
I tried use wp-cli theme install with option url from my dropbox link. But unfortunately, I got this problem: PCLZIP\_ERR\_BAD\_FORMAT (-10) : Unable to find End of Central Dir Record signature This mean my zip file is corrupt. But I tried upload it through wordpress dashboard and it's work good. I tried again with free theme in wordpress.org/themes and it's work good too, so maybe the problem in my vps setting? Maybe someone meet this problem, has resolved it and help me sort it out? Reference: <http://wp-cli.org/commands/theme/install/>
Not sure, but currently in my mind the first solution. Do you need the data from WordPress for the authentication. If you include the `wp-load.php` you have access to WordPress and his functions, maybe to identifier. But the file to include as static path is not really great and solid. ``` define( 'WP_USE_THEMES', FALSE ); require( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' ); ``` Query and redirect ------------------ You can change the query with a custom value and if this value is existent you can redirect via hook to your game. After this redirect you access to all wp functions, also to check the users. This idea works only in front-end, no solution to change pages in the back-end, only as hint. The follow source is only an example to enhance the query with a custom string to identifier and redirect to your custom code. ``` add_filter( 'query_vars', 'fb_plugin_add_trigger', 10, 1 ); function fb_plugin_add_trigger( $vars ) { $vars[] = 'fb_plugin_trigger'; return $vars; } add_action('template_redirect', 'fb_plugin_trigger_check'); function fb_plugin_trigger_check() { if ( (int) get_query_var('fb_plugin_trigger') === 1 ) { // Here is your custom code. exit(); } } ``` The URL for this trigger is as example `example.com/?fb_plugin_trigger=1`. Custom endpoint --------------- Also a option there you should try. Add a [custom endpoint](http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint). ``` add_action( 'init', 'fb_my_endpoint' ); function fb_my_endpoint() { add_rewrite_endpoint( 'fb_plugin_trigger', EP_ROOT ); } ``` After this you will find the value in the url, like `example.com/fb_plugin_trigger/`. Small hint, flush the rewrite rules after adding of the endpoint. Also a hint, if you don't use the permalinks, use the function `add_query_arg()` to add parameters in the url to identifier. Now you can also parse this value in the query and include your game source. ``` add_action( 'parse_query', 'fb_parse_query' ); function fb_parse_query( $query ) { if ( isset( $query->query_vars['my_api'] ) ) { include( plugin_dir_path( __FILE__ ) . 'game/index.php'); exit; } } ```
236,873
<p>Ok, so I have created a custom post type and installed the relevant REST plugins and I have a working JSON feed. </p> <p>What do I do next?</p> <p>Basically, I would like to display a portion of the JSON feed on an existing wordpress page, a bit like doing a <code>wp_query</code> I suppose.</p> <p>Can this be done with AngularJS ? I haven't been able to find any useful tutorials. Any pointers to the right direction would help.</p>
[ { "answer_id": 237256, "author": "Jesús Franco", "author_id": 16301, "author_profile": "https://wordpress.stackexchange.com/users/16301", "pm_score": 1, "selected": false, "text": "<p>Unfortunately I don't know Angular to give you a hand with that, but I'm seeing this question is related to another about <a href=\"https://wordpress.stackexchange.com/questions/237167/create-filtered-list-of-posts-using-json-data\">consuming an endpoint with a filter by meta_key</a> (by the way, I've updated my previous response with a very simple jQuery-only code to show posts retrieved in a list).</p>\n\n<p>However, if you don't mind an example with another library, I used to learn my first steps with React (lesser learning curve than Angular), a simple function to show the last published posts in a simple widget.</p>\n\n<pre><code>(function ( $ ) {\n var resourceUrl = 'http://example.com/wp-json/wp/v2/posts/';\n function refreshLastEntries() {\n var results = [];\n var link, item;\n $.get(\n resourceUrl,\n function (response) {\n console.log(\"Received \" \n + response.length + \" elements\");\n for(item = 0; item &lt; response.length; item++) {\n link = React.DOM.p({}, React.DOM.a({\n style:{\"textDecoration\":\"none\"},\n href:response[item].link\n }, response[item].title.rendered));\n results.push(link);\n }\n ReactDOM.render(React.DOM.div({}, results),\n document.getElementById('reactor'));\n }\n );\n setTimeout(refreshLastEntries, 10000); \n }\n refreshLastEntries();\n\n})(jQuery);\n</code></pre>\n\n<p>If you <strong>really</strong> want learn to use the REST API with Angular, I recommend you again visit the blog I've linked to you in the other question, since that lady has an entire feed about <a href=\"https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/\" rel=\"nofollow noreferrer\" title=\"1fix.io\">Using AngularJS and JSON API in Your WordPress Theme</a>.</p>\n" }, { "answer_id": 272169, "author": "mediaguru", "author_id": 110568, "author_profile": "https://wordpress.stackexchange.com/users/110568", "pm_score": 0, "selected": false, "text": "<p>Yes this can be done. You will have to study $http in angular JS. Include $http in your controller or directive. Then you can do something like this below. Page ID 199 is the about page for one of my sites:</p>\n\n<pre><code> var url = config.API_URL + \"/wp-json/wp/v2/pages/199\";\n $http.get(url)\n .then(function(response) {\n $scope.page = response.data;\n },\n function error(d) {\n $scope.error = true; // use to show an error message\n });\n</code></pre>\n\n<p>$scope.page contains the data from your page. Then in your html you can show it like this:</p>\n\n<pre><code> &lt;h1&gt;{{page.title}}&lt;/h1&gt;\n &lt;div&gt;{{page.content}}&lt;/div&gt;\n</code></pre>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236873", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
Ok, so I have created a custom post type and installed the relevant REST plugins and I have a working JSON feed. What do I do next? Basically, I would like to display a portion of the JSON feed on an existing wordpress page, a bit like doing a `wp_query` I suppose. Can this be done with AngularJS ? I haven't been able to find any useful tutorials. Any pointers to the right direction would help.
Unfortunately I don't know Angular to give you a hand with that, but I'm seeing this question is related to another about [consuming an endpoint with a filter by meta\_key](https://wordpress.stackexchange.com/questions/237167/create-filtered-list-of-posts-using-json-data) (by the way, I've updated my previous response with a very simple jQuery-only code to show posts retrieved in a list). However, if you don't mind an example with another library, I used to learn my first steps with React (lesser learning curve than Angular), a simple function to show the last published posts in a simple widget. ``` (function ( $ ) { var resourceUrl = 'http://example.com/wp-json/wp/v2/posts/'; function refreshLastEntries() { var results = []; var link, item; $.get( resourceUrl, function (response) { console.log("Received " + response.length + " elements"); for(item = 0; item < response.length; item++) { link = React.DOM.p({}, React.DOM.a({ style:{"textDecoration":"none"}, href:response[item].link }, response[item].title.rendered)); results.push(link); } ReactDOM.render(React.DOM.div({}, results), document.getElementById('reactor')); } ); setTimeout(refreshLastEntries, 10000); } refreshLastEntries(); })(jQuery); ``` If you **really** want learn to use the REST API with Angular, I recommend you again visit the blog I've linked to you in the other question, since that lady has an entire feed about [Using AngularJS and JSON API in Your WordPress Theme](https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/ "1fix.io").
236,881
<p>I am currently running an instance of WordPress, version 4.5.3, on an Amazon EC2 server. It uses:</p> <ul> <li>CentOS 7 (OS) and has SELinux enabled.</li> <li>Server runs Apache with <code>mod_security</code> and <code>mod_evasive</code></li> <li>PHP 5.6.24</li> </ul> <p>The site's name is <a href="https://www.ramblingnewyorker.com/" rel="nofollow noreferrer">The Rambling New Yorker</a>. </p> <p>Not long ago I upgraded to SSL using <a href="https://letsencrypt.org/" rel="nofollow noreferrer">Let's Encrypt</a>. The process was fairly simple and I now have the front end secured. I've even installed a plugin which redirects non-SSL traffic to the secure site.</p> <p>Unfortunately, <strong>the admin dashboard is broken</strong>. As soon as I did the switch over it started looking as follows:</p> <p><a href="https://i.stack.imgur.com/jAmSd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jAmSd.png" alt="WordPress SSL Problem"></a></p> <p>I've changed the URLs (in the database, not through the dashboard) to be the SSL version and enabled "<strong>Force SSL Admin</strong>" in the config file. The login page is fine.</p> <p>The switch over once worked when I disabled all plugins. Re-enabling them one by one led me to believe <a href="https://wordpress.org/plugins/wp-super-cache/" rel="nofollow noreferrer">WP Super Cache</a> may be the issue, but when I did the switch over after deleting the plugin, the problem recurred.</p> <p>Disabling <code>mod_security</code> eliminates the problem, but there are no helpful error messages in the Apache error logs so I don't know what's upsetting it.</p> <p>The only clue is that requests for <code>load-styles.php</code> and <code>load-scripts.php</code> return a <code>403 error</code>:</p> <p><a href="https://i.stack.imgur.com/9bvuN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9bvuN.png" alt="WordPress SSL Problem #2"></a></p> <p>However those files have the same ownership (<code>apache:apache</code>) and permissions as every other file in the <code>wp-admin</code> folder (<code>644</code>). So I am clueless. Does anyone have an idea what the underlying cause might be?</p> <p><strong>Update - 8/26</strong><br> Based on some research I came to the conclusion the PHP error noted in the comments below was related to not having a particular extension - mbstrings - installed. Unfortunately when I went to install it, I tried to install the wrong version, then uninstalled some packages, added the Remi repository and then installed some packages which weren't quite the same as the old ones. My server runs PHP 5.6.24, but some of the packages may have been from 5.4. WordPress stopped working. After flailing around for a bit, I just rolled back the server to the AMI created before embarking on my SSL adventure. </p> <p>I'm going to try to migrate to SSL again this weekend. If the problem recurs, I'll be back here. If not I'll post an answer. Either way I'm going to avoid altering the database if at all possible.</p> <p><strong>Update 2 - 8/27</strong><br> The secret ingredient was the package php56u-mbstrings. Once I installed it, the script worked fine at the command line, although the GUI kept throwing AJAX errors and would only search three tables. The CLI script replaced 31 instances of <a href="http://www.ramblingnewyorker.com" rel="nofollow noreferrer">http://www.ramblingnewyorker.com</a> with <a href="https://www.ramblingnewyorker.com" rel="nofollow noreferrer">https://www.ramblingnewyorker.com</a>. However the problem persists. It appeared from the moment the secure site was set up. Disabling mod_security, or adding the following lines to my ssl.conf file do fix the issue: </p> <pre><code>&lt;LocationMatch "/wp-admin/load-scripts.php"&gt; &lt;IfModule mod_security2.c&gt; SecRuleEngine Off &lt;/IfModule&gt; &lt;/LocationMatch&gt; &lt;LocationMatch "/wp-admin/load-styles.php"&gt; &lt;IfModule mod_security2.c&gt; SecRuleEngine Off &lt;/IfModule&gt; &lt;/LocationMatch&gt; </code></pre> <p>Due to the security implications I've commented those lines out. This would seem to be related to mod_security somehow, but I can't find a single error message in the Apache log files.</p>
[ { "answer_id": 237256, "author": "Jesús Franco", "author_id": 16301, "author_profile": "https://wordpress.stackexchange.com/users/16301", "pm_score": 1, "selected": false, "text": "<p>Unfortunately I don't know Angular to give you a hand with that, but I'm seeing this question is related to another about <a href=\"https://wordpress.stackexchange.com/questions/237167/create-filtered-list-of-posts-using-json-data\">consuming an endpoint with a filter by meta_key</a> (by the way, I've updated my previous response with a very simple jQuery-only code to show posts retrieved in a list).</p>\n\n<p>However, if you don't mind an example with another library, I used to learn my first steps with React (lesser learning curve than Angular), a simple function to show the last published posts in a simple widget.</p>\n\n<pre><code>(function ( $ ) {\n var resourceUrl = 'http://example.com/wp-json/wp/v2/posts/';\n function refreshLastEntries() {\n var results = [];\n var link, item;\n $.get(\n resourceUrl,\n function (response) {\n console.log(\"Received \" \n + response.length + \" elements\");\n for(item = 0; item &lt; response.length; item++) {\n link = React.DOM.p({}, React.DOM.a({\n style:{\"textDecoration\":\"none\"},\n href:response[item].link\n }, response[item].title.rendered));\n results.push(link);\n }\n ReactDOM.render(React.DOM.div({}, results),\n document.getElementById('reactor'));\n }\n );\n setTimeout(refreshLastEntries, 10000); \n }\n refreshLastEntries();\n\n})(jQuery);\n</code></pre>\n\n<p>If you <strong>really</strong> want learn to use the REST API with Angular, I recommend you again visit the blog I've linked to you in the other question, since that lady has an entire feed about <a href=\"https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/\" rel=\"nofollow noreferrer\" title=\"1fix.io\">Using AngularJS and JSON API in Your WordPress Theme</a>.</p>\n" }, { "answer_id": 272169, "author": "mediaguru", "author_id": 110568, "author_profile": "https://wordpress.stackexchange.com/users/110568", "pm_score": 0, "selected": false, "text": "<p>Yes this can be done. You will have to study $http in angular JS. Include $http in your controller or directive. Then you can do something like this below. Page ID 199 is the about page for one of my sites:</p>\n\n<pre><code> var url = config.API_URL + \"/wp-json/wp/v2/pages/199\";\n $http.get(url)\n .then(function(response) {\n $scope.page = response.data;\n },\n function error(d) {\n $scope.error = true; // use to show an error message\n });\n</code></pre>\n\n<p>$scope.page contains the data from your page. Then in your html you can show it like this:</p>\n\n<pre><code> &lt;h1&gt;{{page.title}}&lt;/h1&gt;\n &lt;div&gt;{{page.content}}&lt;/div&gt;\n</code></pre>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236881", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101506/" ]
I am currently running an instance of WordPress, version 4.5.3, on an Amazon EC2 server. It uses: * CentOS 7 (OS) and has SELinux enabled. * Server runs Apache with `mod_security` and `mod_evasive` * PHP 5.6.24 The site's name is [The Rambling New Yorker](https://www.ramblingnewyorker.com/). Not long ago I upgraded to SSL using [Let's Encrypt](https://letsencrypt.org/). The process was fairly simple and I now have the front end secured. I've even installed a plugin which redirects non-SSL traffic to the secure site. Unfortunately, **the admin dashboard is broken**. As soon as I did the switch over it started looking as follows: [![WordPress SSL Problem](https://i.stack.imgur.com/jAmSd.png)](https://i.stack.imgur.com/jAmSd.png) I've changed the URLs (in the database, not through the dashboard) to be the SSL version and enabled "**Force SSL Admin**" in the config file. The login page is fine. The switch over once worked when I disabled all plugins. Re-enabling them one by one led me to believe [WP Super Cache](https://wordpress.org/plugins/wp-super-cache/) may be the issue, but when I did the switch over after deleting the plugin, the problem recurred. Disabling `mod_security` eliminates the problem, but there are no helpful error messages in the Apache error logs so I don't know what's upsetting it. The only clue is that requests for `load-styles.php` and `load-scripts.php` return a `403 error`: [![WordPress SSL Problem #2](https://i.stack.imgur.com/9bvuN.png)](https://i.stack.imgur.com/9bvuN.png) However those files have the same ownership (`apache:apache`) and permissions as every other file in the `wp-admin` folder (`644`). So I am clueless. Does anyone have an idea what the underlying cause might be? **Update - 8/26** Based on some research I came to the conclusion the PHP error noted in the comments below was related to not having a particular extension - mbstrings - installed. Unfortunately when I went to install it, I tried to install the wrong version, then uninstalled some packages, added the Remi repository and then installed some packages which weren't quite the same as the old ones. My server runs PHP 5.6.24, but some of the packages may have been from 5.4. WordPress stopped working. After flailing around for a bit, I just rolled back the server to the AMI created before embarking on my SSL adventure. I'm going to try to migrate to SSL again this weekend. If the problem recurs, I'll be back here. If not I'll post an answer. Either way I'm going to avoid altering the database if at all possible. **Update 2 - 8/27** The secret ingredient was the package php56u-mbstrings. Once I installed it, the script worked fine at the command line, although the GUI kept throwing AJAX errors and would only search three tables. The CLI script replaced 31 instances of <http://www.ramblingnewyorker.com> with <https://www.ramblingnewyorker.com>. However the problem persists. It appeared from the moment the secure site was set up. Disabling mod\_security, or adding the following lines to my ssl.conf file do fix the issue: ``` <LocationMatch "/wp-admin/load-scripts.php"> <IfModule mod_security2.c> SecRuleEngine Off </IfModule> </LocationMatch> <LocationMatch "/wp-admin/load-styles.php"> <IfModule mod_security2.c> SecRuleEngine Off </IfModule> </LocationMatch> ``` Due to the security implications I've commented those lines out. This would seem to be related to mod\_security somehow, but I can't find a single error message in the Apache log files.
Unfortunately I don't know Angular to give you a hand with that, but I'm seeing this question is related to another about [consuming an endpoint with a filter by meta\_key](https://wordpress.stackexchange.com/questions/237167/create-filtered-list-of-posts-using-json-data) (by the way, I've updated my previous response with a very simple jQuery-only code to show posts retrieved in a list). However, if you don't mind an example with another library, I used to learn my first steps with React (lesser learning curve than Angular), a simple function to show the last published posts in a simple widget. ``` (function ( $ ) { var resourceUrl = 'http://example.com/wp-json/wp/v2/posts/'; function refreshLastEntries() { var results = []; var link, item; $.get( resourceUrl, function (response) { console.log("Received " + response.length + " elements"); for(item = 0; item < response.length; item++) { link = React.DOM.p({}, React.DOM.a({ style:{"textDecoration":"none"}, href:response[item].link }, response[item].title.rendered)); results.push(link); } ReactDOM.render(React.DOM.div({}, results), document.getElementById('reactor')); } ); setTimeout(refreshLastEntries, 10000); } refreshLastEntries(); })(jQuery); ``` If you **really** want learn to use the REST API with Angular, I recommend you again visit the blog I've linked to you in the other question, since that lady has an entire feed about [Using AngularJS and JSON API in Your WordPress Theme](https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/ "1fix.io").
236,883
<p>I have a custom post type registered called <code>employees</code>. When registering this custom post type I used:</p> <pre><code>... 'rewrite' =&gt; array('slug' =&gt; 'people'), ... </code></pre> <p>Now, when I hover over a link to one of my employees I see the url as this:</p> <pre><code>www.example.com/people/john </code></pre> <p>So that seems correct. But I click the link, I see Chrome navigate to just <code>www.example.com/john</code> and then that doesn't exist so it redirects to <code>www.example.com</code> (the homepage).</p> <p>How do I make it navigate to <code>/people/john</code> and stop it from redirecting to the homepage?</p>
[ { "answer_id": 236884, "author": "Thomas", "author_id": 101453, "author_profile": "https://wordpress.stackexchange.com/users/101453", "pm_score": 1, "selected": false, "text": "<p>if you have register your taxo with\nregister_post_type('employees',$args);</p>\n\n<p>have you create single-employees.php ? </p>\n\n<p>and after in administration / Setting / Permalinks -> Save Changes</p>\n" }, { "answer_id": 236889, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 5, "selected": true, "text": "<p>The most important args for rewrite redirects when registering new post type are:</p>\n\n<ul>\n<li>'public' => true,</li>\n<li>'publicly_queryable' => true,</li>\n<li>'query_var' => true,</li>\n</ul>\n\n<p><strong>I have pasted some code below which I have tested and it working fine for the url : www.example.com/people/john</strong><br /><br /></p>\n\n<pre><code>$labels_employee = <br />array('name' => _x( 'Employees', 'Post typegeneral name', 'textdomain' ),<br />'singular_name' => _x( 'Employee', 'Post type singular name', 'textdomain' ),<br />'menu_name' => _x( 'Employees', 'Admin Menu text', 'textdomain' ),<br />'name_admin_bar' => _x( 'Employee', 'Add New on Toolbar', 'textdomain' ),<br />'add_new' => __( 'Add New', 'textdomain' ),<br />'add_new_item' => __( 'Add New Employee', 'textdomain' ),<br />'new_item' => __( 'New Employee', 'textdomain' ),<br /><br />$args_employee= array(\n 'labels' => $labels_employee,\n 'public' => true,\n 'publicly_queryable' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'people' ),\n 'capability_type' => 'post',\n 'has_archive' => true,\n 'hierarchical' => false,\n 'menu_position' => null,\n 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),\n );<br /><br />register_post_type( 'employee', $args_employee );</code></pre>\n" }, { "answer_id": 333288, "author": "Nikos", "author_id": 164314, "author_profile": "https://wordpress.stackexchange.com/users/164314", "pm_score": 0, "selected": false, "text": "<p>I had the same issue, custom taxonomy link was redirecting to index.</p>\n\n<p>Ok, when register a custom taxonomy, make sure that the register_taxonomy code runs always (init hook) and not only on admin (admin_init)</p>\n\n<pre><code>add_action('init', 'woobr_register_settings');\nfunction woobr_register_settings()\n{\n $args = array(\n //'labels' =&gt; $labels,\n //'labels' =&gt; 'Brand',\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'capability_type' =&gt; 'product',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'),\n\n );\n\n register_taxonomy('woobrand', 'product', $args); \n}\n</code></pre>\n" } ]
2016/08/23
[ "https://wordpress.stackexchange.com/questions/236883", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8160/" ]
I have a custom post type registered called `employees`. When registering this custom post type I used: ``` ... 'rewrite' => array('slug' => 'people'), ... ``` Now, when I hover over a link to one of my employees I see the url as this: ``` www.example.com/people/john ``` So that seems correct. But I click the link, I see Chrome navigate to just `www.example.com/john` and then that doesn't exist so it redirects to `www.example.com` (the homepage). How do I make it navigate to `/people/john` and stop it from redirecting to the homepage?
The most important args for rewrite redirects when registering new post type are: * 'public' => true, * 'publicly\_queryable' => true, * 'query\_var' => true, **I have pasted some code below which I have tested and it working fine for the url : www.example.com/people/john** ``` $labels_employee = array('name' => _x( 'Employees', 'Post typegeneral name', 'textdomain' ), 'singular_name' => _x( 'Employee', 'Post type singular name', 'textdomain' ), 'menu_name' => _x( 'Employees', 'Admin Menu text', 'textdomain' ), 'name_admin_bar' => _x( 'Employee', 'Add New on Toolbar', 'textdomain' ), 'add_new' => __( 'Add New', 'textdomain' ), 'add_new_item' => __( 'Add New Employee', 'textdomain' ), 'new_item' => __( 'New Employee', 'textdomain' ), $args_employee= array( 'labels' => $labels_employee, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'people' ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ), ); register_post_type( 'employee', $args_employee ); ```
236,947
<p>I've created a custom category template to display the current category's child categories instead of posts. Child categories are displayed via a custom thumbnail, title and category description.</p> <p>I have added a function to trim the category description to a predefined number of characters, but I'm not sure which action hook to use.</p> <p>Here's the function:</p> <pre><code>function trim_text($input, $length, $ellipses = true, $strip_html = true) { //strip tags, if desired if ($strip_html) { $input = strip_tags($input); } //no need to trim, already shorter than trim length if (strlen($input) &lt;= $length) { return $input; } //find last space within length $last_space = strrpos(substr($input, 0, $length), ' '); $trimmed_text = substr($input, 0, $last_space); //add ellipses (...) if ($ellipses) { $trimmed_text .= '...'; } return $trimmed_text; } </code></pre>
[ { "answer_id": 236891, "author": "Zareef Ahmed", "author_id": 101508, "author_profile": "https://wordpress.stackexchange.com/users/101508", "pm_score": 0, "selected": false, "text": "<p>From error message it seems that something is wrong with cookie system. have you tried using another browser?</p>\n\n<p>Also, please try to change values of home and siteurl variables in options table via mysql.</p>\n" }, { "answer_id": 237014, "author": "Abdulrahman Hassoun", "author_id": 101507, "author_profile": "https://wordpress.stackexchange.com/users/101507", "pm_score": 2, "selected": true, "text": "<p>Looks like the issue was because of Nginx or other caching server. Rebooting the server solved the issue! There was nothing more to do in the database or <code>wp-config.php</code></p>\n" } ]
2016/08/24
[ "https://wordpress.stackexchange.com/questions/236947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68414/" ]
I've created a custom category template to display the current category's child categories instead of posts. Child categories are displayed via a custom thumbnail, title and category description. I have added a function to trim the category description to a predefined number of characters, but I'm not sure which action hook to use. Here's the function: ``` function trim_text($input, $length, $ellipses = true, $strip_html = true) { //strip tags, if desired if ($strip_html) { $input = strip_tags($input); } //no need to trim, already shorter than trim length if (strlen($input) <= $length) { return $input; } //find last space within length $last_space = strrpos(substr($input, 0, $length), ' '); $trimmed_text = substr($input, 0, $last_space); //add ellipses (...) if ($ellipses) { $trimmed_text .= '...'; } return $trimmed_text; } ```
Looks like the issue was because of Nginx or other caching server. Rebooting the server solved the issue! There was nothing more to do in the database or `wp-config.php`
237,001
<p>For some reason I'm not able to retrieve any child terms for the <code>carabana_cat</code> taxonomy. Here's what I've done so far:</p> <pre><code>$custom_terms = get_terms( 'carabana_Cat', array( 'hide_empty' =&gt; false, 'orderly' =&gt; 'description', 'child_of' =&gt; 28) ); </code></pre> <p>What am I doing wrong here? There are lots of child terms for <code>id=28</code> which aren't showing up.</p>
[ { "answer_id": 237000, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>There are really two questions here 1. what is the impact of having an hook? and 2. Should you just spread hooks everywhere</p>\n\n<ol>\n<li><p>The impact is close to zero. If there is nothing that hooked on on the action/filter the calls to <code>do_action/apply_filters</code> will return almost imidiatly, so there will not be any noticeable impact to people that do not use the hook, and therefor it is not technically bad to add them (if you give any semi reasonable reason to adding hooks to core, it will most likely be added by the core theme).</p></li>\n<li><p>But is it smart as a software development practice? No. Hooks are APIs and APIs means commitment on your part to maintain them in the long run. Therefor like any \"official\" API you create, you should think is it something that make sense for your plugin in the long run and you do not do it just to make one plugin user happy.</p></li>\n</ol>\n\n<p>From your description, if you think that there is a text that needs customized, maybe you should consider using some kind of settings screen for that. This is obviously also some kind of API, but it is more visible accessible for the end users. </p>\n" }, { "answer_id": 237004, "author": "Kolya Korobochkin", "author_id": 46077, "author_profile": "https://wordpress.stackexchange.com/users/46077", "pm_score": 2, "selected": false, "text": "<p>Customization is always a stone of stumbling (painful process). From one side we have a real requests (issues) from users which always matters. On other hand all of this additional options can turn your lovely theme, plugin or some abstract product to the hell. So what can we do as a developer?</p>\n\n<p>First of all. <strong>Write extensible code</strong> with opportunity to change some of pieces of your code — reusable code. Classes, interfaces, traits and just splitting long-wrong code into small methods (functions). Some part of users can easily use them without changes in your product. For example, someone can create a widget with his own needs and use internal plugin function <code>please_echo_the_plugin_awesome_stuff()</code>.</p>\n\n<p>Adding the <strong>new filters and actions is not bad idea</strong>. Many popular plugins like Jetpack or bbPress have hundreds of filters inside their code. Sometimes even excessively. Each new filter (or action) without any handlers usually not doing a large overhead. It's a microseconds.</p>\n\n<p>10^−3 s millisecond ms\n10^−6 s microsecond µs</p>\n\n<p>Much more important is what you're doing on this action by adding new handlers via <code>add_action()</code> or <code>add_filter()</code>. For example, requests to the database server (sometimes non-obvious, like getting non autoload option by <code>get_option()</code>). And you can measure it. The most simple example:</p>\n\n<pre><code>$start = microtime(true);\n// Do some stuff here\n$end = microtime(true);\necho $start, PHP_EOL, $end, PHP_EOL, $end - $start, PHP_EOL,\n</code></pre>\n\n<p>It is very simple and sometimes most suitable technique to profile your code. By the way WordPress have internal \"stopwatch\", checkout <code>timer_start()</code> and <code>timer_stop()</code>.</p>\n\n<p>Or you can use XDebug. It may seem very complex to configure. But you can use <a href=\"https://github.com/Varying-Vagrant-Vagrants/VVV\" rel=\"nofollow\">VVV</a> or any other ready-to-go server. All of them already have properly configured Xdebug and you can just use it - sounds great, isn't it?. If you're using VVV just hit few commands:</p>\n\n<pre><code>vagrant ssh\nxdebung_on\n</code></pre>\n\n<p>That's all! Switch to your IDE and profile your code. Or use VVV internal services like WebGrind. More about this techniques you can find at <a href=\"https://github.com/Varying-Vagrant-Vagrants/VVV/wiki/Code-Debugging\" rel=\"nofollow\">Code Debugging Wiki</a>. It should be remembered that using Xdebug make effect on the performance, but you can find slow code (bottleneck).</p>\n\n<p>And third. The last thing. WordPress philosophy is <strong>Decisions, not Options</strong>.</p>\n" }, { "answer_id": 237011, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 4, "selected": true, "text": "<p>As long as hooks don't have anything hooked to them they are no-ops, that is do nearly nothing and have no considerable effect on runtime. It gets quite different when things <em>are</em> hooked and there are <em>a lot</em> of calls.</p>\n\n<p>Since you talk about customizing strings the good example would be <code>gettext</code> hook in core. Every string that is localized passes through it.</p>\n\n<p>So <em>in theory</em> this is a very flexible hook that allows to filter text nearly anywhere. <em>In practice</em> it can fire <em>thousands</em> of times and if you just hook into it unreservedly it will quickly slow down complex site to a halt.</p>\n\n<p>You don't cover your use case in sufficient detail to recommend specific implementation. In general you have multiple choices on how to organize this:</p>\n\n<ul>\n<li><code>apply_filters( 'prefix_tooltip', $text )</code> is basic case, the filter would have to figure out does the text match exactly to determine context, thus fragile.</li>\n<li><code>apply_filters( 'prefix_tooltip', $text, 'type/location' )</code> additional argument allows you to specify type of tooltip, which filter can target; so even if text changes, the type still identifies it.</li>\n<li><code>apply_filters( 'prefix_tooltip_' . $type, $text )</code> dynamic hook name, which changes with variable value; this is very flexible for cases of many/generated types, the issue mostly is that dynamic hooks are harder to discover in code and are much worse at self-documenting;</li>\n<li><code>apply_filters( 'prefix_tooltips', $texts_array )</code> single filter for complete <em>set</em> of tooltips used.</li>\n</ul>\n\n<p>At a count of 6–8 entries there won’t really be meaningful performance difference between these.</p>\n\n<p>What is important for you to learn here is what approaches there <em>are</em> and that you need to carefully pick the most appropriate one for every case, to have it be meaningful and convenient for yourself and downstream developers.</p>\n" } ]
2016/08/24
[ "https://wordpress.stackexchange.com/questions/237001", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101581/" ]
For some reason I'm not able to retrieve any child terms for the `carabana_cat` taxonomy. Here's what I've done so far: ``` $custom_terms = get_terms( 'carabana_Cat', array( 'hide_empty' => false, 'orderly' => 'description', 'child_of' => 28) ); ``` What am I doing wrong here? There are lots of child terms for `id=28` which aren't showing up.
As long as hooks don't have anything hooked to them they are no-ops, that is do nearly nothing and have no considerable effect on runtime. It gets quite different when things *are* hooked and there are *a lot* of calls. Since you talk about customizing strings the good example would be `gettext` hook in core. Every string that is localized passes through it. So *in theory* this is a very flexible hook that allows to filter text nearly anywhere. *In practice* it can fire *thousands* of times and if you just hook into it unreservedly it will quickly slow down complex site to a halt. You don't cover your use case in sufficient detail to recommend specific implementation. In general you have multiple choices on how to organize this: * `apply_filters( 'prefix_tooltip', $text )` is basic case, the filter would have to figure out does the text match exactly to determine context, thus fragile. * `apply_filters( 'prefix_tooltip', $text, 'type/location' )` additional argument allows you to specify type of tooltip, which filter can target; so even if text changes, the type still identifies it. * `apply_filters( 'prefix_tooltip_' . $type, $text )` dynamic hook name, which changes with variable value; this is very flexible for cases of many/generated types, the issue mostly is that dynamic hooks are harder to discover in code and are much worse at self-documenting; * `apply_filters( 'prefix_tooltips', $texts_array )` single filter for complete *set* of tooltips used. At a count of 6–8 entries there won’t really be meaningful performance difference between these. What is important for you to learn here is what approaches there *are* and that you need to carefully pick the most appropriate one for every case, to have it be meaningful and convenient for yourself and downstream developers.
237,009
<p>Each widget has a row in the <code>options</code> table with values for title and other fields. Is there any way we can update those values outside the <code>update</code> function?</p> <p>For example, here are some values for a sample widget: </p> <pre><code>a:2:{i:2;a:23:{s:5:"title";s:19:"Widget Title";..... </code></pre> <p>now I want to update the <code>title</code> to another value in the <code>function widget($args, $instance)</code> and save the value to the database. </p> <p>I found that <a href="https://codex.wordpress.org/Options_API" rel="nofollow">options API</a> can handle something like this, but I am not sure if this is the correct way and how to update the info for that specific widget. </p> <pre><code>// Update the value of an option that was already added. update_option( $option, $newvalue ); </code></pre>
[ { "answer_id": 237000, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>There are really two questions here 1. what is the impact of having an hook? and 2. Should you just spread hooks everywhere</p>\n\n<ol>\n<li><p>The impact is close to zero. If there is nothing that hooked on on the action/filter the calls to <code>do_action/apply_filters</code> will return almost imidiatly, so there will not be any noticeable impact to people that do not use the hook, and therefor it is not technically bad to add them (if you give any semi reasonable reason to adding hooks to core, it will most likely be added by the core theme).</p></li>\n<li><p>But is it smart as a software development practice? No. Hooks are APIs and APIs means commitment on your part to maintain them in the long run. Therefor like any \"official\" API you create, you should think is it something that make sense for your plugin in the long run and you do not do it just to make one plugin user happy.</p></li>\n</ol>\n\n<p>From your description, if you think that there is a text that needs customized, maybe you should consider using some kind of settings screen for that. This is obviously also some kind of API, but it is more visible accessible for the end users. </p>\n" }, { "answer_id": 237004, "author": "Kolya Korobochkin", "author_id": 46077, "author_profile": "https://wordpress.stackexchange.com/users/46077", "pm_score": 2, "selected": false, "text": "<p>Customization is always a stone of stumbling (painful process). From one side we have a real requests (issues) from users which always matters. On other hand all of this additional options can turn your lovely theme, plugin or some abstract product to the hell. So what can we do as a developer?</p>\n\n<p>First of all. <strong>Write extensible code</strong> with opportunity to change some of pieces of your code — reusable code. Classes, interfaces, traits and just splitting long-wrong code into small methods (functions). Some part of users can easily use them without changes in your product. For example, someone can create a widget with his own needs and use internal plugin function <code>please_echo_the_plugin_awesome_stuff()</code>.</p>\n\n<p>Adding the <strong>new filters and actions is not bad idea</strong>. Many popular plugins like Jetpack or bbPress have hundreds of filters inside their code. Sometimes even excessively. Each new filter (or action) without any handlers usually not doing a large overhead. It's a microseconds.</p>\n\n<p>10^−3 s millisecond ms\n10^−6 s microsecond µs</p>\n\n<p>Much more important is what you're doing on this action by adding new handlers via <code>add_action()</code> or <code>add_filter()</code>. For example, requests to the database server (sometimes non-obvious, like getting non autoload option by <code>get_option()</code>). And you can measure it. The most simple example:</p>\n\n<pre><code>$start = microtime(true);\n// Do some stuff here\n$end = microtime(true);\necho $start, PHP_EOL, $end, PHP_EOL, $end - $start, PHP_EOL,\n</code></pre>\n\n<p>It is very simple and sometimes most suitable technique to profile your code. By the way WordPress have internal \"stopwatch\", checkout <code>timer_start()</code> and <code>timer_stop()</code>.</p>\n\n<p>Or you can use XDebug. It may seem very complex to configure. But you can use <a href=\"https://github.com/Varying-Vagrant-Vagrants/VVV\" rel=\"nofollow\">VVV</a> or any other ready-to-go server. All of them already have properly configured Xdebug and you can just use it - sounds great, isn't it?. If you're using VVV just hit few commands:</p>\n\n<pre><code>vagrant ssh\nxdebung_on\n</code></pre>\n\n<p>That's all! Switch to your IDE and profile your code. Or use VVV internal services like WebGrind. More about this techniques you can find at <a href=\"https://github.com/Varying-Vagrant-Vagrants/VVV/wiki/Code-Debugging\" rel=\"nofollow\">Code Debugging Wiki</a>. It should be remembered that using Xdebug make effect on the performance, but you can find slow code (bottleneck).</p>\n\n<p>And third. The last thing. WordPress philosophy is <strong>Decisions, not Options</strong>.</p>\n" }, { "answer_id": 237011, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 4, "selected": true, "text": "<p>As long as hooks don't have anything hooked to them they are no-ops, that is do nearly nothing and have no considerable effect on runtime. It gets quite different when things <em>are</em> hooked and there are <em>a lot</em> of calls.</p>\n\n<p>Since you talk about customizing strings the good example would be <code>gettext</code> hook in core. Every string that is localized passes through it.</p>\n\n<p>So <em>in theory</em> this is a very flexible hook that allows to filter text nearly anywhere. <em>In practice</em> it can fire <em>thousands</em> of times and if you just hook into it unreservedly it will quickly slow down complex site to a halt.</p>\n\n<p>You don't cover your use case in sufficient detail to recommend specific implementation. In general you have multiple choices on how to organize this:</p>\n\n<ul>\n<li><code>apply_filters( 'prefix_tooltip', $text )</code> is basic case, the filter would have to figure out does the text match exactly to determine context, thus fragile.</li>\n<li><code>apply_filters( 'prefix_tooltip', $text, 'type/location' )</code> additional argument allows you to specify type of tooltip, which filter can target; so even if text changes, the type still identifies it.</li>\n<li><code>apply_filters( 'prefix_tooltip_' . $type, $text )</code> dynamic hook name, which changes with variable value; this is very flexible for cases of many/generated types, the issue mostly is that dynamic hooks are harder to discover in code and are much worse at self-documenting;</li>\n<li><code>apply_filters( 'prefix_tooltips', $texts_array )</code> single filter for complete <em>set</em> of tooltips used.</li>\n</ul>\n\n<p>At a count of 6–8 entries there won’t really be meaningful performance difference between these.</p>\n\n<p>What is important for you to learn here is what approaches there <em>are</em> and that you need to carefully pick the most appropriate one for every case, to have it be meaningful and convenient for yourself and downstream developers.</p>\n" } ]
2016/08/24
[ "https://wordpress.stackexchange.com/questions/237009", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82260/" ]
Each widget has a row in the `options` table with values for title and other fields. Is there any way we can update those values outside the `update` function? For example, here are some values for a sample widget: ``` a:2:{i:2;a:23:{s:5:"title";s:19:"Widget Title";..... ``` now I want to update the `title` to another value in the `function widget($args, $instance)` and save the value to the database. I found that [options API](https://codex.wordpress.org/Options_API) can handle something like this, but I am not sure if this is the correct way and how to update the info for that specific widget. ``` // Update the value of an option that was already added. update_option( $option, $newvalue ); ```
As long as hooks don't have anything hooked to them they are no-ops, that is do nearly nothing and have no considerable effect on runtime. It gets quite different when things *are* hooked and there are *a lot* of calls. Since you talk about customizing strings the good example would be `gettext` hook in core. Every string that is localized passes through it. So *in theory* this is a very flexible hook that allows to filter text nearly anywhere. *In practice* it can fire *thousands* of times and if you just hook into it unreservedly it will quickly slow down complex site to a halt. You don't cover your use case in sufficient detail to recommend specific implementation. In general you have multiple choices on how to organize this: * `apply_filters( 'prefix_tooltip', $text )` is basic case, the filter would have to figure out does the text match exactly to determine context, thus fragile. * `apply_filters( 'prefix_tooltip', $text, 'type/location' )` additional argument allows you to specify type of tooltip, which filter can target; so even if text changes, the type still identifies it. * `apply_filters( 'prefix_tooltip_' . $type, $text )` dynamic hook name, which changes with variable value; this is very flexible for cases of many/generated types, the issue mostly is that dynamic hooks are harder to discover in code and are much worse at self-documenting; * `apply_filters( 'prefix_tooltips', $texts_array )` single filter for complete *set* of tooltips used. At a count of 6–8 entries there won’t really be meaningful performance difference between these. What is important for you to learn here is what approaches there *are* and that you need to carefully pick the most appropriate one for every case, to have it be meaningful and convenient for yourself and downstream developers.
237,020
<p>I am attempting to add a data attribute to all menu items, but it's simply not working. I am using <code>wp_nav_menu</code> to call my menu walker as well.</p> <pre><code>function menu_anchor_attributes ( $atts, $item, $args ) { $atts['data-menuanchor'] = $item-&gt;attr_title; return $atts; } add_filter( 'nav_menu_link_attributes', 'menu_anchor_attributes', 10, 3 ); </code></pre> <p>I am using JointsWP as my framework, which includes this walker:</p> <pre><code>// The Top Menu function joints_top_nav() { wp_nav_menu(array( 'container' =&gt; false, // Remove nav container 'menu_class' =&gt; 'horizontal menu', // Adding custom nav class 'items_wrap' =&gt; '&lt;ul id="%1$s" class="%2$s" data-responsive-menu="accordion medium-dropdown"&gt;%3$s&lt;/ul&gt;', 'theme_location' =&gt; 'main-nav', // Where it's located in the theme 'depth' =&gt; 5, // Limit the depth of the nav 'fallback_cb' =&gt; false, // Fallback function (see below) 'walker' =&gt; new Topbar_Menu_Walker() )); } // Big thanks to Brett Mason (https://github.com/brettsmason) for the awesome walker class Topbar_Menu_Walker extends Walker_Nav_Menu { function start_lvl(&amp;$output, $depth = 0, $args = Array() ) { $indent = str_repeat("\t", $depth); $output .= "\n$indent&lt;ul class=\"menu\"&gt;\n"; } } </code></pre>
[ { "answer_id": 237494, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>Whenever an attribute is empty WordPress filters decide just not to show the attribute so a simple test for this is the following:</p>\n\n<pre><code>function menu_anchor_attributes ( $atts, $item, $args ) {\n $atts['data-menuanchor'] = ( ! empty( $item-&gt;attr_title ) ) ? $item-&gt;attr_title : 'test';\n return $atts;\n}\nadd_filter( 'nav_menu_link_attributes', 'menu_anchor_attributes', 10, 3 );\n</code></pre>\n\n<p>This way, if a title attribute hasn't been filled into the back-end it will still display the attribute with a value of <code>test</code>.</p>\n" }, { "answer_id": 328228, "author": "Nicola", "author_id": 31679, "author_profile": "https://wordpress.stackexchange.com/users/31679", "pm_score": 0, "selected": false, "text": "<p>The fiter <code>nav_menu_link_attributes</code> only works on menus that are created in wp-admin. By default <code>wp_nav_menu</code> returns the published pages even if you did not create a menu on the backend but as soon as you click \"create menu\" on Appearance -> Menus the filter does its job</p>\n" } ]
2016/08/24
[ "https://wordpress.stackexchange.com/questions/237020", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101588/" ]
I am attempting to add a data attribute to all menu items, but it's simply not working. I am using `wp_nav_menu` to call my menu walker as well. ``` function menu_anchor_attributes ( $atts, $item, $args ) { $atts['data-menuanchor'] = $item->attr_title; return $atts; } add_filter( 'nav_menu_link_attributes', 'menu_anchor_attributes', 10, 3 ); ``` I am using JointsWP as my framework, which includes this walker: ``` // The Top Menu function joints_top_nav() { wp_nav_menu(array( 'container' => false, // Remove nav container 'menu_class' => 'horizontal menu', // Adding custom nav class 'items_wrap' => '<ul id="%1$s" class="%2$s" data-responsive-menu="accordion medium-dropdown">%3$s</ul>', 'theme_location' => 'main-nav', // Where it's located in the theme 'depth' => 5, // Limit the depth of the nav 'fallback_cb' => false, // Fallback function (see below) 'walker' => new Topbar_Menu_Walker() )); } // Big thanks to Brett Mason (https://github.com/brettsmason) for the awesome walker class Topbar_Menu_Walker extends Walker_Nav_Menu { function start_lvl(&$output, $depth = 0, $args = Array() ) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul class=\"menu\">\n"; } } ```
Whenever an attribute is empty WordPress filters decide just not to show the attribute so a simple test for this is the following: ``` function menu_anchor_attributes ( $atts, $item, $args ) { $atts['data-menuanchor'] = ( ! empty( $item->attr_title ) ) ? $item->attr_title : 'test'; return $atts; } add_filter( 'nav_menu_link_attributes', 'menu_anchor_attributes', 10, 3 ); ``` This way, if a title attribute hasn't been filled into the back-end it will still display the attribute with a value of `test`.
237,023
<p>Learning more about sessions I've gathered that a <code>session_start()</code> should come directly after <code>&lt;?php</code> per <a href="https://stackoverflow.com/questions/20308478/where-exactly-do-i-put-a-session-start">Where exactly do I put a SESSION_START?</a> and I wanted to play around and create a plugin that would add a <code>session_start()</code> to <code>header.php</code> after it's <code>&lt;?php</code> but after searching I've been inclusive with trying to figure out the appropriate procedure to do this. </p> <p>I did search for <a href="https://wordpress.stackexchange.com/search?q=session">session</a> but I've seen a variety of Q&amp;As that mostly seem to use:</p> <ul> <li><code>init</code>: <a href="https://wordpress.stackexchange.com/questions/149132/session-is-not-starting">Session is not starting</a></li> <li><code>wp_head</code>: <a href="https://wordpress.stackexchange.com/questions/167928/hook-into-wp-head-in-a-plugin">Hook into wp_head(); in a plugin</a></li> <li><code>wp_loaded</code>: <a href="https://wordpress.stackexchange.com/questions/105453/getting-headers-already-sent-error-from-plugin">Getting headers already sent error from plugin</a></li> </ul> <p>So when authoring a plugin that relies on session to be added to header.php what is the appropriate hook for adding <code>session_start()</code>?</p>
[ { "answer_id": 237034, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>There is no regular output and hence no header sent before <code>template_redirect</code> on the front end. If you need sessions on the back end too, use the action <code>wp_loaded</code> to cover both.</p>\n\n<p>Example:</p>\n\n<pre><code>add_action( 'template_redirect', function() {\n\n $status = session_status();\n\n if ( PHP_SESSION_DISABLED === $status ) {\n // That's why you cannot rely on sessions!\n return;\n }\n\n if ( PHP_SESSION_NONE === $status ) {\n session_start();\n }\n\n $_SESSION[ 'foo' ] = 'bar';\n});\n</code></pre>\n\n<p>Keep in mind that using sessions adds a whole <a href=\"https://wordpress.stackexchange.com/q/167585/73\">set of very complex problems</a> to your code, including security, scalability (load balancers), and following time consuming support issues. I don't recommend it.</p>\n" }, { "answer_id": 323601, "author": "Ivijan Stefan Stipić", "author_id": 82023, "author_profile": "https://wordpress.stackexchange.com/users/82023", "pm_score": 1, "selected": false, "text": "<p>Here is also another solution for all kind of PHP versions what you can find inside <a href=\"https://wordpress.org/plugins/cf-geoplugin/\" rel=\"nofollow noreferrer\">CF Geo Plugin</a>:</p>\n\n<pre><code>if (version_compare(PHP_VERSION, '7.0.0') &gt;= 0) {\n if(function_exists('session_status') &amp;&amp; session_status() == PHP_SESSION_NONE) {\n session_start(array(\n 'cache_limiter' =&gt; 'private_no_expire',\n 'read_and_close' =&gt; false,\n ));\n }\n}\nelse if (version_compare(PHP_VERSION, '5.4.0') &gt;= 0)\n{\n if (function_exists('session_status') &amp;&amp; session_status() == PHP_SESSION_NONE) {\n session_cache_limiter('private_no_expire');\n session_start();\n }\n}\nelse\n{\n if(session_id() == '') {\n if(version_compare(PHP_VERSION, '4.0.0') &gt;= 0){\n session_cache_limiter('private_no_expire');\n }\n session_start();\n }\n}\n</code></pre>\n\n<p>With this solution you can prevent any problem with session and start it anytime you need.</p>\n" }, { "answer_id": 391613, "author": "Sachin Saini", "author_id": 208742, "author_profile": "https://wordpress.stackexchange.com/users/208742", "pm_score": 0, "selected": false, "text": "<p>We can use the easy way by init hook. Write this function in the function.php</p>\n<pre><code>function register_my_session() {\n if( !session_id() )\n session_start();\n}\nadd_action('init', 'register_my_session');\n</code></pre>\n<p>after adding this function in function.php you can Set values in sessions like</p>\n<pre><code>$_SESSION['user_country'] = 'india';\n</code></pre>\n<p>Get session value</p>\n<pre><code>echo $_SESSION['user_country'];\n</code></pre>\n<p>for destroying session value</p>\n<pre><code>unset($_SESSION[&quot;user_country&quot;]);\n</code></pre>\n" } ]
2016/08/24
[ "https://wordpress.stackexchange.com/questions/237023", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25271/" ]
Learning more about sessions I've gathered that a `session_start()` should come directly after `<?php` per [Where exactly do I put a SESSION\_START?](https://stackoverflow.com/questions/20308478/where-exactly-do-i-put-a-session-start) and I wanted to play around and create a plugin that would add a `session_start()` to `header.php` after it's `<?php` but after searching I've been inclusive with trying to figure out the appropriate procedure to do this. I did search for [session](https://wordpress.stackexchange.com/search?q=session) but I've seen a variety of Q&As that mostly seem to use: * `init`: [Session is not starting](https://wordpress.stackexchange.com/questions/149132/session-is-not-starting) * `wp_head`: [Hook into wp\_head(); in a plugin](https://wordpress.stackexchange.com/questions/167928/hook-into-wp-head-in-a-plugin) * `wp_loaded`: [Getting headers already sent error from plugin](https://wordpress.stackexchange.com/questions/105453/getting-headers-already-sent-error-from-plugin) So when authoring a plugin that relies on session to be added to header.php what is the appropriate hook for adding `session_start()`?
There is no regular output and hence no header sent before `template_redirect` on the front end. If you need sessions on the back end too, use the action `wp_loaded` to cover both. Example: ``` add_action( 'template_redirect', function() { $status = session_status(); if ( PHP_SESSION_DISABLED === $status ) { // That's why you cannot rely on sessions! return; } if ( PHP_SESSION_NONE === $status ) { session_start(); } $_SESSION[ 'foo' ] = 'bar'; }); ``` Keep in mind that using sessions adds a whole [set of very complex problems](https://wordpress.stackexchange.com/q/167585/73) to your code, including security, scalability (load balancers), and following time consuming support issues. I don't recommend it.
237,025
<p>We need to style a single page differently depending on what user journey you take. Currently we have event posts listed in WP, they are either under the "get involved > events" page or "urban innovation center > attend an event" some events are listed in both. If you come from "get involved > events" we need the single event page to have a light background and if you come from "urban innovation center > attend an event" we need the single event page to have a dark background. We dont want to have to duplicate the events in WP.</p> <p><a href="https://futurecities.catapult.org.uk/events/" rel="nofollow">https://futurecities.catapult.org.uk/events/</a></p>
[ { "answer_id": 237034, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>There is no regular output and hence no header sent before <code>template_redirect</code> on the front end. If you need sessions on the back end too, use the action <code>wp_loaded</code> to cover both.</p>\n\n<p>Example:</p>\n\n<pre><code>add_action( 'template_redirect', function() {\n\n $status = session_status();\n\n if ( PHP_SESSION_DISABLED === $status ) {\n // That's why you cannot rely on sessions!\n return;\n }\n\n if ( PHP_SESSION_NONE === $status ) {\n session_start();\n }\n\n $_SESSION[ 'foo' ] = 'bar';\n});\n</code></pre>\n\n<p>Keep in mind that using sessions adds a whole <a href=\"https://wordpress.stackexchange.com/q/167585/73\">set of very complex problems</a> to your code, including security, scalability (load balancers), and following time consuming support issues. I don't recommend it.</p>\n" }, { "answer_id": 323601, "author": "Ivijan Stefan Stipić", "author_id": 82023, "author_profile": "https://wordpress.stackexchange.com/users/82023", "pm_score": 1, "selected": false, "text": "<p>Here is also another solution for all kind of PHP versions what you can find inside <a href=\"https://wordpress.org/plugins/cf-geoplugin/\" rel=\"nofollow noreferrer\">CF Geo Plugin</a>:</p>\n\n<pre><code>if (version_compare(PHP_VERSION, '7.0.0') &gt;= 0) {\n if(function_exists('session_status') &amp;&amp; session_status() == PHP_SESSION_NONE) {\n session_start(array(\n 'cache_limiter' =&gt; 'private_no_expire',\n 'read_and_close' =&gt; false,\n ));\n }\n}\nelse if (version_compare(PHP_VERSION, '5.4.0') &gt;= 0)\n{\n if (function_exists('session_status') &amp;&amp; session_status() == PHP_SESSION_NONE) {\n session_cache_limiter('private_no_expire');\n session_start();\n }\n}\nelse\n{\n if(session_id() == '') {\n if(version_compare(PHP_VERSION, '4.0.0') &gt;= 0){\n session_cache_limiter('private_no_expire');\n }\n session_start();\n }\n}\n</code></pre>\n\n<p>With this solution you can prevent any problem with session and start it anytime you need.</p>\n" }, { "answer_id": 391613, "author": "Sachin Saini", "author_id": 208742, "author_profile": "https://wordpress.stackexchange.com/users/208742", "pm_score": 0, "selected": false, "text": "<p>We can use the easy way by init hook. Write this function in the function.php</p>\n<pre><code>function register_my_session() {\n if( !session_id() )\n session_start();\n}\nadd_action('init', 'register_my_session');\n</code></pre>\n<p>after adding this function in function.php you can Set values in sessions like</p>\n<pre><code>$_SESSION['user_country'] = 'india';\n</code></pre>\n<p>Get session value</p>\n<pre><code>echo $_SESSION['user_country'];\n</code></pre>\n<p>for destroying session value</p>\n<pre><code>unset($_SESSION[&quot;user_country&quot;]);\n</code></pre>\n" } ]
2016/08/24
[ "https://wordpress.stackexchange.com/questions/237025", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101582/" ]
We need to style a single page differently depending on what user journey you take. Currently we have event posts listed in WP, they are either under the "get involved > events" page or "urban innovation center > attend an event" some events are listed in both. If you come from "get involved > events" we need the single event page to have a light background and if you come from "urban innovation center > attend an event" we need the single event page to have a dark background. We dont want to have to duplicate the events in WP. <https://futurecities.catapult.org.uk/events/>
There is no regular output and hence no header sent before `template_redirect` on the front end. If you need sessions on the back end too, use the action `wp_loaded` to cover both. Example: ``` add_action( 'template_redirect', function() { $status = session_status(); if ( PHP_SESSION_DISABLED === $status ) { // That's why you cannot rely on sessions! return; } if ( PHP_SESSION_NONE === $status ) { session_start(); } $_SESSION[ 'foo' ] = 'bar'; }); ``` Keep in mind that using sessions adds a whole [set of very complex problems](https://wordpress.stackexchange.com/q/167585/73) to your code, including security, scalability (load balancers), and following time consuming support issues. I don't recommend it.
237,032
<p>I'm iterating over a custom post type that uses an image from the media library for each item. The images are being rendered for each one correctly with the right size, but for some reason it is loading the full image instead of the medium, which is greatly affecting my page load time.</p> <p>Here is what I have:</p> <pre><code> $args = array( 'post_type' =&gt; 'recent-project', 'posts_per_page' =&gt; -1 ); $projects = new WP_Query( $args ); while ( $projects-&gt;have_posts() ) : $projects-&gt;the_post(); echo '&lt;a href="' . $get_permalink(); . '"&gt;'; echo '&lt;div class="item"&gt;'; echo wp_get_attachment_image( get_post_thumbnail_id( $post-&gt;ID ), 'medium' ); echo '&lt;/div&gt;&lt;/a&gt;'; endwhile; </code></pre> <p>Anyone know how I can get the medium size to load instead of the full?</p>
[ { "answer_id": 237034, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>There is no regular output and hence no header sent before <code>template_redirect</code> on the front end. If you need sessions on the back end too, use the action <code>wp_loaded</code> to cover both.</p>\n\n<p>Example:</p>\n\n<pre><code>add_action( 'template_redirect', function() {\n\n $status = session_status();\n\n if ( PHP_SESSION_DISABLED === $status ) {\n // That's why you cannot rely on sessions!\n return;\n }\n\n if ( PHP_SESSION_NONE === $status ) {\n session_start();\n }\n\n $_SESSION[ 'foo' ] = 'bar';\n});\n</code></pre>\n\n<p>Keep in mind that using sessions adds a whole <a href=\"https://wordpress.stackexchange.com/q/167585/73\">set of very complex problems</a> to your code, including security, scalability (load balancers), and following time consuming support issues. I don't recommend it.</p>\n" }, { "answer_id": 323601, "author": "Ivijan Stefan Stipić", "author_id": 82023, "author_profile": "https://wordpress.stackexchange.com/users/82023", "pm_score": 1, "selected": false, "text": "<p>Here is also another solution for all kind of PHP versions what you can find inside <a href=\"https://wordpress.org/plugins/cf-geoplugin/\" rel=\"nofollow noreferrer\">CF Geo Plugin</a>:</p>\n\n<pre><code>if (version_compare(PHP_VERSION, '7.0.0') &gt;= 0) {\n if(function_exists('session_status') &amp;&amp; session_status() == PHP_SESSION_NONE) {\n session_start(array(\n 'cache_limiter' =&gt; 'private_no_expire',\n 'read_and_close' =&gt; false,\n ));\n }\n}\nelse if (version_compare(PHP_VERSION, '5.4.0') &gt;= 0)\n{\n if (function_exists('session_status') &amp;&amp; session_status() == PHP_SESSION_NONE) {\n session_cache_limiter('private_no_expire');\n session_start();\n }\n}\nelse\n{\n if(session_id() == '') {\n if(version_compare(PHP_VERSION, '4.0.0') &gt;= 0){\n session_cache_limiter('private_no_expire');\n }\n session_start();\n }\n}\n</code></pre>\n\n<p>With this solution you can prevent any problem with session and start it anytime you need.</p>\n" }, { "answer_id": 391613, "author": "Sachin Saini", "author_id": 208742, "author_profile": "https://wordpress.stackexchange.com/users/208742", "pm_score": 0, "selected": false, "text": "<p>We can use the easy way by init hook. Write this function in the function.php</p>\n<pre><code>function register_my_session() {\n if( !session_id() )\n session_start();\n}\nadd_action('init', 'register_my_session');\n</code></pre>\n<p>after adding this function in function.php you can Set values in sessions like</p>\n<pre><code>$_SESSION['user_country'] = 'india';\n</code></pre>\n<p>Get session value</p>\n<pre><code>echo $_SESSION['user_country'];\n</code></pre>\n<p>for destroying session value</p>\n<pre><code>unset($_SESSION[&quot;user_country&quot;]);\n</code></pre>\n" } ]
2016/08/24
[ "https://wordpress.stackexchange.com/questions/237032", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93811/" ]
I'm iterating over a custom post type that uses an image from the media library for each item. The images are being rendered for each one correctly with the right size, but for some reason it is loading the full image instead of the medium, which is greatly affecting my page load time. Here is what I have: ``` $args = array( 'post_type' => 'recent-project', 'posts_per_page' => -1 ); $projects = new WP_Query( $args ); while ( $projects->have_posts() ) : $projects->the_post(); echo '<a href="' . $get_permalink(); . '">'; echo '<div class="item">'; echo wp_get_attachment_image( get_post_thumbnail_id( $post->ID ), 'medium' ); echo '</div></a>'; endwhile; ``` Anyone know how I can get the medium size to load instead of the full?
There is no regular output and hence no header sent before `template_redirect` on the front end. If you need sessions on the back end too, use the action `wp_loaded` to cover both. Example: ``` add_action( 'template_redirect', function() { $status = session_status(); if ( PHP_SESSION_DISABLED === $status ) { // That's why you cannot rely on sessions! return; } if ( PHP_SESSION_NONE === $status ) { session_start(); } $_SESSION[ 'foo' ] = 'bar'; }); ``` Keep in mind that using sessions adds a whole [set of very complex problems](https://wordpress.stackexchange.com/q/167585/73) to your code, including security, scalability (load balancers), and following time consuming support issues. I don't recommend it.
237,044
<p>According to the <a href="https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/" rel="noreferrer">docs</a>, <code>wp_get_nav_menu_items()</code> parameter 1 accepts</p> <pre><code>(string) (Required) Menu name, ID, or slug. </code></pre> <p>Here is how I'm registering my menus</p> <pre><code>register_nav_menus( array( 'primary' =&gt; 'Navigation primaire', 'secondary' =&gt; 'Navigation secondaire', ) ); </code></pre> <p>Here is how I have tried to load one</p> <pre><code>var_dump( wp_get_nav_menu_items('primary') ); // bool(false) var_dump( wp_get_nav_menu_items('navigation-primaire') ); // bool(false) var_dump( wp_get_nav_menu_items('Navigation primaire') ); // bool(false) var_dump( wp_get_nav_menu_items(51) ); // array([...]) (correct) </code></pre> <p>So, the function will only return the menu when I use the ID. I would much rather use the slug since my site is multilingual and I don't want to have to use different ID's depending on the language.</p> <p>Am I doing something wrong or is this a core bug? I've tried this on the TwentySixteen theme with my multilingual plugin disabled (Polylang).</p>
[ { "answer_id": 237107, "author": "Ignat B.", "author_id": 38121, "author_profile": "https://wordpress.stackexchange.com/users/38121", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code> $menu_name = 'primary'; \n\n if ( ( $locations = get_nav_menu_locations() ) &amp;&amp; isset( $locations[ $menu_name ] ) ) {\n $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );\n\n $menu_items = wp_get_nav_menu_items($menu-&gt;term_id);\n // Your output code\n }\n</code></pre>\n" }, { "answer_id": 267425, "author": "Abuzer Killibacak", "author_id": 119908, "author_profile": "https://wordpress.stackexchange.com/users/119908", "pm_score": 0, "selected": false, "text": "<pre><code>custom_menu('primary');\n\nfunction custom_menu( $theme_location ) {\nif ( ($theme_location) &amp;&amp; ($locations = get_nav_menu_locations()) &amp;&amp; isset($locations[$theme_location]) ) {\n $menu = get_term( $locations[$theme_location], 'nav_menu' );\n $menu_items = wp_get_nav_menu_items($menu-&gt;term_id);\n //your menu code.\n}\n</code></pre>\n" }, { "answer_id": 268883, "author": "JoeMoe1984", "author_id": 32601, "author_profile": "https://wordpress.stackexchange.com/users/32601", "pm_score": 6, "selected": true, "text": "<p>Since nobody has really explained why the function doesn't work the way you thought it did, I shall take a stab at explaining it in detail as I just fell for the same trap as you did.</p>\n\n<p>This is where the docs aren't really clear as to what the slug is referring to. Most people would assume its the slug of the registered menu but thats not correct. Its actually the slug of the term for the taxonomy nav_menu.</p>\n\n<p>Lets dive into the source code to see how the Wordpress core interprets the slug of the menu.</p>\n\n<pre><code>function wp_get_nav_menu_items( $menu, $args = array() ) {\n $menu = wp_get_nav_menu_object( $menu );\n....\n</code></pre>\n\n<p>The first line shows that it uses a function named wp_get_nav_menu_object() to retrieve the menu. It passes the <code>$menu</code> as the first parameter to this function. Since this is what we use for our slug we will have to dive into the source for <code>wp_get_nav_menu_object()</code>.</p>\n\n<pre><code>function wp_get_nav_menu_object( $menu ) {\n $menu_obj = false;\n\n if ( is_object( $menu ) ) {\n $menu_obj = $menu;\n }\n\n if ( $menu &amp;&amp; ! $menu_obj ) {\n $menu_obj = get_term( $menu, 'nav_menu' );\n\n if ( ! $menu_obj ) {\n $menu_obj = get_term_by( 'slug', $menu, 'nav_menu' );\n }\n\n if ( ! $menu_obj ) {\n $menu_obj = get_term_by( 'name', $menu, 'nav_menu' );\n }\n }\n....\n</code></pre>\n\n<p>we can see that this function uses the <code>get_term_by</code> function to retrieve the <code>$menu_obj</code>. This is where we get our menu. </p>\n\n<p>When you create a menu in the Wordpress admin area, it creates a new term. Terms, have slugs based off of their name. So if you have a menu name of \"My Awesome Menu\" Wordpress will generate a slug named \"my-awesome-menu\". You may have registered the menu as \"primary\" but that is not the slug these functions refer to. Its actually the menus term slug.</p>\n\n<p>So to be clear, lets just say you registered a menu like so:</p>\n\n<pre><code>register_nav_menu('primary', 'my primary nav');\n</code></pre>\n\n<p><code>primary</code> is not the slug. <code>my-primary-nav</code> is also not the slug.</p>\n\n<p>Since we created a menu named \"My Awesome Menu\" (as an example), and the slug is 'my-awesome-menu', you can retrieve it like so:</p>\n\n<pre><code>$awesome_menu = wp_get_nav_menu_items( 'my-awesome-menu' );\n</code></pre>\n\n<p>You can see for yourself what the slug is just by checking the database in the wp_terms (or whatever your prefix is) table and look for your menu name in there.</p>\n\n<p>Since you are using a multilingual site or even a multisite, this method won't be the best way to go about it. Since the name and slug could possibly be different.</p>\n\n<p>So the best method is to get the all the menu locations with <code>get_nav_menu_locations()</code> which will return an associative array where the key is the slug of the registered menu and the value is the id of the menu term selected for its location.</p>\n\n<p>With the term id, we can get that terms info and then return the proper slug the function is requiring.</p>\n\n<p>Below is a function that utilizes the <code>wp_get_nav_items()</code> function but you would pass in the registered menu slug. In your case this would be 'primary'.</p>\n\n<h2>Code Solution</h2>\n\n<pre><code>// kind of a long function name but whatevs\nfunction get_menu_items_by_registered_slug($menu_slug) {\n\n $menu_items = array();\n\n if ( ( $locations = get_nav_menu_locations() ) &amp;&amp; isset( $locations[ $menu_slug ] ) ) {\n $menu = get_term( $locations[ $menu_slug ] );\n\n $menu_items = wp_get_nav_menu_items($menu-&gt;term_id);\n\n\n }\n\n return $menu_items;\n\n}\n</code></pre>\n" }, { "answer_id": 302047, "author": "Narek Malkhasyan", "author_id": 112853, "author_profile": "https://wordpress.stackexchange.com/users/112853", "pm_score": 2, "selected": false, "text": "<p>Small modification to the accepted answer</p>\n\n<p>After removing a menu from menu location, <code>$locations[ $menu_slug ]</code> returns <code>0</code>, so it's good to add this check:</p>\n\n<pre><code>function get_menu_items_by_registered_slug($menu_slug) {\n $menu_items = array();\n\n if ( ($locations = get_nav_menu_locations()) &amp;&amp; isset($locations[$menu_slug]) &amp;&amp; $locations[$menu_slug] != 0 ) {\n $menu = get_term( $locations[ $menu_slug ] );\n $menu_items = wp_get_nav_menu_items($menu-&gt;term_id);\n }\n\n return $menu_items;\n}\n</code></pre>\n" } ]
2016/08/24
[ "https://wordpress.stackexchange.com/questions/237044", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44937/" ]
According to the [docs](https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/), `wp_get_nav_menu_items()` parameter 1 accepts ``` (string) (Required) Menu name, ID, or slug. ``` Here is how I'm registering my menus ``` register_nav_menus( array( 'primary' => 'Navigation primaire', 'secondary' => 'Navigation secondaire', ) ); ``` Here is how I have tried to load one ``` var_dump( wp_get_nav_menu_items('primary') ); // bool(false) var_dump( wp_get_nav_menu_items('navigation-primaire') ); // bool(false) var_dump( wp_get_nav_menu_items('Navigation primaire') ); // bool(false) var_dump( wp_get_nav_menu_items(51) ); // array([...]) (correct) ``` So, the function will only return the menu when I use the ID. I would much rather use the slug since my site is multilingual and I don't want to have to use different ID's depending on the language. Am I doing something wrong or is this a core bug? I've tried this on the TwentySixteen theme with my multilingual plugin disabled (Polylang).
Since nobody has really explained why the function doesn't work the way you thought it did, I shall take a stab at explaining it in detail as I just fell for the same trap as you did. This is where the docs aren't really clear as to what the slug is referring to. Most people would assume its the slug of the registered menu but thats not correct. Its actually the slug of the term for the taxonomy nav\_menu. Lets dive into the source code to see how the Wordpress core interprets the slug of the menu. ``` function wp_get_nav_menu_items( $menu, $args = array() ) { $menu = wp_get_nav_menu_object( $menu ); .... ``` The first line shows that it uses a function named wp\_get\_nav\_menu\_object() to retrieve the menu. It passes the `$menu` as the first parameter to this function. Since this is what we use for our slug we will have to dive into the source for `wp_get_nav_menu_object()`. ``` function wp_get_nav_menu_object( $menu ) { $menu_obj = false; if ( is_object( $menu ) ) { $menu_obj = $menu; } if ( $menu && ! $menu_obj ) { $menu_obj = get_term( $menu, 'nav_menu' ); if ( ! $menu_obj ) { $menu_obj = get_term_by( 'slug', $menu, 'nav_menu' ); } if ( ! $menu_obj ) { $menu_obj = get_term_by( 'name', $menu, 'nav_menu' ); } } .... ``` we can see that this function uses the `get_term_by` function to retrieve the `$menu_obj`. This is where we get our menu. When you create a menu in the Wordpress admin area, it creates a new term. Terms, have slugs based off of their name. So if you have a menu name of "My Awesome Menu" Wordpress will generate a slug named "my-awesome-menu". You may have registered the menu as "primary" but that is not the slug these functions refer to. Its actually the menus term slug. So to be clear, lets just say you registered a menu like so: ``` register_nav_menu('primary', 'my primary nav'); ``` `primary` is not the slug. `my-primary-nav` is also not the slug. Since we created a menu named "My Awesome Menu" (as an example), and the slug is 'my-awesome-menu', you can retrieve it like so: ``` $awesome_menu = wp_get_nav_menu_items( 'my-awesome-menu' ); ``` You can see for yourself what the slug is just by checking the database in the wp\_terms (or whatever your prefix is) table and look for your menu name in there. Since you are using a multilingual site or even a multisite, this method won't be the best way to go about it. Since the name and slug could possibly be different. So the best method is to get the all the menu locations with `get_nav_menu_locations()` which will return an associative array where the key is the slug of the registered menu and the value is the id of the menu term selected for its location. With the term id, we can get that terms info and then return the proper slug the function is requiring. Below is a function that utilizes the `wp_get_nav_items()` function but you would pass in the registered menu slug. In your case this would be 'primary'. Code Solution ------------- ``` // kind of a long function name but whatevs function get_menu_items_by_registered_slug($menu_slug) { $menu_items = array(); if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_slug ] ) ) { $menu = get_term( $locations[ $menu_slug ] ); $menu_items = wp_get_nav_menu_items($menu->term_id); } return $menu_items; } ```
237,081
<p>I have a variable that picks up data from the theme settings like background image and such, and it's stored in a separate file with inline <code>style</code> like:</p> <pre><code>$style = 'style="'.$background_image.$background_color.'"'; </code></pre> <p>The <code>$background_image</code> and <code>$background_color</code> are just css values for <code>background_image</code> and <code>background_color</code> that you can set in the options.</p> <p>I'm using this variable in the header like</p> <pre><code>&lt;header id="header" class="myheader" &lt;?php echo $style; ?&gt;&gt; </code></pre> <p>Now this is not safe and should be sanitized, so I added <code>esc_attr()</code> to escape the attribute.</p> <pre><code>&lt;header id="header" class="myheader" &lt;?php echo esc_attr( $style ); ?&gt;&gt; </code></pre> <p>This, in turn, made my double quotes into <code>&amp;quot;</code> and the style didn't work of course. Now I could put <code>htmlspecialchars_decode()</code> around the escaped value, but that kinda seems... odd.</p> <p>Another solution would be to put the <code>style</code> directly in the header, and only put the escaped values in, which would solve the double quote issue, but in the case that no styling has been set I'm left with an empty <code>style</code> in my element, and that also seems kinda unnecessary.</p> <p>What is the best solution out there? </p> <p>Also if I use <code>htmlspecialchars_decode()</code> I still get a phpcs error about escaping function and that is utterly annoying...</p>
[ { "answer_id": 237050, "author": "Ivan Miranda", "author_id": 101610, "author_profile": "https://wordpress.stackexchange.com/users/101610", "pm_score": -1, "selected": false, "text": "<p>Paste your WordPress Address (URL) and your Site Address (URL). Plus give where you installed WP (maybe is this a problem, maybe not).</p>\n\n<p>Cheers</p>\n" }, { "answer_id": 237051, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 0, "selected": false, "text": "<p>I'm not able to visit either link successfully. I get a redirect loop error:</p>\n\n<blockquote>\n <p>ERR_TOO_MANY_REDIRECTS</p>\n</blockquote>\n\n<p>Changing the URL of your website in <em>Settings > General > Site URL</em> is not enough unfortunately. You will still have your post content with your sub domain URL (<code>clasificados.example.com</code>) causing your website to not load properly.</p>\n\n<p>Once you've downloaded and imported your database to your localhost. Follow these steps:</p>\n\n<ol>\n<li>Go and download <a href=\"https://github.com/interconnectit/Search-Replace-DB/archive/master.zip\" rel=\"nofollow noreferrer\">Interconnect IT's Database Search &amp; Replace Script here</a></li>\n<li>Unzip the file and drop the folder where your WordPress is installed (the root) and rename the folder to <strong><code>replace</code></strong> (<a href=\"https://i.stack.imgur.com/J9Ga5.png\" rel=\"nofollow noreferrer\">screenshot</a>)</li>\n<li>Navigate to the new folder you created in your browser (ex: <code>http://clasificadosvallemedio.com/replace</code>) and <a href=\"https://i.stack.imgur.com/pbED1.png\" rel=\"nofollow noreferrer\">you will see the search/replace tool</a></li>\n<li>It should be pretty self-explanatory up to this point:\n\n<ul>\n<li><strong><code>search for…</code></strong>: enter your old subdomain (<code>http://clasificados.example.com</code>) </li>\n<li><strong><code>replace with…</code></strong>: - enter your new domain (<code>http://clasificadosvallemedio.com</code>)</li>\n</ul></li>\n</ol>\n\n<p>You can click the <em>dry run</em> button under <em>actions</em> to see what it will be replacing before you execute the script. Once you're done be sure to remove the <code>/replace/</code> folder.</p>\n" } ]
2016/08/25
[ "https://wordpress.stackexchange.com/questions/237081", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58895/" ]
I have a variable that picks up data from the theme settings like background image and such, and it's stored in a separate file with inline `style` like: ``` $style = 'style="'.$background_image.$background_color.'"'; ``` The `$background_image` and `$background_color` are just css values for `background_image` and `background_color` that you can set in the options. I'm using this variable in the header like ``` <header id="header" class="myheader" <?php echo $style; ?>> ``` Now this is not safe and should be sanitized, so I added `esc_attr()` to escape the attribute. ``` <header id="header" class="myheader" <?php echo esc_attr( $style ); ?>> ``` This, in turn, made my double quotes into `&quot;` and the style didn't work of course. Now I could put `htmlspecialchars_decode()` around the escaped value, but that kinda seems... odd. Another solution would be to put the `style` directly in the header, and only put the escaped values in, which would solve the double quote issue, but in the case that no styling has been set I'm left with an empty `style` in my element, and that also seems kinda unnecessary. What is the best solution out there? Also if I use `htmlspecialchars_decode()` I still get a phpcs error about escaping function and that is utterly annoying...
I'm not able to visit either link successfully. I get a redirect loop error: > > ERR\_TOO\_MANY\_REDIRECTS > > > Changing the URL of your website in *Settings > General > Site URL* is not enough unfortunately. You will still have your post content with your sub domain URL (`clasificados.example.com`) causing your website to not load properly. Once you've downloaded and imported your database to your localhost. Follow these steps: 1. Go and download [Interconnect IT's Database Search & Replace Script here](https://github.com/interconnectit/Search-Replace-DB/archive/master.zip) 2. Unzip the file and drop the folder where your WordPress is installed (the root) and rename the folder to **`replace`** ([screenshot](https://i.stack.imgur.com/J9Ga5.png)) 3. Navigate to the new folder you created in your browser (ex: `http://clasificadosvallemedio.com/replace`) and [you will see the search/replace tool](https://i.stack.imgur.com/pbED1.png) 4. It should be pretty self-explanatory up to this point: * **`search for…`**: enter your old subdomain (`http://clasificados.example.com`) * **`replace with…`**: - enter your new domain (`http://clasificadosvallemedio.com`) You can click the *dry run* button under *actions* to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder.
237,086
<p>Is there a way I could show only the comments by a particular user role to his same user role?</p> <p>For example: The logged in user belongs to the "Advertisers" user role, he should only see the comments made by him and all users under his role.</p> <p>Thank you.</p>
[ { "answer_id": 237098, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 0, "selected": false, "text": "<p>Here's one way (untested) to display comments from users in the same role as the current user:</p>\n\n<pre><code>add_filter( 'comments_template_query_args', function( array $args )\n{ \n // Nothing to do for visitors\n if( ! is_user_logged_in() )\n return $args;\n\n // Nothing to do for threaded comments \n if( isset( $args['hierarchical'] ) &amp;&amp; 'threaded' === $args['hierarchical'] )\n return $args;\n\n // Get current user\n $u = wp_get_current_user();\n\n // Nothing to do for users without any roles\n if( ! isset( $u-&gt;roles ) ||empty( $u-&gt;roles ) )\n return $args;\n\n // Fetch user ids with the same role\n $user_ids = get_users( [ 'role__in' =&gt; (array) $u-&gt;roles, 'fields' =&gt; 'ID' ] );\n\n // Restrict comment authors\n if( ! empty( $user_ids ) )\n $args['author__in'] = (array) $user_ids;\n\n return $args;\n\n} );\n</code></pre>\n\n<p>Here we assume the user base is not huge and we use the <code>comments_template_query_args</code> filter to target the main comments query in the <code>comments_template()</code> part in the theme.</p>\n" }, { "answer_id": 237101, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<p>Yes you can, </p>\n\n<p><strong>Frontend only</strong></p>\n\n<p>you would need to check each post comment author for it's role. If the role of that comment author is not <em>adverstisers</em> then remove it from the array of comments attached to that post.</p>\n\n<p>Then you would have to return only the comments if the current logged in user is also from the <em>advertisers</em> role.</p>\n\n<p>using the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/comments_array\" rel=\"nofollow\"><code>comments_array</code></a> filter we can go over each comments attached to a post. But this filter is applied in comments_template so it won't affect the access comments in backend.</p>\n\n<p>Here's how you can do it</p>\n\n<pre><code>add_filter( 'comments_array' , 'wpse_filter_by_role_frontend' , 10, 2 );\nfunction wpse_filter_by_role_frontend( $comments, $post_id ){\n\n $current_user = wp_get_current_user(); // retrieve the currently logged in user\n\n // go over each comments for the current post\n foreach( $comments as $key =&gt; $comment ){\n\n $comment_author = new WP_User( $comment-&gt;user_id ); // for each comment get the author user object\n\n // here we say unset the current comment if the role of the comment author is not the same as the role of the logged in user\n if( $comment_author-&gt;roles[0] != $current_user-&gt;roles[0] ){\n unset( $comments[$key] );\n }\n\n }\n\n // Return the filtered $comments array \n return $comments;\n\n\n}\n</code></pre>\n\n<p><strong>Frontend and backend</strong></p>\n\n<pre><code>add_action( 'pre_get_comments' , 'wpse_hide_for_backend' );\nfunction wpse_hide_for_backend( $comments_query ){\n\n // Hide all for non logged in users \n if( !is_user_logged_in() ){\n return $comments_query-&gt;query_vars['comment__in'] = array(0);\n }\n\n $current_user = wp_get_current_user();\n\n // if you don't want to apply restrictions to admins\n if( $current_user-&gt;roles[0] == 'administrator' ){\n return $comments_query;\n }\n\n $user_ids = get_users( array( \n 'role__in' =&gt; $current_user-&gt;roles, \n 'fields' =&gt; 'ID' \n ) );\n\n $comments_query-&gt;query_vars['author__in'] = $user_ids;\n\n}\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>I modified the second function.</p>\n\n<p>Seeing @birgire's answer I realized there was an <code>author_in</code> query arg and using <code>get_users</code> with query arg <code>role__in</code> we can achieve the desired effect on both front and back end.</p>\n\n<p>So thanks to @birgire for the inspiration :)</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>To allow more than just the role of the current user in the fetching of comments (like adding comments made by administrators) simply append the array in <code>role__in</code> with the desired roles</p>\n\n<p>so the function would become</p>\n\n<pre><code>add_action( 'pre_get_comments' , 'wpse_hide_for_backend' );\nfunction wpse_hide_for_backend( $comments_query ){\n\n // Hide all for non logged in users \n if( !is_user_logged_in() ){\n return $comments_query-&gt;query_vars['comment__in'] = array(0);\n }\n\n $current_user = wp_get_current_user();\n\n // if you don't want to apply restrictions to admins\n if( $current_user-&gt;roles[0] == 'administrator' ){\n return $comments_query;\n }\n\n $user_ids = get_users( array( \n 'role__in' =&gt; array(\n 'administrator',\n $current_user-&gt;roles[0],\n ), \n 'fields' =&gt; 'ID' \n ) );\n\n $comments_query-&gt;query_vars['author__in'] = $user_ids;\n\n}\n</code></pre>\n\n<p>or (for readability on this forum)</p>\n\n<pre><code>$permitted_roles = array(\n 'administrator',\n $current_user-&gt;roles[0],\n);\n\n$user_ids = get_users( array( \n 'role__in' =&gt; $permitted_roles, \n 'fields' =&gt; 'ID' \n ) );\n</code></pre>\n" } ]
2016/08/25
[ "https://wordpress.stackexchange.com/questions/237086", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101629/" ]
Is there a way I could show only the comments by a particular user role to his same user role? For example: The logged in user belongs to the "Advertisers" user role, he should only see the comments made by him and all users under his role. Thank you.
Yes you can, **Frontend only** you would need to check each post comment author for it's role. If the role of that comment author is not *adverstisers* then remove it from the array of comments attached to that post. Then you would have to return only the comments if the current logged in user is also from the *advertisers* role. using the [`comments_array`](https://codex.wordpress.org/Plugin_API/Filter_Reference/comments_array) filter we can go over each comments attached to a post. But this filter is applied in comments\_template so it won't affect the access comments in backend. Here's how you can do it ``` add_filter( 'comments_array' , 'wpse_filter_by_role_frontend' , 10, 2 ); function wpse_filter_by_role_frontend( $comments, $post_id ){ $current_user = wp_get_current_user(); // retrieve the currently logged in user // go over each comments for the current post foreach( $comments as $key => $comment ){ $comment_author = new WP_User( $comment->user_id ); // for each comment get the author user object // here we say unset the current comment if the role of the comment author is not the same as the role of the logged in user if( $comment_author->roles[0] != $current_user->roles[0] ){ unset( $comments[$key] ); } } // Return the filtered $comments array return $comments; } ``` **Frontend and backend** ``` add_action( 'pre_get_comments' , 'wpse_hide_for_backend' ); function wpse_hide_for_backend( $comments_query ){ // Hide all for non logged in users if( !is_user_logged_in() ){ return $comments_query->query_vars['comment__in'] = array(0); } $current_user = wp_get_current_user(); // if you don't want to apply restrictions to admins if( $current_user->roles[0] == 'administrator' ){ return $comments_query; } $user_ids = get_users( array( 'role__in' => $current_user->roles, 'fields' => 'ID' ) ); $comments_query->query_vars['author__in'] = $user_ids; } ``` **EDIT** I modified the second function. Seeing @birgire's answer I realized there was an `author_in` query arg and using `get_users` with query arg `role__in` we can achieve the desired effect on both front and back end. So thanks to @birgire for the inspiration :) **EDIT** To allow more than just the role of the current user in the fetching of comments (like adding comments made by administrators) simply append the array in `role__in` with the desired roles so the function would become ``` add_action( 'pre_get_comments' , 'wpse_hide_for_backend' ); function wpse_hide_for_backend( $comments_query ){ // Hide all for non logged in users if( !is_user_logged_in() ){ return $comments_query->query_vars['comment__in'] = array(0); } $current_user = wp_get_current_user(); // if you don't want to apply restrictions to admins if( $current_user->roles[0] == 'administrator' ){ return $comments_query; } $user_ids = get_users( array( 'role__in' => array( 'administrator', $current_user->roles[0], ), 'fields' => 'ID' ) ); $comments_query->query_vars['author__in'] = $user_ids; } ``` or (for readability on this forum) ``` $permitted_roles = array( 'administrator', $current_user->roles[0], ); $user_ids = get_users( array( 'role__in' => $permitted_roles, 'fields' => 'ID' ) ); ```
237,100
<p>For example, I have an url:</p> <pre><code>mysite.com/author/admin </code></pre> <p>It's not considered as single post or single page to add meta tag via SEO plugin. And to this page I want to add something like:</p> <pre><code>&lt;meta name="description" content="All posts by author admin."/&gt; </code></pre> <p>Is there are any way to do this? Thanks in advance!</p>
[ { "answer_id": 237113, "author": "teheteh", "author_id": 98699, "author_profile": "https://wordpress.stackexchange.com/users/98699", "pm_score": 0, "selected": false, "text": "<p>UPDT: Figured it out. Had to just hardcode it in header.php file located in my theme name folder.</p>\n\n<pre><code>&lt;!-- Meta Tags --&gt;\n\n&lt;?php if (is_archive() &amp;&amp; !is_category()){\n echo '&lt;meta property=\"og:description\" content=\"Your description\"/&gt;';\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 237116, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>There is not a standerized way to add HTML meta tags in WordPress but you can use <a href=\"https://developer.wordpress.org/reference/hooks/wp_head/\" rel=\"nofollow\"><code>wp_head</code> action</a> as a generic way to add meta tags.</p>\n\n<p>I think description meta tag should not be in the theme, as you suggest in your answer, because description meta tag is a property of the document, nothing to do with the look and feel of the document, that is, the theme.</p>\n\n<p>This is a samlple code to do it:</p>\n\n<pre><code>add_action( 'wp_head', 'cyb_author_archive_meta_desc' );\nfunction cyb_author_archive_meta_desc() {\n\n // Check is we are in author archive\n // https://developer.wordpress.org/reference/functions/is_author/\n if( is_author() ) {\n // get_queried_object() returns current author in author's arvhives\n // https://developer.wordpress.org/reference/classes/wp_query/get_queried_object/\n $author = get_queried_object();\n\n // Generate meta description\n $description = sprintf( __( 'All posts by author %s', 'cyb-textdomain' ), $author-&gt;display_name );\n\n // Print description meta tag\n echo '&lt;meta name=\"description\" content=\"' . esc_attr( $description ) . '\"&gt;';\n }\n\n}\n</code></pre>\n" } ]
2016/08/25
[ "https://wordpress.stackexchange.com/questions/237100", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98699/" ]
For example, I have an url: ``` mysite.com/author/admin ``` It's not considered as single post or single page to add meta tag via SEO plugin. And to this page I want to add something like: ``` <meta name="description" content="All posts by author admin."/> ``` Is there are any way to do this? Thanks in advance!
There is not a standerized way to add HTML meta tags in WordPress but you can use [`wp_head` action](https://developer.wordpress.org/reference/hooks/wp_head/) as a generic way to add meta tags. I think description meta tag should not be in the theme, as you suggest in your answer, because description meta tag is a property of the document, nothing to do with the look and feel of the document, that is, the theme. This is a samlple code to do it: ``` add_action( 'wp_head', 'cyb_author_archive_meta_desc' ); function cyb_author_archive_meta_desc() { // Check is we are in author archive // https://developer.wordpress.org/reference/functions/is_author/ if( is_author() ) { // get_queried_object() returns current author in author's arvhives // https://developer.wordpress.org/reference/classes/wp_query/get_queried_object/ $author = get_queried_object(); // Generate meta description $description = sprintf( __( 'All posts by author %s', 'cyb-textdomain' ), $author->display_name ); // Print description meta tag echo '<meta name="description" content="' . esc_attr( $description ) . '">'; } } ```
237,118
<p>I've been trying to find an explanation of the following code which I'm using to add pagination to a custom category template.</p> <pre><code>$catpage = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $catnum = 3; $offset = ($catnum * $catpage) - 3; </code></pre> <p>In particular, I would like to know what exactly the query variable "paged" refers to and also the meaning of "offset".</p>
[ { "answer_id": 237121, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>The following code line:</p>\n\n<pre><code>$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n</code></pre>\n\n<p>is using the <a href=\"http://php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow\"><em>ternary operator</em></a> <code>?:</code></p>\n\n<p>It's a shorthand notation for</p>\n\n<pre><code>if( get_query_var( 'paged' ) )\n $paged = get_query_var('paged' );\nelse\n $paged = 1;\n</code></pre>\n\n<p>This can in fact be simplified further, by using the the second input parameter for the default value, namely:</p>\n\n<pre><code>$paged = get_query_var( 'paged', 1 );\n</code></pre>\n\n<p>See the <code>get_query_var()</code> function definition <a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"nofollow\">here</a>.</p>\n\n<p>What are query variables?</p>\n\n<p>Let me quote the <a href=\"https://codex.wordpress.org/WordPress_Query_Vars\" rel=\"nofollow\">Codex</a>:</p>\n\n<blockquote>\n <p>Query vars define a query for WordPress posts.</p>\n \n <p>When ugly permalinks are enabled, query variables can be seen in the\n URL. For example, in the URL <a href=\"http://example.com/?p=1\" rel=\"nofollow\">http://example.com/?p=1</a> the p query var\n is set to 1, which will display the single post with an ID of 1.</p>\n \n <p>When pretty permalinks are enabled, URLs don't include query\n variables. Instead, WordPress transforms the URL into query vars via\n the Rewrite API, which are used to populate the query.</p>\n</blockquote>\n\n<p>I see you've added more code to the question:</p>\n\n<pre><code>$catpage = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;\n$catnum = 3;\n$offset = ($catnum * $catpage) - 3;\n</code></pre>\n\n<p>Let's check out the category archive for a category called <code>blue</code>:</p>\n\n<p>When the <code>paged</code> query variable isn't defined, on the first page</p>\n\n<pre><code>http://example.tld/category/blue/\n</code></pre>\n\n<p>then we set it as 1 and then:</p>\n\n<pre><code>offset = 3 * 1 - 3 = 0\n</code></pre>\n\n<p>When the <code>paged</code> query variable is 2 (on the second page)</p>\n\n<pre><code>http://example.tld/category/blue/page/2/\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>offset = 3 * 2 - 3 = 6 - 3 = 3\n</code></pre>\n\n<p>When the <code>paged</code> query variable is 3 on the third page </p>\n\n<pre><code>http://example.tld/category/blue/page/3/\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>offset = 3 * 3 - 3 = 9 - 3 = 6\n</code></pre>\n\n<p>etc</p>\n" }, { "answer_id": 237123, "author": "Bhagchandani", "author_id": 101627, "author_profile": "https://wordpress.stackexchange.com/users/101627", "pm_score": 1, "selected": false, "text": "<p>It will return the current page number. If the <code>paged</code> variable is not set, it will return <code>1</code>. <code>1</code> stands for page number 1 in pagination. </p>\n" } ]
2016/08/25
[ "https://wordpress.stackexchange.com/questions/237118", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68414/" ]
I've been trying to find an explanation of the following code which I'm using to add pagination to a custom category template. ``` $catpage = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $catnum = 3; $offset = ($catnum * $catpage) - 3; ``` In particular, I would like to know what exactly the query variable "paged" refers to and also the meaning of "offset".
The following code line: ``` $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; ``` is using the [*ternary operator*](http://php.net/manual/en/language.operators.comparison.php) `?:` It's a shorthand notation for ``` if( get_query_var( 'paged' ) ) $paged = get_query_var('paged' ); else $paged = 1; ``` This can in fact be simplified further, by using the the second input parameter for the default value, namely: ``` $paged = get_query_var( 'paged', 1 ); ``` See the `get_query_var()` function definition [here](https://developer.wordpress.org/reference/functions/get_query_var/). What are query variables? Let me quote the [Codex](https://codex.wordpress.org/WordPress_Query_Vars): > > Query vars define a query for WordPress posts. > > > When ugly permalinks are enabled, query variables can be seen in the > URL. For example, in the URL <http://example.com/?p=1> the p query var > is set to 1, which will display the single post with an ID of 1. > > > When pretty permalinks are enabled, URLs don't include query > variables. Instead, WordPress transforms the URL into query vars via > the Rewrite API, which are used to populate the query. > > > I see you've added more code to the question: ``` $catpage = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $catnum = 3; $offset = ($catnum * $catpage) - 3; ``` Let's check out the category archive for a category called `blue`: When the `paged` query variable isn't defined, on the first page ``` http://example.tld/category/blue/ ``` then we set it as 1 and then: ``` offset = 3 * 1 - 3 = 0 ``` When the `paged` query variable is 2 (on the second page) ``` http://example.tld/category/blue/page/2/ ``` then: ``` offset = 3 * 2 - 3 = 6 - 3 = 3 ``` When the `paged` query variable is 3 on the third page ``` http://example.tld/category/blue/page/3/ ``` then: ``` offset = 3 * 3 - 3 = 9 - 3 = 6 ``` etc
237,131
<p>This wonderful answer to a related question; that of displaying dimensions in the media library. </p> <p><a href="https://wordpress.stackexchange.com/questions/30894/display-image-size-in-media-library-screen">display image size in media library screen</a></p> <p>is it possible to use this technique to display the file size as a column? If so how?</p>
[ { "answer_id": 237138, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 4, "selected": true, "text": "<p>In your theme's <code>functions.php</code> add the following code to get the file size for all of your items in the <em>Media</em> library:</p>\n\n<pre><code>add_filter( 'manage_upload_columns', 'wpse_237131_add_column_file_size' );\nadd_action( 'manage_media_custom_column', 'wpse_237131_column_file_size', 10, 2 );\n\nfunction wpse_237131_add_column_file_size( $columns ) { // Create the column\n $columns['filesize'] = 'File Size';\n return $columns;\n}\nfunction wpse_237131_column_file_size( $column_name, $media_item ) { // Display the file size\n if ( 'filesize' != $column_name || !wp_attachment_is_image( $media_item ) ) {\n return;\n }\n $filesize = filesize( get_attached_file( $media_item ) );\n $filesize = size_format($filesize, 2);\n echo $filesize;\n}\n</code></pre>\n" }, { "answer_id": 237350, "author": "Chris Pink", "author_id": 57686, "author_profile": "https://wordpress.stackexchange.com/users/57686", "pm_score": 2, "selected": false, "text": "<p>Just a little bit of extra work, change the function above to this;</p>\n\n<pre><code>function wpse_237131_column_file_size( $column_name, $media_item ) { // Display the file size\nif ( 'filesize' != $column_name || !wp_attachment_is_image( $media_item ) ) {\n return;\n}\n$filesize = filesize( get_attached_file( $media_item ) );\n$filesize = size_format($filesize, 2);\necho $filesize;\n}\n</code></pre>\n" } ]
2016/08/25
[ "https://wordpress.stackexchange.com/questions/237131", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57686/" ]
This wonderful answer to a related question; that of displaying dimensions in the media library. [display image size in media library screen](https://wordpress.stackexchange.com/questions/30894/display-image-size-in-media-library-screen) is it possible to use this technique to display the file size as a column? If so how?
In your theme's `functions.php` add the following code to get the file size for all of your items in the *Media* library: ``` add_filter( 'manage_upload_columns', 'wpse_237131_add_column_file_size' ); add_action( 'manage_media_custom_column', 'wpse_237131_column_file_size', 10, 2 ); function wpse_237131_add_column_file_size( $columns ) { // Create the column $columns['filesize'] = 'File Size'; return $columns; } function wpse_237131_column_file_size( $column_name, $media_item ) { // Display the file size if ( 'filesize' != $column_name || !wp_attachment_is_image( $media_item ) ) { return; } $filesize = filesize( get_attached_file( $media_item ) ); $filesize = size_format($filesize, 2); echo $filesize; } ```
237,149
<p>I know that according default Wordpress boot process, firstly <code>functions.php</code> is called, after that goes all theme stuff. But I am currently going to refactor my theme completely to optimize it. My idea is to have one base css file for common properties, normalize, colors. Or to keep single css file, but in this case I need to hardcode switch case in <code>functions.php</code> in order to determine page. And another one specific for each page, because this doesn't make sense to load huge css style file with all styles defined. </p> <p>So my question is what is the best place to to hook for loading specific script/style ? </p> <p>Should it be <code>header-xxx.php</code> or another file ? Maybe there is a way to implement this idea in more scalable and elegant way ? </p> <p>I would be grateful for any help.</p>
[ { "answer_id": 237153, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 5, "selected": true, "text": "<p>It all depends on the scale of your customizations and how you will organize your stuff. But there is 2 main ways of doing it. <strong><em>functions.php</em></strong> and <strong><em>template files</em></strong></p>\n\n<p>The way I like to do it, is <strong>register</strong> all my script/styles in functions.php so I know what I will work with but I will <strong>enqueue</strong> only what I need when I need it.</p>\n\n<p>You could enqueue all your stuff conditionally within your functions.php file ( <code>if( is_page( 'blah') { //... enqueue stuff }</code> ) or you could make use of <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"noreferrer\">template files</a> to style specific categories/tags/posts/pages etc. </p>\n\n<p>Then, within that template file, you call your <strong>enqueue</strong> script/style files there. That makes it also neet way to understand what is loaded where.</p>\n\n<p>But definitely, if you wish to break down your stylesheet into smaller files you will need to use</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_register_style\" rel=\"noreferrer\"><code>wp_register_style</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"noreferrer\"><code>wp_enqueue_style</code></a></li>\n</ul>\n\n<p>The same logic would apply to script with corresponding <strong>register/enqueue</strong> functions</p>\n\n<p>Also, take into consideration the number of requests in your strategy, if you do break your stuff down into multiple files, try to keep the number of loaded files low so you don't negatively affect page load that way.</p>\n\n<p>There is another thing you can do to speed up page load. If you tell the browser to cache your stylesheets, then maybe 1 (or a small few) would have more chances to be loaded from cache then if you have multiple files all over your site and they always need to be fetch from the server because it's a new file request on each new page that is loaded. So keep this in mind to.</p>\n\n<p>Regardless, caching 1 or many assets is a good approach and will increase your website perceived responsiveness in terms of site speed.</p>\n\n<p>If you need more guidance on how to use those functions, just let us know.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>The main reasons for registering scripts are as follow</p>\n\n<ul>\n<li>Makes it easier to call a script/style when we need it</li>\n<li>Makes it possible to use a registered script/style as a dependency for a file we need to load.</li>\n<li>Prevent ourselves to write the same code more than we need to, effectively simplifying our code</li>\n<li>More things that I might not be thinking of right now</li>\n</ul>\n\n<p><em>NOTE</em></p>\n\n<p>A script/style that has been registered doesn't need to be enqueued if it is listed as a <code>$deps</code> of the file you are currently enqueuing.</p>\n\n<p>An example (not necessarily how you should do it, but so you understand the purpose)</p>\n\n<p>I have registered </p>\n\n<ul>\n<li>common-style.css</li>\n<li>navigation.css</li>\n<li>buttons.css</li>\n</ul>\n\n<p>Now those style are registered, so if I go on a <em>specific</em> page and want to apply a different styling there. I enqueue on that page (either by conditional statement in functions.php or in my page template) <code>specific-style.css</code> like so.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_specific_style' );\nfunction my_specific_style(){\n wp_enqueue_style( 'specific-style', get_stylesheet_directory_uri() . '/path/to/specific-style.css', array( 'common-style', 'navigation', 'button') );\n}\n</code></pre>\n\n<p>Note that the array in <code>wp_enqueue_style</code> is a array of the handles of already registered styles. WP will conveniently load all 4 files in the correct order to respect dependency.</p>\n\n<p>You could cascade dependency by simply registering each script/style with correct dependency</p>\n\n<p>i.e <strong>buttons.css</strong> depends on <strong>navigation.css</strong> that depends on <strong>common-style.css</strong></p>\n\n<p>If I register with that logic in mind, I only need to enqueue <strong>specific-style.css</strong> with <strong>buttons.css</strong> as a dependency and WP will daisy chain the loading to respect the order.</p>\n" }, { "answer_id": 237157, "author": "zendka", "author_id": 89608, "author_profile": "https://wordpress.stackexchange.com/users/89608", "pm_score": 3, "selected": false, "text": "<p>\"<strong>refactor</strong>\", \"<strong>optimise</strong>\", \"<strong>scalable</strong>\", \"<strong>elegant</strong>\". Great concerns! You're on the right path. However splitting a CSS file into several is not the answer for these concerns. Here's why:</p>\n\n<p>Browsers cache CSS files. So once the first page loads the browser won't request the same CSS file for the next page. Yes, the first page load will be slightly, unnoticeably slower. But the rest of the pages will benefit from this.</p>\n\n<p><strong>Fewer requests</strong> is one of most important ways to <strong>optimise</strong> website speed. (see <a href=\"http://stevesouders.com/hpws/rules.php\" rel=\"nofollow\">Steve Souders</a> or <a href=\"https://developer.yahoo.com/blogs/ydn/high-performance-sites-rule-1-fewer-http-requests-7163.html\" rel=\"nofollow\">this article</a>).</p>\n\n<p>A further optimisation is to <strong>minify</strong> your CSS. (see <a href=\"https://developers.google.com/speed/docs/insights/MinifyResources\" rel=\"nofollow\">Google PageSpeed post</a>.) Thanks @bynicolas for the suggestion.</p>\n\n<p>Sure you may say, but what about <strong>elegance</strong>? Here's the good news: <strong>Sass</strong> and <strong>LESS</strong>. They allow you to write less code, split it into several files that are compiled into one CSS file, and much much more.</p>\n" } ]
2016/08/25
[ "https://wordpress.stackexchange.com/questions/237149", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93387/" ]
I know that according default Wordpress boot process, firstly `functions.php` is called, after that goes all theme stuff. But I am currently going to refactor my theme completely to optimize it. My idea is to have one base css file for common properties, normalize, colors. Or to keep single css file, but in this case I need to hardcode switch case in `functions.php` in order to determine page. And another one specific for each page, because this doesn't make sense to load huge css style file with all styles defined. So my question is what is the best place to to hook for loading specific script/style ? Should it be `header-xxx.php` or another file ? Maybe there is a way to implement this idea in more scalable and elegant way ? I would be grateful for any help.
It all depends on the scale of your customizations and how you will organize your stuff. But there is 2 main ways of doing it. ***functions.php*** and ***template files*** The way I like to do it, is **register** all my script/styles in functions.php so I know what I will work with but I will **enqueue** only what I need when I need it. You could enqueue all your stuff conditionally within your functions.php file ( `if( is_page( 'blah') { //... enqueue stuff }` ) or you could make use of [template files](https://developer.wordpress.org/themes/basics/template-hierarchy/) to style specific categories/tags/posts/pages etc. Then, within that template file, you call your **enqueue** script/style files there. That makes it also neet way to understand what is loaded where. But definitely, if you wish to break down your stylesheet into smaller files you will need to use * [`wp_register_style`](https://codex.wordpress.org/Function_Reference/wp_register_style) * [`wp_enqueue_style`](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) The same logic would apply to script with corresponding **register/enqueue** functions Also, take into consideration the number of requests in your strategy, if you do break your stuff down into multiple files, try to keep the number of loaded files low so you don't negatively affect page load that way. There is another thing you can do to speed up page load. If you tell the browser to cache your stylesheets, then maybe 1 (or a small few) would have more chances to be loaded from cache then if you have multiple files all over your site and they always need to be fetch from the server because it's a new file request on each new page that is loaded. So keep this in mind to. Regardless, caching 1 or many assets is a good approach and will increase your website perceived responsiveness in terms of site speed. If you need more guidance on how to use those functions, just let us know. **EDIT** The main reasons for registering scripts are as follow * Makes it easier to call a script/style when we need it * Makes it possible to use a registered script/style as a dependency for a file we need to load. * Prevent ourselves to write the same code more than we need to, effectively simplifying our code * More things that I might not be thinking of right now *NOTE* A script/style that has been registered doesn't need to be enqueued if it is listed as a `$deps` of the file you are currently enqueuing. An example (not necessarily how you should do it, but so you understand the purpose) I have registered * common-style.css * navigation.css * buttons.css Now those style are registered, so if I go on a *specific* page and want to apply a different styling there. I enqueue on that page (either by conditional statement in functions.php or in my page template) `specific-style.css` like so. ``` add_action( 'wp_enqueue_scripts', 'my_specific_style' ); function my_specific_style(){ wp_enqueue_style( 'specific-style', get_stylesheet_directory_uri() . '/path/to/specific-style.css', array( 'common-style', 'navigation', 'button') ); } ``` Note that the array in `wp_enqueue_style` is a array of the handles of already registered styles. WP will conveniently load all 4 files in the correct order to respect dependency. You could cascade dependency by simply registering each script/style with correct dependency i.e **buttons.css** depends on **navigation.css** that depends on **common-style.css** If I register with that logic in mind, I only need to enqueue **specific-style.css** with **buttons.css** as a dependency and WP will daisy chain the loading to respect the order.
237,195
<p>bbPress has an annoying error about <code>bbp_setup_current_user was called incorrectly.</code> <a href="https://bbpress.org/forums/topic/bbp_setup_current_user-was-called-incorrectly/" rel="noreferrer">bbPress topic</a> and <a href="https://bbpress.trac.wordpress.org/ticket/2412" rel="noreferrer">bbPress ticket #2412</a>, and it looks like nothing will change to fix it. </p> <p>On the site we used to use forum as a support platform, but has since then moved to a ticket system, so I've closed the forums, but you can look through them. I've also commented out the notice that was thrown in the backend because of it, but the problem is that the <code>error.log</code> on the server is filled with such errors (it's 85MB during the last 4 days). It's all like this:</p> <blockquote> <p>[Fri Aug 26 02:00:52.251831 2016] [:error] [pid 1832] [client xx.xx.xx.xx:32824] PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'bbp_setup_current_user' not found or invalid function name in /var/www/html/wp-includes/plugin.php on line 524</p> </blockquote> <p>So is there any kind of command I can use to suppress the writing of this specific warning in the error log? I'd still like to have possible errors written here. </p>
[ { "answer_id": 271698, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 2, "selected": false, "text": "<p>\"Technically\" it's just a PHP warning and not an error, and you should not have warnings enabled on production servers. You can disable PHP from logging warnings and it will still log errors to the error log file.</p>\n\n<p>You can disable PHP warnings by setting it in a custom php.ini file on the server (all errors except for warnings):\n<code>error_reporting = E_ALL &amp; ~E_WARNING</code></p>\n\n<p>or try setting it with PHP:</p>\n\n<p><code>error_reporting(E_ALL &amp; ~E_WARNING);</code></p>\n\n<p>From <code>php.ini</code> file:</p>\n\n<pre><code>; Common Values:\n; E_ALL (Show all errors, warnings and notices including coding standards.)\n; E_ALL &amp; ~E_NOTICE (Show all errors, except for notices)\n; E_ALL &amp; ~E_NOTICE &amp; ~E_STRICT (Show all errors, except for notices and coding standards warnings.)\n; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)\n; Default Value: E_ALL &amp; ~E_NOTICE &amp; ~E_STRICT &amp; ~E_DEPRECATED\n; Development Value: E_ALL\n; Production Value: E_ALL &amp; ~E_DEPRECATED &amp; ~E_STRICT\n; http://php.net/error-reporting\n</code></pre>\n" }, { "answer_id": 325291, "author": "Get Result", "author_id": 158609, "author_profile": "https://wordpress.stackexchange.com/users/158609", "pm_score": 0, "selected": false, "text": "<pre><code>/ Enable WP_DEBUG mode\ndefine( 'WP_DEBUG', true );\n\n// Enable Debug logging to the /wp-content/debug.log file\ndefine( 'WP_DEBUG_LOG', true );\n\n// Disable display of errors and warnings \ndefine( 'WP_DEBUG_DISPLAY', false );\n@ini_set( 'display_errors', 0 );\n\n// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)\ndefine( 'SCRIPT_DEBUG', true );\n</code></pre>\n\n<p>Check this </p>\n" } ]
2016/08/26
[ "https://wordpress.stackexchange.com/questions/237195", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58895/" ]
bbPress has an annoying error about `bbp_setup_current_user was called incorrectly.` [bbPress topic](https://bbpress.org/forums/topic/bbp_setup_current_user-was-called-incorrectly/) and [bbPress ticket #2412](https://bbpress.trac.wordpress.org/ticket/2412), and it looks like nothing will change to fix it. On the site we used to use forum as a support platform, but has since then moved to a ticket system, so I've closed the forums, but you can look through them. I've also commented out the notice that was thrown in the backend because of it, but the problem is that the `error.log` on the server is filled with such errors (it's 85MB during the last 4 days). It's all like this: > > [Fri Aug 26 02:00:52.251831 2016] [:error] [pid 1832] [client xx.xx.xx.xx:32824] PHP Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'bbp\_setup\_current\_user' not found or invalid function name in /var/www/html/wp-includes/plugin.php on line 524 > > > So is there any kind of command I can use to suppress the writing of this specific warning in the error log? I'd still like to have possible errors written here.
"Technically" it's just a PHP warning and not an error, and you should not have warnings enabled on production servers. You can disable PHP from logging warnings and it will still log errors to the error log file. You can disable PHP warnings by setting it in a custom php.ini file on the server (all errors except for warnings): `error_reporting = E_ALL & ~E_WARNING` or try setting it with PHP: `error_reporting(E_ALL & ~E_WARNING);` From `php.ini` file: ``` ; Common Values: ; E_ALL (Show all errors, warnings and notices including coding standards.) ; E_ALL & ~E_NOTICE (Show all errors, except for notices) ; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.) ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors) ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED ; Development Value: E_ALL ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT ; http://php.net/error-reporting ```
237,211
<p>I seem to have a problem trying to display the "alternative text" of the featured image.</p> <p>Here is the code that I have been working on. Not sure why the alternative text is showing blank. </p> <pre><code> &lt;?php $projects = new WP_Query( array( 'post_type' =&gt; 'print-billboard' ) ); if ( $projects-&gt;have_posts() ) : while ( $projects-&gt;have_posts() ) : $projects-&gt;the_post(); ?&gt; &lt;?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large' ); $featured_image_url = wp_get_attachment_url( get_post_thumbnail_id() ); $alt = get_post_meta( $featured_image, '_wp_attachment_image_alt', true ); if ( has_post_thumbnail() ) : ?&gt; &lt;a href="&lt;?php echo $featured_image_url; ?&gt;" id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class( 'four columns project-post fancybox' ) ?&gt; &gt; &lt;?php $thumbnail_meta = get_post_meta( $featured_image, '_wp_attachment_image_alt', true ); ?&gt; &lt;figure class="full-width featured-image"&gt; &lt;img src="&lt;?php echo $featured_image[0]; ?&gt;" data-fancybox-group="gallery" title="Lorem ipsum dolor sit amet" alt="&lt;?php echo $featured_image; ?&gt;" /&gt; &lt;div class="overlay"&gt; &lt;/div&gt; &lt;/figure&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php endwhile; else: ?&gt; &lt;p class="error-message"&gt;No Projects&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; </code></pre>
[ { "answer_id": 237213, "author": "Rishabh", "author_id": 81621, "author_profile": "https://wordpress.stackexchange.com/users/81621", "pm_score": 0, "selected": false, "text": "<pre><code> if ( $projects-&gt;have_posts() ) : while ( $projects-&gt;have_posts() ) :\n $projects-&gt;the_post();\n\n/***** Thumbnail ******/\n the_post_thumbnail(\n array(120, 90), //Size of the thumbnail Image\n array(\n\n 'class' =&gt; 'class_name', //Specify class name to thumbnail image if any\n 'alt' =&gt; 'post thumbnail', // alternate text in case if no thumbnail image to show\n 'title' =&gt; 'Notice' //Specify title if want to\n )\n );\n/******* Thumbnail Ends ********/\n</code></pre>\n" }, { "answer_id": 237214, "author": "Belal Mostafa Amin", "author_id": 101694, "author_profile": "https://wordpress.stackexchange.com/users/101694", "pm_score": 1, "selected": false, "text": "<p>I am not so sure of what I am going to say, but from a fast look, $featured_image is an array <strong>(URL, width, height, is_intermediate)</strong>. so assuming that your alternative text exists in this array, you need to specify its index like this: \n<strong>$featured_image[index_of_alt_text]</strong>\naccording to my understanding, the $featured_image array doesn't contain your alternative text or you didn't specify the index. </p>\n\n<p>I hope it helped</p>\n" } ]
2016/08/26
[ "https://wordpress.stackexchange.com/questions/237211", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35356/" ]
I seem to have a problem trying to display the "alternative text" of the featured image. Here is the code that I have been working on. Not sure why the alternative text is showing blank. ``` <?php $projects = new WP_Query( array( 'post_type' => 'print-billboard' ) ); if ( $projects->have_posts() ) : while ( $projects->have_posts() ) : $projects->the_post(); ?> <?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large' ); $featured_image_url = wp_get_attachment_url( get_post_thumbnail_id() ); $alt = get_post_meta( $featured_image, '_wp_attachment_image_alt', true ); if ( has_post_thumbnail() ) : ?> <a href="<?php echo $featured_image_url; ?>" id="post-<?php the_ID(); ?>" <?php post_class( 'four columns project-post fancybox' ) ?> > <?php $thumbnail_meta = get_post_meta( $featured_image, '_wp_attachment_image_alt', true ); ?> <figure class="full-width featured-image"> <img src="<?php echo $featured_image[0]; ?>" data-fancybox-group="gallery" title="Lorem ipsum dolor sit amet" alt="<?php echo $featured_image; ?>" /> <div class="overlay"> </div> </figure> </a> <?php endif; ?> <?php wp_reset_postdata(); ?> <?php endwhile; else: ?> <p class="error-message">No Projects</p> <?php endif; ?> <?php wp_reset_query(); ?> ```
I am not so sure of what I am going to say, but from a fast look, $featured\_image is an array **(URL, width, height, is\_intermediate)**. so assuming that your alternative text exists in this array, you need to specify its index like this: **$featured\_image[index\_of\_alt\_text]** according to my understanding, the $featured\_image array doesn't contain your alternative text or you didn't specify the index. I hope it helped
237,212
<p><strong>What I am trying to do</strong></p> <p>I am adding a custom field to a WooCommerce email template, however I am trying to make the custom field only appear in one custom email template instead of all of them however i am struggling to achieve this. The template is called: <code>customer-completed-order.php</code></p> <p><strong>What I have so far</strong></p> <p>Using my child theme, i have copied the template from the original WooCommerce folder to <code>soulmedic-child/woocommerce/emails/customer-completed-order.php</code></p> <p>I have successfully made the custom field appear in all the original email templates using the following code in <code>functions.php</code>:</p> <pre><code>add_filter( 'woocommerce_email_order_meta_keys', 'my_custom_checkout_field_order_meta_keys'); function my_custom_checkout_field_order_meta_keys( $keys ) { $keys[] = 'Postage Tracking Number'; return $keys; } </code></pre> <p>I have checked through available hooks and have tried adding the following to the filter list, however, this did not worked: <code>woocommerce_email_heading_customer_completed_order</code></p> <p>I have searched through loads and loads of other posts however have not found anyone else who has managed to do this.</p> <p>I have attempted to add code directly to the email template however as i am already specifying the custom fields in <code>functions.php</code> it still adds the field to all email templates. I tried putting the code only in the email template however this broke the template.</p> <p>Could someone show me what I need to do to allow the information in the custom field to only appear on that specific template and no where else?</p>
[ { "answer_id": 237213, "author": "Rishabh", "author_id": 81621, "author_profile": "https://wordpress.stackexchange.com/users/81621", "pm_score": 0, "selected": false, "text": "<pre><code> if ( $projects-&gt;have_posts() ) : while ( $projects-&gt;have_posts() ) :\n $projects-&gt;the_post();\n\n/***** Thumbnail ******/\n the_post_thumbnail(\n array(120, 90), //Size of the thumbnail Image\n array(\n\n 'class' =&gt; 'class_name', //Specify class name to thumbnail image if any\n 'alt' =&gt; 'post thumbnail', // alternate text in case if no thumbnail image to show\n 'title' =&gt; 'Notice' //Specify title if want to\n )\n );\n/******* Thumbnail Ends ********/\n</code></pre>\n" }, { "answer_id": 237214, "author": "Belal Mostafa Amin", "author_id": 101694, "author_profile": "https://wordpress.stackexchange.com/users/101694", "pm_score": 1, "selected": false, "text": "<p>I am not so sure of what I am going to say, but from a fast look, $featured_image is an array <strong>(URL, width, height, is_intermediate)</strong>. so assuming that your alternative text exists in this array, you need to specify its index like this: \n<strong>$featured_image[index_of_alt_text]</strong>\naccording to my understanding, the $featured_image array doesn't contain your alternative text or you didn't specify the index. </p>\n\n<p>I hope it helped</p>\n" } ]
2016/08/26
[ "https://wordpress.stackexchange.com/questions/237212", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101645/" ]
**What I am trying to do** I am adding a custom field to a WooCommerce email template, however I am trying to make the custom field only appear in one custom email template instead of all of them however i am struggling to achieve this. The template is called: `customer-completed-order.php` **What I have so far** Using my child theme, i have copied the template from the original WooCommerce folder to `soulmedic-child/woocommerce/emails/customer-completed-order.php` I have successfully made the custom field appear in all the original email templates using the following code in `functions.php`: ``` add_filter( 'woocommerce_email_order_meta_keys', 'my_custom_checkout_field_order_meta_keys'); function my_custom_checkout_field_order_meta_keys( $keys ) { $keys[] = 'Postage Tracking Number'; return $keys; } ``` I have checked through available hooks and have tried adding the following to the filter list, however, this did not worked: `woocommerce_email_heading_customer_completed_order` I have searched through loads and loads of other posts however have not found anyone else who has managed to do this. I have attempted to add code directly to the email template however as i am already specifying the custom fields in `functions.php` it still adds the field to all email templates. I tried putting the code only in the email template however this broke the template. Could someone show me what I need to do to allow the information in the custom field to only appear on that specific template and no where else?
I am not so sure of what I am going to say, but from a fast look, $featured\_image is an array **(URL, width, height, is\_intermediate)**. so assuming that your alternative text exists in this array, you need to specify its index like this: **$featured\_image[index\_of\_alt\_text]** according to my understanding, the $featured\_image array doesn't contain your alternative text or you didn't specify the index. I hope it helped
237,253
<p>I'm working on a project on my desktop for a theme development, but an issue I am having is that when the user clicks on the navigation menu, it causes it to collapse. Since I got collapse to work on hover, I don't need it when clicked.</p> <p>I'm using the theme Unite. I don't have a way of sharing this project, and only have done surface customizations until the navigation bar. It's all the original PHP and JS. The CSS is original outside of color changes.</p> <p>If someone is able to assist me, I'd be most appreciative!</p>
[ { "answer_id": 237772, "author": "shamim khan", "author_id": 98304, "author_profile": "https://wordpress.stackexchange.com/users/98304", "pm_score": 1, "selected": true, "text": "<p>I think this will work for you\n<a href=\"http://jsfiddle.net/2Smgv/3100/\" rel=\"nofollow\">demo</a></p>\n\n<p>here is another js solution\n<a href=\"https://jsfiddle.net/PRkonsult/mn31qf0p/1/\" rel=\"nofollow\">demo2</a></p>\n\n<pre>\n$('ul.nav li.dropdown').hover(function() {\n $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);\n}, function() {\n $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);\n});\n</pre>\n" }, { "answer_id": 311948, "author": "sandeep jha", "author_id": 149062, "author_profile": "https://wordpress.stackexchange.com/users/149062", "pm_score": 1, "selected": false, "text": "<p>In the Menus page, click on the Custom Links section on the left.\nThe Custom Links option lets you link to any URL you want, but we’ve got a special trick instead.\nIn the URL input, replace “http://” with a pound sign “#,” and enter whatever text you want for the Link Text.\nClick the Add to Menu button, and then you can arrange the new item in your menu. Since the menu item isn’t linked anywhere, visitors won’t be taken to a new page if they click it.</p>\n" }, { "answer_id": 405060, "author": "estinamir", "author_id": 221518, "author_profile": "https://wordpress.stackexchange.com/users/221518", "pm_score": 0, "selected": false, "text": "<p>This approach uses global variable to return false for link click in desktop but true on mobile and tablet. Also works for resized windows.</p>\n<pre><code>$(document).ready(function () {\n win_width = $(window).width();\n $('.yamm-fw &gt; a').click(function(e){\n return win_width &lt; 1200;\n });\n});\n\n$(window).on('resize', function () {\n win_width = $(window).width();\n});\n</code></pre>\n" } ]
2016/08/26
[ "https://wordpress.stackexchange.com/questions/237253", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98508/" ]
I'm working on a project on my desktop for a theme development, but an issue I am having is that when the user clicks on the navigation menu, it causes it to collapse. Since I got collapse to work on hover, I don't need it when clicked. I'm using the theme Unite. I don't have a way of sharing this project, and only have done surface customizations until the navigation bar. It's all the original PHP and JS. The CSS is original outside of color changes. If someone is able to assist me, I'd be most appreciative!
I think this will work for you [demo](http://jsfiddle.net/2Smgv/3100/) here is another js solution [demo2](https://jsfiddle.net/PRkonsult/mn31qf0p/1/) ``` $('ul.nav li.dropdown').hover(function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500); }, function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500); }); ```
237,262
<p>I know how to display my field groups on specific pages (display location: page is equal to myPage). </p> <p>I have a few different templates on my site and would like to display Field Group X when the page is using template Y. Is this possible?</p>
[ { "answer_id": 237264, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 3, "selected": true, "text": "<p>Hard to give an exact answer without sharing your code, but using <a href=\"https://developer.wordpress.org/reference/functions/is_page_template/\" rel=\"nofollow\"><code>is_page_template()</code></a> in an <code>if</code> statement will help determine when you display your custom field group:</p>\n\n<pre><code>if ( is_page_template( 'template-y.php' ) ) {\n # Display Field Group X code here...\n}\nelse {\n # Do something else...\n}\n</code></pre>\n\n<p>Again, if you could provide your code, I can give you a better answer.</p>\n" }, { "answer_id": 237271, "author": "depiction", "author_id": 101731, "author_profile": "https://wordpress.stackexchange.com/users/101731", "pm_score": 1, "selected": false, "text": "<p>You say you already know how to add fields. Once you add the metabox containing these fields add the following code. This will toggle the display of the metabox when the page template is changed. You'll need to change the metabox id and the file name of the page template that when selected, should show the metabox. Inspect the page to find the metabox id.</p>\n\n<p>So if the metabox has an id of \"metabox_id\" and you want it to appear when the selected page template's file name is \"template-file-name.php\", use the following.</p>\n\n<p>In functions.php</p>\n\n<pre><code>add_action('admin_enqueue_scripts', 'my_admin_script');\n\nfunction my_admin_script() {\n wp_enqueue_script('my-admin', get_bloginfo('stylesheet_directory').'/js/custom-admin.js', array('jquery'), '1.0.0', true);\n}\n</code></pre>\n\n<p>In custom-admin.js</p>\n\n<pre><code>(function($){\n $(document).ready(function() {\n\n $('#page_template').change(function() {\n $('#metabox_id').toggle($(this).val() == 'template-file-name.php'); //Change\n }).change();\n\n });\n})(jQuery);\n</code></pre>\n" } ]
2016/08/26
[ "https://wordpress.stackexchange.com/questions/237262", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101727/" ]
I know how to display my field groups on specific pages (display location: page is equal to myPage). I have a few different templates on my site and would like to display Field Group X when the page is using template Y. Is this possible?
Hard to give an exact answer without sharing your code, but using [`is_page_template()`](https://developer.wordpress.org/reference/functions/is_page_template/) in an `if` statement will help determine when you display your custom field group: ``` if ( is_page_template( 'template-y.php' ) ) { # Display Field Group X code here... } else { # Do something else... } ``` Again, if you could provide your code, I can give you a better answer.
237,266
<p>I want add a new settings box on the <em>Post</em> page. I'd like to be under the category or above, like so:</p> <p><a href="https://i.stack.imgur.com/ipng6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ipng6.png" alt="enter image description here"></a></p>
[ { "answer_id": 237268, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 2, "selected": false, "text": "<p>You need to use the <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow\"><code>add_meta_box</code></a> function</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'my_custom_meta_box' ) );\nfunction my_custom_meta_box(){\n\n $args = array();\n\n add_meta_box(\n 'my_metabox_id',\n __( 'My Meta Box', 'my_textdomain' ), // Title\n 'my_callback_function', // Callback function that renders the content of the meta box\n 'post', // Admin page (or post type) to show the meta box on\n 'side', // Context where the box is shown on the page\n 'high', // Priority within that context\n $args // Arguments to pass the callback function, if any\n );\n}\n\n\nfunction my_callback_function( $args ){\n\n //The markup for your meta box goes here\n\n}\n</code></pre>\n" }, { "answer_id": 237300, "author": "Bhagchandani", "author_id": 101627, "author_profile": "https://wordpress.stackexchange.com/users/101627", "pm_score": 0, "selected": false, "text": "<p>Put below code in you <code>function.php</code> file. The below code will create text box in post type \"post\". Only defining text field will not work you need to make it save too when post is saved. check below url for saving value of meta box.</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'cd_meta_box_add' );\nfunction cd_meta_box_add(){\n add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );}\n\nfunction cd_meta_box_cb(){ \n &lt;label for=\"my_meta_box_text\"&gt;Text Label&lt;/label&gt;\n &lt;input type=\"text\" name=\"my_meta_box_text\" id=\"my_meta_box_text\" /&gt;\n}\n</code></pre>\n\n<p>For more details visit <a href=\"http://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336\" rel=\"nofollow\">http://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336</a></p>\n" } ]
2016/08/26
[ "https://wordpress.stackexchange.com/questions/237266", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101728/" ]
I want add a new settings box on the *Post* page. I'd like to be under the category or above, like so: [![enter image description here](https://i.stack.imgur.com/ipng6.png)](https://i.stack.imgur.com/ipng6.png)
You need to use the [`add_meta_box`](https://developer.wordpress.org/reference/functions/add_meta_box/) function ``` add_action( 'add_meta_boxes', 'my_custom_meta_box' ) ); function my_custom_meta_box(){ $args = array(); add_meta_box( 'my_metabox_id', __( 'My Meta Box', 'my_textdomain' ), // Title 'my_callback_function', // Callback function that renders the content of the meta box 'post', // Admin page (or post type) to show the meta box on 'side', // Context where the box is shown on the page 'high', // Priority within that context $args // Arguments to pass the callback function, if any ); } function my_callback_function( $args ){ //The markup for your meta box goes here } ```
237,270
<p>I have a taxonomy "artist" for two different custom post types ("project" and "product").</p> <p>I need to display a list of "artists", but only if they have related "products", and only if those products are still in stock.</p> <pre><code>$artists = get_terms( array( 'taxonomy' =&gt; 'artist', 'hide_empty' =&gt; 1, ) ); </code></pre> <p>This includes artists having "projects" but no "products". Is it possible to specify for which post type the "hide_empty" argument should refer to ?</p> <p><em>EDIT</em> Here is what I have so far. </p> <pre><code> /* Useful when one taxonomy applies to multiple post types source: http://wordpress.stackexchange.com/a/24074/82 */ function get_terms_by_post_type( $taxonomies, $post_types ) { global $wpdb; $query = $wpdb-&gt;prepare( "SELECT t.*, COUNT(*) from $wpdb-&gt;terms AS t INNER JOIN $wpdb-&gt;term_taxonomy AS tt ON t.term_id = tt.term_id INNER JOIN $wpdb-&gt;term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN $wpdb-&gt;posts AS p ON p.ID = r.object_id WHERE p.post_type IN('%s') AND tt.taxonomy IN('%s') GROUP BY t.term_id", join( "', '", $post_types ), join( "', '", $taxonomies ) ); $results = $wpdb-&gt;get_results( $query ); return $results; } $artists = get_terms_by_post_type( array('artist'), array('product')); //* if( !empty($artists) &amp;&amp; !is_wp_error( $artists ) ){ // filter out out-of-stock products artists foreach($artists as $k=&gt;$artist){ $args = array( 'post_type' =&gt; 'product', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'artist', 'field' =&gt; 'id', 'terms' =&gt; array( $artist-&gt;term_id ) ), array( 'key' =&gt; '_stock_status', 'value' =&gt; 'instock' ) ) ); $query = new WP_Query($args); echo $artist-&gt;slug; pr($query-&gt;post_count); if($query-&gt;post_count&lt;1){ unset($artists[$k]); } } } </code></pre> <p>It almost works, but it does not remove products out of stock.</p>
[ { "answer_id": 237268, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 2, "selected": false, "text": "<p>You need to use the <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow\"><code>add_meta_box</code></a> function</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'my_custom_meta_box' ) );\nfunction my_custom_meta_box(){\n\n $args = array();\n\n add_meta_box(\n 'my_metabox_id',\n __( 'My Meta Box', 'my_textdomain' ), // Title\n 'my_callback_function', // Callback function that renders the content of the meta box\n 'post', // Admin page (or post type) to show the meta box on\n 'side', // Context where the box is shown on the page\n 'high', // Priority within that context\n $args // Arguments to pass the callback function, if any\n );\n}\n\n\nfunction my_callback_function( $args ){\n\n //The markup for your meta box goes here\n\n}\n</code></pre>\n" }, { "answer_id": 237300, "author": "Bhagchandani", "author_id": 101627, "author_profile": "https://wordpress.stackexchange.com/users/101627", "pm_score": 0, "selected": false, "text": "<p>Put below code in you <code>function.php</code> file. The below code will create text box in post type \"post\". Only defining text field will not work you need to make it save too when post is saved. check below url for saving value of meta box.</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'cd_meta_box_add' );\nfunction cd_meta_box_add(){\n add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );}\n\nfunction cd_meta_box_cb(){ \n &lt;label for=\"my_meta_box_text\"&gt;Text Label&lt;/label&gt;\n &lt;input type=\"text\" name=\"my_meta_box_text\" id=\"my_meta_box_text\" /&gt;\n}\n</code></pre>\n\n<p>For more details visit <a href=\"http://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336\" rel=\"nofollow\">http://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336</a></p>\n" } ]
2016/08/26
[ "https://wordpress.stackexchange.com/questions/237270", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82/" ]
I have a taxonomy "artist" for two different custom post types ("project" and "product"). I need to display a list of "artists", but only if they have related "products", and only if those products are still in stock. ``` $artists = get_terms( array( 'taxonomy' => 'artist', 'hide_empty' => 1, ) ); ``` This includes artists having "projects" but no "products". Is it possible to specify for which post type the "hide\_empty" argument should refer to ? *EDIT* Here is what I have so far. ``` /* Useful when one taxonomy applies to multiple post types source: http://wordpress.stackexchange.com/a/24074/82 */ function get_terms_by_post_type( $taxonomies, $post_types ) { global $wpdb; $query = $wpdb->prepare( "SELECT t.*, COUNT(*) from $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id WHERE p.post_type IN('%s') AND tt.taxonomy IN('%s') GROUP BY t.term_id", join( "', '", $post_types ), join( "', '", $taxonomies ) ); $results = $wpdb->get_results( $query ); return $results; } $artists = get_terms_by_post_type( array('artist'), array('product')); //* if( !empty($artists) && !is_wp_error( $artists ) ){ // filter out out-of-stock products artists foreach($artists as $k=>$artist){ $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'artist', 'field' => 'id', 'terms' => array( $artist->term_id ) ), array( 'key' => '_stock_status', 'value' => 'instock' ) ) ); $query = new WP_Query($args); echo $artist->slug; pr($query->post_count); if($query->post_count<1){ unset($artists[$k]); } } } ``` It almost works, but it does not remove products out of stock.
You need to use the [`add_meta_box`](https://developer.wordpress.org/reference/functions/add_meta_box/) function ``` add_action( 'add_meta_boxes', 'my_custom_meta_box' ) ); function my_custom_meta_box(){ $args = array(); add_meta_box( 'my_metabox_id', __( 'My Meta Box', 'my_textdomain' ), // Title 'my_callback_function', // Callback function that renders the content of the meta box 'post', // Admin page (or post type) to show the meta box on 'side', // Context where the box is shown on the page 'high', // Priority within that context $args // Arguments to pass the callback function, if any ); } function my_callback_function( $args ){ //The markup for your meta box goes here } ```
237,299
<p>I'm working in a blog with a template of my own. When I link to a category page (i.e. <code>mydomain.com/category/mycategory</code>) Wordpress generates this HTML code just after the <code>header.php</code>:</p> <pre><code>&lt;!-- HTML rendered by header.php --&gt; &lt;!-- This 2 lines belong to index.php --&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; &lt;!-- HTML rendered by content.php --&gt; &lt;header class="page-header"&gt; &lt;h1 class="page-title"&gt;Category: My Category&lt;/h1&gt; &lt;/header&gt; &lt;!-- .page-header --&gt; &lt;!-- this comment is also generated by content.php --&gt; &lt;div id="post-292" class="grid-item"&gt; &lt;!-- The rest of content.php --&gt; &lt;/div&gt; </code></pre> <p>My <code>content.php</code> file is as follows:</p> <pre><code>&lt;?php /** * The template part for displaying content * * @package WordPress * @subpackage Twenty_Sixteen * @since Twenty Sixteen 1.0 */ ?&gt; &lt;div id="post-&lt;?php the_ID(); ?&gt;" class="grid-item"&gt; ... </code></pre> <p>So the question is: where is the <code>&lt;header&gt;</code> tag generated and how can I customize it? I want to change the <code>&lt;h1&gt;</code> rendered content <em>Category: My Category</em> to be just <em>My Category</em>, for example.</p> <p>Any help or guide is appreciated. Thanks in advance for your answers. </p>
[ { "answer_id": 237314, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 1, "selected": false, "text": "<ol>\n<li>Create another file form <code>header.php</code> and name it like <code>header-{category-name}.php</code>.</li>\n<li>Do your needed change on <code>header-{category-name}.php</code>.</li>\n<li>Then in your <code>category.php</code> call this file by <code>get_header( 'category-name' )</code>.</li>\n<li>If you don't have <code>category.php</code> file then create one by copying the <code>archive.php</code> template then follow the above instruction.</li>\n</ol>\n\n<p>Follow those above steps and you'll get your desired result.</p>\n" }, { "answer_id": 237357, "author": "Greg McMullen", "author_id": 36028, "author_profile": "https://wordpress.stackexchange.com/users/36028", "pm_score": 3, "selected": true, "text": "<p>Review the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#category\" rel=\"nofollow\">template hierarchy</a> from the Codex to gain a better understanding of what files are read when. This will help you to understand what's called in what situation (tag/category/front-page/etc). </p>\n\n<p>Content.php is never mentioned in the documentation as its not a part of the template hierarchy. Theme developers will use different file names and will reference them within the loop. </p>\n\n<p>Most of the themes by Automattic use this technique to call the various parts to build out the content. Review your <code>index.php</code>, <code>page.php</code>, or <code>post.php</code> to see if <code>content.php</code> is used there. </p>\n" } ]
2016/08/27
[ "https://wordpress.stackexchange.com/questions/237299", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100952/" ]
I'm working in a blog with a template of my own. When I link to a category page (i.e. `mydomain.com/category/mycategory`) Wordpress generates this HTML code just after the `header.php`: ``` <!-- HTML rendered by header.php --> <!-- This 2 lines belong to index.php --> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <!-- HTML rendered by content.php --> <header class="page-header"> <h1 class="page-title">Category: My Category</h1> </header> <!-- .page-header --> <!-- this comment is also generated by content.php --> <div id="post-292" class="grid-item"> <!-- The rest of content.php --> </div> ``` My `content.php` file is as follows: ``` <?php /** * The template part for displaying content * * @package WordPress * @subpackage Twenty_Sixteen * @since Twenty Sixteen 1.0 */ ?> <div id="post-<?php the_ID(); ?>" class="grid-item"> ... ``` So the question is: where is the `<header>` tag generated and how can I customize it? I want to change the `<h1>` rendered content *Category: My Category* to be just *My Category*, for example. Any help or guide is appreciated. Thanks in advance for your answers.
Review the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#category) from the Codex to gain a better understanding of what files are read when. This will help you to understand what's called in what situation (tag/category/front-page/etc). Content.php is never mentioned in the documentation as its not a part of the template hierarchy. Theme developers will use different file names and will reference them within the loop. Most of the themes by Automattic use this technique to call the various parts to build out the content. Review your `index.php`, `page.php`, or `post.php` to see if `content.php` is used there.
237,301
<p>I'm trying to count the total number of paragraphs within each blog post but it is not getting executed and hence returning nothing. </p> <p><strong>How do you want to use this code?</strong></p> <p>Currently in my <code>function.php</code> I have the following code that I use to show up ads inside my post:</p> <pre><code>add_filter( 'the_content', '_some_func' ); function _some_func( $content ) { $ad_code = "the ad code"; if ( is_singular( 'post' ) ) { return prefix_insert_after_paragraph( $ad_code, 12, $content ); } return $content; } // Parent Function that makes the magic happen function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $closing_p = '&lt;/p&gt;'; $paragraphs = explode( $closing_p, $content ); foreach ($paragraphs as $index =&gt; $paragraph) { if ( trim( $paragraph ) ) { $paragraphs[$index] .= $closing_p; } if ( $paragraph_id == $index + 1 ) { $paragraphs[$index] .= $insertion; } } return implode( '', $paragraphs ); } </code></pre> <p>Now I want to take it to next level by servicing code based on now many paragraphs are there, like this:</p> <pre><code>add_filter( 'the_content', '_some_func' ); function _some_func( $content ) { if( __check_paragraph_count_blog() &gt; 15 ) $ad_code = "the ad code"; if ( is_singular( 'post' ) ) { return prefix_insert_after_paragraph( $ad_code, 12, $content ); } return $content; } </code></pre> <p>So, I tried to write the following <code>__check_paragraph_count_blog()</code> function to get the total paragraph count so that I can use it in the above call.</p> <pre><code>function __check_paragraph_count_blog() { global $post; if ( is_singular( 'post' ) ) { $count = substr_count( $post-&gt;post_content, '&lt;/p&gt;' ); return $count; } else { return 0; } } </code></pre> <p>There are 2 problem with my <code>__check_paragraph_count_blog()</code> function:</p> <ul> <li>It is always returning 0</li> <li>It considers the <code>&lt;/p&gt;</code> tags inside <code>&lt;code&gt;</code> and <code>&lt;pre&gt;</code> tags too.</li> </ul> <p>So, if anyone can help me fix my <code>__check_paragraph_count_blog()</code> function so that it work properly it will be a really big help.</p>
[ { "answer_id": 237310, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>If you just dump a <a href=\"http://php.net/manual/en/language.oop5.magic.php\" rel=\"nofollow\">magic function</a> in <code>functions.php</code> it will be evaluated immediately when the theme is inititiated (someone better in PHP and OOP should be able to explain how this happens, but I assume you are defining a class).</p>\n\n<p>This evalution is long before WP determines which post to show. So there is no post, there are no paragraphs and the count is zero.</p>\n\n<p>How to fix this depends on what you want to do. Currently you are just writing to the browser console, so <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">any hook</a> after the post has been loaded would be fine. Like this:</p>\n\n<pre><code>add_action ('wp', 'wpse237301_check_paragraph_count_blog');\n</code></pre>\n" }, { "answer_id": 237316, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 3, "selected": true, "text": "<p>I'm pretty sure that <code>is_singular()</code> is going to return false when you are inside the WP loop, since there are more than one posts being looped through. Try <code>is_single()</code> or just look at the post object and examine the <code>post_type</code> attribute.</p>\n\n<pre><code>add_filter( 'the_content', '_some_func', 15 );\n\nfunction _some_func( $content ) {\n\n if( __check_paragraph_count_blog( $content ) &gt; 15 )\n $ad_code = \"the ad code\";\n else\n $ad_code = '';\n\n return prefix_insert_after_paragraph( $ad_code, 12, $content );\n\n}\n\n\nfunction __check_paragraph_count_blog( $content ) {\n global $post;\n if ( $post-&gt;post_type == 'post' ) {\n $count = substr_count( $content, '&lt;/p&gt;' );\n return $count;\n } else {\n return 0;\n }\n}\n</code></pre>\n" }, { "answer_id": 237318, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>You first need to define what is a paragraph, is it a paragraph as being seen in the editor, or the one being seen on the html page. The distinction is critical as there is a difference of how wordpress stores the content in the DB and how it is \"sent\" to the html (and obviously a difference in taking into account shortcodes, oembeds and other manipulations.</p>\n\n<p>In the DB itself, wordpress <strong>do not</strong> store the content as true HTML. Paragraphs are being separated by a new line character and not by a P tag. A filter running <a href=\"https://codex.wordpress.org/FunctionReference/wpautop\" rel=\"nofollow\">wpautop</a> is responsible to do the conversion from a new line to the P element. If you want to be sure that you are working with the HTML version of the content you should use a priority of 11 or higher for your hook.</p>\n\n<p>The other thing that is problematic with your code is that filters/actions should not be added before the <code>wp_loaded</code> hook, there are some exceptions for specific cases but even then you should not add filters in some random places in your code.</p>\n\n<p>Last and not least, if you want to properly parse html, you should use an html parser and not string comparison and neither regexp. You might find it easier to actually use JS on client side then trying to handle badly formatted HTML on server side.</p>\n" } ]
2016/08/27
[ "https://wordpress.stackexchange.com/questions/237301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50584/" ]
I'm trying to count the total number of paragraphs within each blog post but it is not getting executed and hence returning nothing. **How do you want to use this code?** Currently in my `function.php` I have the following code that I use to show up ads inside my post: ``` add_filter( 'the_content', '_some_func' ); function _some_func( $content ) { $ad_code = "the ad code"; if ( is_singular( 'post' ) ) { return prefix_insert_after_paragraph( $ad_code, 12, $content ); } return $content; } // Parent Function that makes the magic happen function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $closing_p = '</p>'; $paragraphs = explode( $closing_p, $content ); foreach ($paragraphs as $index => $paragraph) { if ( trim( $paragraph ) ) { $paragraphs[$index] .= $closing_p; } if ( $paragraph_id == $index + 1 ) { $paragraphs[$index] .= $insertion; } } return implode( '', $paragraphs ); } ``` Now I want to take it to next level by servicing code based on now many paragraphs are there, like this: ``` add_filter( 'the_content', '_some_func' ); function _some_func( $content ) { if( __check_paragraph_count_blog() > 15 ) $ad_code = "the ad code"; if ( is_singular( 'post' ) ) { return prefix_insert_after_paragraph( $ad_code, 12, $content ); } return $content; } ``` So, I tried to write the following `__check_paragraph_count_blog()` function to get the total paragraph count so that I can use it in the above call. ``` function __check_paragraph_count_blog() { global $post; if ( is_singular( 'post' ) ) { $count = substr_count( $post->post_content, '</p>' ); return $count; } else { return 0; } } ``` There are 2 problem with my `__check_paragraph_count_blog()` function: * It is always returning 0 * It considers the `</p>` tags inside `<code>` and `<pre>` tags too. So, if anyone can help me fix my `__check_paragraph_count_blog()` function so that it work properly it will be a really big help.
I'm pretty sure that `is_singular()` is going to return false when you are inside the WP loop, since there are more than one posts being looped through. Try `is_single()` or just look at the post object and examine the `post_type` attribute. ``` add_filter( 'the_content', '_some_func', 15 ); function _some_func( $content ) { if( __check_paragraph_count_blog( $content ) > 15 ) $ad_code = "the ad code"; else $ad_code = ''; return prefix_insert_after_paragraph( $ad_code, 12, $content ); } function __check_paragraph_count_blog( $content ) { global $post; if ( $post->post_type == 'post' ) { $count = substr_count( $content, '</p>' ); return $count; } else { return 0; } } ```