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
|
---|---|---|---|---|---|---|
282,919 | <p>I currently use the form below :</p>
<pre><code><form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Type Business or Town', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
<input type="text" value="<?php echo get_query_var('location'); ?>" name="location" id="location" class="headersearch location" placeholder="<?php esc_attr_e( 'Enter your county..', 'search-cust' ); ?>" />
<input type="hidden" name="post_type" value="business" />
<input type="submit" class="button radius tiny success" style="width: 100%;" value="<?php esc_attr_e( 'Search...', 'search-cust' ); ?>" />
</form>
</code></pre>
<p>I also have this in functions.php : </p>
<pre><code> function custom_cpt_search( $query ) {
if ( is_search() && $query->is_main_query() && $query->get( 's' ) ){
$query->set('post_type', array('business'));
}
return $query;
};
add_filter('pre_get_posts', 'custom_cpt_search');
</code></pre>
<p>Ideally id like to have the second input as a drop-down taxonomy list instead of a type-in input, Ideally listing ALL categories in the taxonomy instead of only categories with posts in them. With the first dropdown item being a placeholder such as "Select your county". </p>
<p>Edited to make clearer, and remove part of the question I have resolved. </p>
| [
{
"answer_id": 283168,
"author": "Misha Rudrastyh",
"author_id": 85985,
"author_profile": "https://wordpress.stackexchange.com/users/85985",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can do it in two following steps:</p>\n\n<ol>\n<li><p>In HTML code just add a dropdown with the values you need.</p>\n\n<pre><code><select name=\"yourselect\"><option value=\"1\">Value 1</option>\n\n...\n\n</select>\n</code></pre></li>\n<li><p>In your <code>pre_get_posts</code> filter add <code>tax_query</code> parameter like this</p>\n\n<pre><code>if( !empty( $_GET['yourselect'] ) ) {\n $query->set('tax_query', array(\n array(\n 'taxonomy' => 'YOUR_TAXONOMY_NAME',\n 'field' => 'id', // or slug if you want\n 'terms' => $_POST['yourselect']\n )\n );\n}\n</code></pre></li>\n</ol>\n\n<p>I'm not sure if it is a good idea to configure this way the <em>default</em> WordPress search. A couple months ago I already implemented similar functionality using AJAX filters. Example is here, hope it helps <a href=\"https://rudrastyh.com/wordpress/ajax-post-filters.html\" rel=\"noreferrer\">https://rudrastyh.com/wordpress/ajax-post-filters.html</a></p>\n"
},
{
"answer_id": 283186,
"author": "Randomer11",
"author_id": 62291,
"author_profile": "https://wordpress.stackexchange.com/users/62291",
"pm_score": 3,
"selected": true,
"text": "<p>After Misha answered above, a lightbulb came on which lead me to understand something a little more, this is the form which is now working as expected using wp_dropdown_categories and some args. </p>\n\n<p>I had previously done it this way, but it seems the main problem previously was that it was searching for the ID in the URL instead of the slug, for some reason the id doesnt find the posts, but using the slug did ( if someone can tell me why that would be great for my learning )</p>\n\n<p>This is the working form, to note ( location ) is my custom taxonomy so anyone using this will need to change it to match their taxonomy.</p>\n\n<pre><code><form role=\"search\" method=\"get\" class=\"search-form\" action=\"<?php echo home_url( '/' ); ?>\">\n\n <input type=\"search\" class=\"search-field\" placeholder=\"<?php echo esc_attr_x( 'Search Business or Service', 'placeholder' ) ?>\" value=\"<?php echo get_query_var('business'); ?>\" name=\"s\" title=\"<?php echo esc_attr_x( 'Search for:', 'label' ) ?>\" />\n\n <?php $location_args = array('taxonomy' => 'location', 'value_field' => 'slug', 'name' => 'location', 'show_option_none' => __( 'Select County' ),'option_none_value' => '0', 'order' => 'ASC', 'hide_empty' => 0); ?> \n <?php wp_dropdown_categories($location_args); ?>\n\n <input type=\"hidden\" name=\"post_type\" value=\"business\" />\n <input type=\"submit\" class=\"button\" style=\"width: 100%;\" value=\"<?php esc_attr_e( 'Search...', 'custom' ); ?>\" />\n\n</form>\n</code></pre>\n"
}
]
| 2017/10/14 | [
"https://wordpress.stackexchange.com/questions/282919",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62291/"
]
| I currently use the form below :
```
<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Type Business or Town', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
<input type="text" value="<?php echo get_query_var('location'); ?>" name="location" id="location" class="headersearch location" placeholder="<?php esc_attr_e( 'Enter your county..', 'search-cust' ); ?>" />
<input type="hidden" name="post_type" value="business" />
<input type="submit" class="button radius tiny success" style="width: 100%;" value="<?php esc_attr_e( 'Search...', 'search-cust' ); ?>" />
</form>
```
I also have this in functions.php :
```
function custom_cpt_search( $query ) {
if ( is_search() && $query->is_main_query() && $query->get( 's' ) ){
$query->set('post_type', array('business'));
}
return $query;
};
add_filter('pre_get_posts', 'custom_cpt_search');
```
Ideally id like to have the second input as a drop-down taxonomy list instead of a type-in input, Ideally listing ALL categories in the taxonomy instead of only categories with posts in them. With the first dropdown item being a placeholder such as "Select your county".
Edited to make clearer, and remove part of the question I have resolved. | After Misha answered above, a lightbulb came on which lead me to understand something a little more, this is the form which is now working as expected using wp\_dropdown\_categories and some args.
I had previously done it this way, but it seems the main problem previously was that it was searching for the ID in the URL instead of the slug, for some reason the id doesnt find the posts, but using the slug did ( if someone can tell me why that would be great for my learning )
This is the working form, to note ( location ) is my custom taxonomy so anyone using this will need to change it to match their taxonomy.
```
<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search Business or Service', 'placeholder' ) ?>" value="<?php echo get_query_var('business'); ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
<?php $location_args = array('taxonomy' => 'location', 'value_field' => 'slug', 'name' => 'location', 'show_option_none' => __( 'Select County' ),'option_none_value' => '0', 'order' => 'ASC', 'hide_empty' => 0); ?>
<?php wp_dropdown_categories($location_args); ?>
<input type="hidden" name="post_type" value="business" />
<input type="submit" class="button" style="width: 100%;" value="<?php esc_attr_e( 'Search...', 'custom' ); ?>" />
</form>
``` |
282,920 | <p>How I can remove all internal or external links on my posts at once? just remove link and leave anchor text.</p>
| [
{
"answer_id": 282923,
"author": "Dejan Gavrilovic",
"author_id": 129636,
"author_profile": "https://wordpress.stackexchange.com/users/129636",
"pm_score": 0,
"selected": false,
"text": "<p>Target your links with some CSS. In default twentyseventeen theme it's</p>\n\n<pre><code>.entry-content a {\n pointer-events: none;\n cursor: default;\n}\n</code></pre>\n"
},
{
"answer_id": 282934,
"author": "Misha Rudrastyh",
"author_id": 85985,
"author_profile": "https://wordpress.stackexchange.com/users/85985",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure about the database but you can do it easily with <code>the_content</code> filter, just add the code below to your current (child) theme <code>functions.php</code> file:</p>\n\n<pre><code>add_filter( 'the_content', 'misha_remove_all_a' );\nfunction misha_remove_all_a( $content ){\n\n return preg_replace('#<a.*?>(.*?)</a>#is', '\\1', $content);\n\n}\n</code></pre>\n"
},
{
"answer_id": 346013,
"author": "user168547",
"author_id": 168547,
"author_profile": "https://wordpress.stackexchange.com/users/168547",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_filter('the_content', 'removelink_content',1);\n\nfunction removelink_content($content = '')\n{\n preg_match_all(\"#<a(.*?)>(.*?)</a>#i\",$content, $matches);\n $num = count($matches[0]);for($i = 0;$i < $num;$i++){\n $content = str_replace($matches[0][$i] , $matches[2][$i] , $content);\n }\n return $content;\n}\n</code></pre>\n"
}
]
| 2017/10/14 | [
"https://wordpress.stackexchange.com/questions/282920",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83204/"
]
| How I can remove all internal or external links on my posts at once? just remove link and leave anchor text. | Not sure about the database but you can do it easily with `the_content` filter, just add the code below to your current (child) theme `functions.php` file:
```
add_filter( 'the_content', 'misha_remove_all_a' );
function misha_remove_all_a( $content ){
return preg_replace('#<a.*?>(.*?)</a>#is', '\1', $content);
}
``` |
282,929 | <p>I want to add Google Analytics code snippet between the <code><head></code> and <code></head></code> tags of some relevant pages of my WordPress website. Adding the code snippet to the header.php file will affect all the pages of the website what I do not want. How should I proceed?</p>
| [
{
"answer_id": 282930,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": false,
"text": "<p>The header.php is the right place, but you'll need one more thing: a condition. This way you can decide on which pages to place the code and on which not to. You can check that via <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\"><code>is_page()</code></a></p>\n\n<pre><code><?php\n$relevant_pages = array('slug1', 'slug2');\nif (is_page($relevant_pages)) {\n ?>\n GA snippet\n <?php\n}\n?>\n</head>\n</code></pre>\n"
},
{
"answer_id": 282935,
"author": "ssnepenthe",
"author_id": 125601,
"author_profile": "https://wordpress.stackexchange.com/users/125601",
"pm_score": 4,
"selected": true,
"text": "<p>While you can add the snippet directly to <code>header.php</code>, a better choice is probably the <code>wp_head</code> action which should be triggered in any well-made, modern theme.</p>\n\n<p>Using this hook allows you to insert the snippet without actually modifying your theme. It might look something like this:</p>\n\n<pre><code>function wpse_282929_conditionally_print_ga_snippet() {\n if ( ! some_conditional_tag() ) {\n return;\n }\n\n ?>\n\n {GA Snippet Here}\n\n <?php\n}\nadd_action( 'wp_head', 'wpse_282929_conditionally_print_ga_snippet' );\n</code></pre>\n\n<p>Where <code>! some_conditional_tag()</code> gets replaced by the appropriate conditional that would indicate you DO NOT WANT to print the snippet, and <code>{GA Snippet Here}</code> obviously gets replaced with your specific GA snippet.</p>\n\n<p>WordPress provides a number of conditional tags to determine what kind of page your visitor is currently on.</p>\n\n<p>In fact, there are too many to list here, but you can find a complete listing on the <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\">Conditional Tags page in the codex</a>.</p>\n\n<p>As for where to include this code - if you are already working within a custom theme, you can just add it to your <code>functions.php</code> file.</p>\n\n<p>If not, I would probably recommend creating a must-use plugin. To do so, first create the <code>mu-plugins</code> directory within <code>wp-content</code> if it does not already exist. Next, create a file called <code>ga-snippet.php</code> within the <code>mu-plugins</code> directory and include your GA snippet function there.</p>\n"
}
]
| 2017/10/14 | [
"https://wordpress.stackexchange.com/questions/282929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129204/"
]
| I want to add Google Analytics code snippet between the `<head>` and `</head>` tags of some relevant pages of my WordPress website. Adding the code snippet to the header.php file will affect all the pages of the website what I do not want. How should I proceed? | While you can add the snippet directly to `header.php`, a better choice is probably the `wp_head` action which should be triggered in any well-made, modern theme.
Using this hook allows you to insert the snippet without actually modifying your theme. It might look something like this:
```
function wpse_282929_conditionally_print_ga_snippet() {
if ( ! some_conditional_tag() ) {
return;
}
?>
{GA Snippet Here}
<?php
}
add_action( 'wp_head', 'wpse_282929_conditionally_print_ga_snippet' );
```
Where `! some_conditional_tag()` gets replaced by the appropriate conditional that would indicate you DO NOT WANT to print the snippet, and `{GA Snippet Here}` obviously gets replaced with your specific GA snippet.
WordPress provides a number of conditional tags to determine what kind of page your visitor is currently on.
In fact, there are too many to list here, but you can find a complete listing on the [Conditional Tags page in the codex](https://codex.wordpress.org/Conditional_Tags).
As for where to include this code - if you are already working within a custom theme, you can just add it to your `functions.php` file.
If not, I would probably recommend creating a must-use plugin. To do so, first create the `mu-plugins` directory within `wp-content` if it does not already exist. Next, create a file called `ga-snippet.php` within the `mu-plugins` directory and include your GA snippet function there. |
282,940 | <p>I have created <strong>custom Post type</strong>. Now I am using <strong>excerpt</strong> to show some limited words in the archive page. but I am showing same posts on the homepage in a <strong>content slider (Owl Carousel)</strong> which is giving me problem cuz <strong>excerpt size</strong>. </p>
<ol>
<li><p>So, I have decided to use <strong>first 160 words of the post</strong> to show on
the <strong>archive page</strong>. Instead of Excerpt </p></li>
<li><p>Also, I have placed <strong>Read more</strong> Button and I would like to know
how to put the link in that</p></li>
</ol>
<p>. </p>
<pre><code> <?php
/**
* Template part for displaying posts
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="row">
<div class="col-md-3">
<div class="thumbnail alignleft" style="width:100%;">
<?php echo get_the_post_thumbnail(); ?>
</div>
</div>
<div class="col-md-9">
<header class="entry-header article">
<?php
if ( is_singular() ) :
the_title( '<h1 class="entry-title">', '</h1>' );
else :
the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
endif;
if ( 'post' === get_post_type() ) : ?>
<div class="entry-meta">
<?php arcvertex_posted_on(); ?>
</div><!-- .entry-meta -->
<?php
endif; ?>
</header><!-- .entry-header -->
<div class="row">
<div class="col-md-12">
<div class="entry-content-article">
<?php echo get_the_excerpt(); ?>
</div><!-- .entry-content -->
<button type="button" class="btn btn-readmore">Read More...</button>
</div>
</div><!-- .Row -->
</div>
</div><!-- .Row -->
<hr class="half-rule-breadcrumb" style="margin-top:10px;" />
<footer class="entry-footer">
<?php arcvertex_entry_footer(); ?>
</footer><!-- .entry-footer -->
</article><!-- #post-<?php the_ID(); ?> -->
</code></pre>
| [
{
"answer_id": 282930,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": false,
"text": "<p>The header.php is the right place, but you'll need one more thing: a condition. This way you can decide on which pages to place the code and on which not to. You can check that via <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\"><code>is_page()</code></a></p>\n\n<pre><code><?php\n$relevant_pages = array('slug1', 'slug2');\nif (is_page($relevant_pages)) {\n ?>\n GA snippet\n <?php\n}\n?>\n</head>\n</code></pre>\n"
},
{
"answer_id": 282935,
"author": "ssnepenthe",
"author_id": 125601,
"author_profile": "https://wordpress.stackexchange.com/users/125601",
"pm_score": 4,
"selected": true,
"text": "<p>While you can add the snippet directly to <code>header.php</code>, a better choice is probably the <code>wp_head</code> action which should be triggered in any well-made, modern theme.</p>\n\n<p>Using this hook allows you to insert the snippet without actually modifying your theme. It might look something like this:</p>\n\n<pre><code>function wpse_282929_conditionally_print_ga_snippet() {\n if ( ! some_conditional_tag() ) {\n return;\n }\n\n ?>\n\n {GA Snippet Here}\n\n <?php\n}\nadd_action( 'wp_head', 'wpse_282929_conditionally_print_ga_snippet' );\n</code></pre>\n\n<p>Where <code>! some_conditional_tag()</code> gets replaced by the appropriate conditional that would indicate you DO NOT WANT to print the snippet, and <code>{GA Snippet Here}</code> obviously gets replaced with your specific GA snippet.</p>\n\n<p>WordPress provides a number of conditional tags to determine what kind of page your visitor is currently on.</p>\n\n<p>In fact, there are too many to list here, but you can find a complete listing on the <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\">Conditional Tags page in the codex</a>.</p>\n\n<p>As for where to include this code - if you are already working within a custom theme, you can just add it to your <code>functions.php</code> file.</p>\n\n<p>If not, I would probably recommend creating a must-use plugin. To do so, first create the <code>mu-plugins</code> directory within <code>wp-content</code> if it does not already exist. Next, create a file called <code>ga-snippet.php</code> within the <code>mu-plugins</code> directory and include your GA snippet function there.</p>\n"
}
]
| 2017/10/14 | [
"https://wordpress.stackexchange.com/questions/282940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128689/"
]
| I have created **custom Post type**. Now I am using **excerpt** to show some limited words in the archive page. but I am showing same posts on the homepage in a **content slider (Owl Carousel)** which is giving me problem cuz **excerpt size**.
1. So, I have decided to use **first 160 words of the post** to show on
the **archive page**. Instead of Excerpt
2. Also, I have placed **Read more** Button and I would like to know
how to put the link in that
.
```
<?php
/**
* Template part for displaying posts
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="row">
<div class="col-md-3">
<div class="thumbnail alignleft" style="width:100%;">
<?php echo get_the_post_thumbnail(); ?>
</div>
</div>
<div class="col-md-9">
<header class="entry-header article">
<?php
if ( is_singular() ) :
the_title( '<h1 class="entry-title">', '</h1>' );
else :
the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
endif;
if ( 'post' === get_post_type() ) : ?>
<div class="entry-meta">
<?php arcvertex_posted_on(); ?>
</div><!-- .entry-meta -->
<?php
endif; ?>
</header><!-- .entry-header -->
<div class="row">
<div class="col-md-12">
<div class="entry-content-article">
<?php echo get_the_excerpt(); ?>
</div><!-- .entry-content -->
<button type="button" class="btn btn-readmore">Read More...</button>
</div>
</div><!-- .Row -->
</div>
</div><!-- .Row -->
<hr class="half-rule-breadcrumb" style="margin-top:10px;" />
<footer class="entry-footer">
<?php arcvertex_entry_footer(); ?>
</footer><!-- .entry-footer -->
</article><!-- #post-<?php the_ID(); ?> -->
``` | While you can add the snippet directly to `header.php`, a better choice is probably the `wp_head` action which should be triggered in any well-made, modern theme.
Using this hook allows you to insert the snippet without actually modifying your theme. It might look something like this:
```
function wpse_282929_conditionally_print_ga_snippet() {
if ( ! some_conditional_tag() ) {
return;
}
?>
{GA Snippet Here}
<?php
}
add_action( 'wp_head', 'wpse_282929_conditionally_print_ga_snippet' );
```
Where `! some_conditional_tag()` gets replaced by the appropriate conditional that would indicate you DO NOT WANT to print the snippet, and `{GA Snippet Here}` obviously gets replaced with your specific GA snippet.
WordPress provides a number of conditional tags to determine what kind of page your visitor is currently on.
In fact, there are too many to list here, but you can find a complete listing on the [Conditional Tags page in the codex](https://codex.wordpress.org/Conditional_Tags).
As for where to include this code - if you are already working within a custom theme, you can just add it to your `functions.php` file.
If not, I would probably recommend creating a must-use plugin. To do so, first create the `mu-plugins` directory within `wp-content` if it does not already exist. Next, create a file called `ga-snippet.php` within the `mu-plugins` directory and include your GA snippet function there. |
282,953 | <p>I am developing a Custom wordpress theme. In my home page I have created a custom loop to show latest posts in a grid view.. I am trying to add a pagination there and the pagination shows also. But the pagination is loading same posts grids every time. This loop has also counter added where I wanted to add advertisement grid into a certain position after a grid..</p>
<p>This is the grid link <a href="https://dev.ahsanurrahman.com/myprojects/cms/wp/csdug/" rel="nofollow noreferrer">https://dev.ahsanurrahman.com/myprojects/cms/wp/csdug/</a></p>
<p>My Code is as below and I am using index.php as a front page to show this posts grid…</p>
<pre><code><?php
/**
* The main template file
*/
get_header(); ?>
<?php // Advertisement Placeing Number Functions ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_first_add_in_home_page = ot_get_option( 'place_of_first_add_in_home_page', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_second_add_in_home_page = ot_get_option( 'place_of_second_add_in_home_page', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_third_add_in_home_page = ot_get_option( 'place_of_third_add_in_home_page', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_fourth_add_in_home_page = ot_get_option( 'place_of_fourth_add_in_home_page', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_fifth_add_in_home_page = ot_get_option( 'place_of_fifth_add_in_home_page', '' );} ?>
<?php // Advertisement Block Functions ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__1__home = ot_get_option( 'p300x250__1__home', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__2__home = ot_get_option( 'p300x250__2__home', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__3__home = ot_get_option( 'p300x250__3__home', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__4__home = ot_get_option( 'p300x250__4__home', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__5__home = ot_get_option( 'p300x250__5__home', '' );} ?>
<?php // Advertisement Block Functions ?>
<div class="main-content">
<div class="main-wrap">
<div class="col-md-12 hero-post">
<?php query_posts('order=dsc&showposts=1'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="col-md-12">
<div class="col-md-9">
<div class="hero_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
</div><!-- col-md-9 ends here -->
<div class="col-md-3">
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- col-md-3 ends here -->
</div><!-- col-md-12 ends here -->
<?php endwhile; ?>
<?php endif; ?>
</div><!-- hero post ends here -->
<div class="col-md-12">
<?php
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
$query_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'paged' => $paged,
'page' => $paged,
'offset' => 1
);
$the_query = new WP_Query( $query_args ); ?>
<?php $adcounter = 1; ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<?php if ($adcounter == $place_of_first_add_in_home_page) : ?>
<?php {?>
<div class="col-md-4 home-post-grid post-container">
<?php echo $p300x250__1__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php }?>
<?php elseif ($adcounter == $place_of_second_add_in_home_page) :{ ?>
<div class="col-md-4 home-post-grid">
<?php echo $p300x250__2__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php } ?>
<?php // Second Else if ends here ?>
<?php elseif ($adcounter == $place_of_third_add_in_home_page) :{ ?>
<div class="col-md-4 home-post-grid">
<?php echo $p300x250__3__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php } ?>
<?php // 3rd Else if ends here ?>
<?php elseif ($adcounter == $place_of_fourth_add_in_home_page) :{ ?>
<div class="col-md-4 home-post-grid">
<?php echo $p300x250__4__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php } ?>
<?php // 4th Else if ends here ?>
<?php elseif ($adcounter == $place_of_fifth_add_in_home_page) :{ ?>
<div class="col-md-4 home-post-grid">
<?php echo $p300x250__5__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php } ?>
<?php // 5th Else if ends here ?>
<?php else : ?>
<?php {?>
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php }?>
<?php endif; ?>
<?php $adcounter++; ?>
<?php endwhile; ?>
</div> <!-- row ends here -->
<?php
if (function_exists(custom_pagination)) {
custom_pagination($the_query->max_num_pages,"",$paged);
}
?>
<?php wp_reset_postdata(); ?>
</div> <!-- col-md-12 ends here -->
<?php endif; ?>
</div><!-- main wrap ends here -->
<div class="clr"></div>
</div><!-- main content ends here -->
<?php get_footer(); ?>
</code></pre>
<p>And here is the custom pagination code in function.php </p>
<pre><code><?php // Custom Pagination for loop
function custom_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
/**
* This first part of our function is a fallback
* for custom pagination inside a regular loop that
* uses the global $paged and global $wp_query variables.
*
* It's good because we can now override default pagination
* in our theme, and use this function in default quries
* and custom queries.
*/
global $paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
global $wp_query;
$numpages = $wp_query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
/**
* We construct the pagination arguments to enter into our paginate_links
* function.
*/
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('&laquo;'),
'next_text' => __('&raquo;'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> ";
echo $paginate_links;
echo "</nav>";
}
} ?>
</code></pre>
| [
{
"answer_id": 282973,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>If you need an \"inner loop\" pagination, you should use your own query variable to \"carry\" the number of the requested page. This means you can not use the wordpress APIs for generating pagination links, and will have to write your own.</p>\n"
},
{
"answer_id": 283142,
"author": "FluffyKitten",
"author_id": 63360,
"author_profile": "https://wordpress.stackexchange.com/users/63360",
"pm_score": 3,
"selected": true,
"text": "<p>Between your question and comments, you say that the purpose of changing the main query is to exclude the most recent post from the main loop on your static home page, becuase it is being displayed as a \"hero\" post on its own before the rest.</p>\n\n<p>The easiest way to do this is actually using the main loop, and use the <code>pre_get_posts</code> action and <code>found_posts</code> filter to adjust it to remove the most recent post, as follows:</p>\n\n<p><strong>1. Index.php: Get the most recent post(s) using WP_Query</strong></p>\n\n<p>Use a custom query to get the most recent post</p>\n\n<pre><code><?php \n// custom query to get the most recent post\n$the_query = new WP_Query( array('posts_per_page' => '1', 'order' => 'DESC') );\n\nif( $the_query->have_posts() ): \n while ( $the_query->have_posts() ) : $the_query->the_post(); \n global $post; ?>\n\n [...display post content as required, e.g...]\n <h1><a href=\"<?php the_permalink();?>\"><?php the_title();?></a></h1>\n <?php the_content(); ?>\n\n <?php endwhile;\nendif; \nwp_reset_query(); // Restore global post data stomped by the_post(). \n?>\n</code></pre>\n\n<p><br><strong>2. Functions.php: Set up offset and pagination to remove the most recent post(s) from the main loop</strong></p>\n\n<p>Hook into <code>pre_get_posts</code> to adjust the query and pagination for the number of posts to skip, and <code>found_posts</code> filter to adjust the value of number of posts found. Add to functions.php:</p>\n\n<pre><code>/** Exclude the most recept post from the main query **/\nadd_action('pre_get_posts', 'pre_query_homepage_offset', 1 );\nfunction pre_query_homepage_offset(&$query) {\n\n // only continue if this is the main query on the homepage\n if ( !$query->is_home() || !$query->is_main_query() ) \n return;\n\n $posts_to_skip = 1; // the number of most recent posts to skip\n $posts_per_page = get_option('posts_per_page'); // get posts per page from WP settings\n\n //Detect and handle pagination...\n if ( !$query->is_paged ) // if we're on the first page...\n $offset = $posts_to_skip; //...just offset by the number of posts to skip\n else \n // Calculate the page offset if we are not on the first page\n $offset = $posts_to_skip + ( ($query->query_vars['paged']-1) * $posts_per_page );\n\n $query->set('offset',$offset); // set the offset for the query\n}\n\n\n/** Adjust the number of posts found by the main query to account for our offset **/\nadd_filter('found_posts', 'adjust_homepage_offset_pagination', 1, 2 );\nfunction adjust_homepage_offset_pagination($found_posts, $query) {\n\n // return the actual value if this isn't the main query on the homepage\n if ( !$query->is_home() || !$query->is_main_query() ) \n return $found_posts;\n\n $posts_to_skip = 1; // the number of posts to skip\n return $found_posts - $posts_to_skip;\n}\n</code></pre>\n\n<p><br><strong>3. Index.php: Display the rest of the posts (excluding the most recent) using the main loop</strong></p>\n\n<p>Instead of using a custom query, now we can use the main loop, as it now has been adjusted to exclude the most recent post by our functions in step 2.</p>\n\n<pre><code><?php if ( have_posts() ) : \n while ( have_posts() ) : the_post(); ?>\n\n [...display post content as required e.g....]\n <h2><?php the_title( ); ?></h2>\n <?php the_content(); ?>\n\n endwhile;\n\n // Previous/next page navigation.\n the_posts_pagination( array(\n 'prev_text' => __('&laquo;'),\n 'next_text' => __('&raquo;'),\n ) );\n\nendif;\n?>\n</code></pre>\n"
}
]
| 2017/10/14 | [
"https://wordpress.stackexchange.com/questions/282953",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109213/"
]
| I am developing a Custom wordpress theme. In my home page I have created a custom loop to show latest posts in a grid view.. I am trying to add a pagination there and the pagination shows also. But the pagination is loading same posts grids every time. This loop has also counter added where I wanted to add advertisement grid into a certain position after a grid..
This is the grid link <https://dev.ahsanurrahman.com/myprojects/cms/wp/csdug/>
My Code is as below and I am using index.php as a front page to show this posts grid…
```
<?php
/**
* The main template file
*/
get_header(); ?>
<?php // Advertisement Placeing Number Functions ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_first_add_in_home_page = ot_get_option( 'place_of_first_add_in_home_page', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_second_add_in_home_page = ot_get_option( 'place_of_second_add_in_home_page', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_third_add_in_home_page = ot_get_option( 'place_of_third_add_in_home_page', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_fourth_add_in_home_page = ot_get_option( 'place_of_fourth_add_in_home_page', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$place_of_fifth_add_in_home_page = ot_get_option( 'place_of_fifth_add_in_home_page', '' );} ?>
<?php // Advertisement Block Functions ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__1__home = ot_get_option( 'p300x250__1__home', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__2__home = ot_get_option( 'p300x250__2__home', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__3__home = ot_get_option( 'p300x250__3__home', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__4__home = ot_get_option( 'p300x250__4__home', '' );} ?>
<?php if ( function_exists( 'ot_get_option' ) ) {$p300x250__5__home = ot_get_option( 'p300x250__5__home', '' );} ?>
<?php // Advertisement Block Functions ?>
<div class="main-content">
<div class="main-wrap">
<div class="col-md-12 hero-post">
<?php query_posts('order=dsc&showposts=1'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="col-md-12">
<div class="col-md-9">
<div class="hero_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
</div><!-- col-md-9 ends here -->
<div class="col-md-3">
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- col-md-3 ends here -->
</div><!-- col-md-12 ends here -->
<?php endwhile; ?>
<?php endif; ?>
</div><!-- hero post ends here -->
<div class="col-md-12">
<?php
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
$query_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'paged' => $paged,
'page' => $paged,
'offset' => 1
);
$the_query = new WP_Query( $query_args ); ?>
<?php $adcounter = 1; ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<?php if ($adcounter == $place_of_first_add_in_home_page) : ?>
<?php {?>
<div class="col-md-4 home-post-grid post-container">
<?php echo $p300x250__1__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php }?>
<?php elseif ($adcounter == $place_of_second_add_in_home_page) :{ ?>
<div class="col-md-4 home-post-grid">
<?php echo $p300x250__2__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php } ?>
<?php // Second Else if ends here ?>
<?php elseif ($adcounter == $place_of_third_add_in_home_page) :{ ?>
<div class="col-md-4 home-post-grid">
<?php echo $p300x250__3__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php } ?>
<?php // 3rd Else if ends here ?>
<?php elseif ($adcounter == $place_of_fourth_add_in_home_page) :{ ?>
<div class="col-md-4 home-post-grid">
<?php echo $p300x250__4__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php } ?>
<?php // 4th Else if ends here ?>
<?php elseif ($adcounter == $place_of_fifth_add_in_home_page) :{ ?>
<div class="col-md-4 home-post-grid">
<?php echo $p300x250__5__home;?>
</div><!-- advertisement area ends here -->
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php } ?>
<?php // 5th Else if ends here ?>
<?php else : ?>
<?php {?>
<div class="col-md-4 home-post-grid">
<div class="other_post_thumbnail">
<a href="<?php the_permalink();?>"><?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif;
?></a>
</div><!-- post thumbnail ends here -->
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<h5 class="csdug_subtitle"><?php global $post; echo get_post_meta($post->ID,'wpshed_textfield',true) ?></h5>
<h3 class="entry-title"><?php the_title(); ?></h3></a>
<div class="home-grid-post-info"><?php csdug_entry_meta(); ?></div>
<div class="home-para"><?php the_excerpt();?></div>
<div class="post_love_count"><?php echo do_shortcode('[post_love_count]');?></div>
<div class="clr"></div>
<?php echo do_shortcode('[social_share_icons]');?>
<div class="clr"></div>
</div><!-- home post grid ends here -->
<?php }?>
<?php endif; ?>
<?php $adcounter++; ?>
<?php endwhile; ?>
</div> <!-- row ends here -->
<?php
if (function_exists(custom_pagination)) {
custom_pagination($the_query->max_num_pages,"",$paged);
}
?>
<?php wp_reset_postdata(); ?>
</div> <!-- col-md-12 ends here -->
<?php endif; ?>
</div><!-- main wrap ends here -->
<div class="clr"></div>
</div><!-- main content ends here -->
<?php get_footer(); ?>
```
And here is the custom pagination code in function.php
```
<?php // Custom Pagination for loop
function custom_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
/**
* This first part of our function is a fallback
* for custom pagination inside a regular loop that
* uses the global $paged and global $wp_query variables.
*
* It's good because we can now override default pagination
* in our theme, and use this function in default quries
* and custom queries.
*/
global $paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
global $wp_query;
$numpages = $wp_query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
/**
* We construct the pagination arguments to enter into our paginate_links
* function.
*/
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> ";
echo $paginate_links;
echo "</nav>";
}
} ?>
``` | Between your question and comments, you say that the purpose of changing the main query is to exclude the most recent post from the main loop on your static home page, becuase it is being displayed as a "hero" post on its own before the rest.
The easiest way to do this is actually using the main loop, and use the `pre_get_posts` action and `found_posts` filter to adjust it to remove the most recent post, as follows:
**1. Index.php: Get the most recent post(s) using WP\_Query**
Use a custom query to get the most recent post
```
<?php
// custom query to get the most recent post
$the_query = new WP_Query( array('posts_per_page' => '1', 'order' => 'DESC') );
if( $the_query->have_posts() ):
while ( $the_query->have_posts() ) : $the_query->the_post();
global $post; ?>
[...display post content as required, e.g...]
<h1><a href="<?php the_permalink();?>"><?php the_title();?></a></h1>
<?php the_content(); ?>
<?php endwhile;
endif;
wp_reset_query(); // Restore global post data stomped by the_post().
?>
```
**2. Functions.php: Set up offset and pagination to remove the most recent post(s) from the main loop**
Hook into `pre_get_posts` to adjust the query and pagination for the number of posts to skip, and `found_posts` filter to adjust the value of number of posts found. Add to functions.php:
```
/** Exclude the most recept post from the main query **/
add_action('pre_get_posts', 'pre_query_homepage_offset', 1 );
function pre_query_homepage_offset(&$query) {
// only continue if this is the main query on the homepage
if ( !$query->is_home() || !$query->is_main_query() )
return;
$posts_to_skip = 1; // the number of most recent posts to skip
$posts_per_page = get_option('posts_per_page'); // get posts per page from WP settings
//Detect and handle pagination...
if ( !$query->is_paged ) // if we're on the first page...
$offset = $posts_to_skip; //...just offset by the number of posts to skip
else
// Calculate the page offset if we are not on the first page
$offset = $posts_to_skip + ( ($query->query_vars['paged']-1) * $posts_per_page );
$query->set('offset',$offset); // set the offset for the query
}
/** Adjust the number of posts found by the main query to account for our offset **/
add_filter('found_posts', 'adjust_homepage_offset_pagination', 1, 2 );
function adjust_homepage_offset_pagination($found_posts, $query) {
// return the actual value if this isn't the main query on the homepage
if ( !$query->is_home() || !$query->is_main_query() )
return $found_posts;
$posts_to_skip = 1; // the number of posts to skip
return $found_posts - $posts_to_skip;
}
```
**3. Index.php: Display the rest of the posts (excluding the most recent) using the main loop**
Instead of using a custom query, now we can use the main loop, as it now has been adjusted to exclude the most recent post by our functions in step 2.
```
<?php if ( have_posts() ) :
while ( have_posts() ) : the_post(); ?>
[...display post content as required e.g....]
<h2><?php the_title( ); ?></h2>
<?php the_content(); ?>
endwhile;
// Previous/next page navigation.
the_posts_pagination( array(
'prev_text' => __('«'),
'next_text' => __('»'),
) );
endif;
?>
``` |
283,001 | <p>The below is just a scenario to provide context so you understand what im trying to accomplish, However please keep your answers related to the title if possible and a css solution/function. </p>
<p>I have a podcast site that im working on. And i have "next" and "prev" buttons on the podcast post pages that take the user in order to the next podcast episode by date and these buttons only display for the podcast post category.</p>
<p>(so just regular wordpress blog posts in a category called "podcast")</p>
<p>My issue is the most recent podcast post (for example podcast Ep# 150) would display a "next" episode button. - Being that Ep#150 is the newest podcast post there should be no "Next" button displayed. Right now its taking you to "Ep# 1" when you press it which makes sense, but i would rather not direct users to older episodes on our newest posts.</p>
<p>So i just want to "display:none;" that button on the most recent post in the podcast category.</p>
<p>Thanks for any help!</p>
<pre><code><span class="prev-ep-wrap">
<span class="prev-ep">
<?php next_post_link_plus( array( 'order_by' => 'post_date', 'loop' => true, 'tooltip' => 'Previous Episode', 'in_same_cat' => true, 'ex_cats' => '30, 11', 'link' => 'Previous Episode' ) );?>
</span>
</span>
<span class="next-ep-wrap">
<span class="next-ep">
<?php previous_post_link_plus( array( 'order_by' => 'post_date', 'loop' => true, 'tooltip' => 'Next Episode', 'in_same_cat' => true, 'ex_cats' => '30, 11', 'link' => 'Next Episode' ) );?>
</span>
</span>
</code></pre>
| [
{
"answer_id": 283002,
"author": "L.Milo",
"author_id": 129596,
"author_profile": "https://wordpress.stackexchange.com/users/129596",
"pm_score": 1,
"selected": false,
"text": "<p>From the context of your question I understand that you don't use <code>next_post_link</code> and <code>previous_post_link</code> for the implementation of the <em>Next</em> and <em>Prev</em> buttons, so you have to use CSS to hide them appropriately.</p>\n\n<p><code>next_post_link</code> and <code>previous_post_link</code> simply don't display the links if the current post is the last/first on the loop, so I think it would be better to add them in your template instead of using CSS.</p>\n\n<p>You can check the documentation here: </p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/next_post_link\" rel=\"nofollow noreferrer\">next_post_link</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/previous_post_link\" rel=\"nofollow noreferrer\">previous_post_link</a></li>\n</ul>\n"
},
{
"answer_id": 283061,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 0,
"selected": false,
"text": "<p>I highly suggest using <a href=\"https://wordpress.stackexchange.com/a/283002/108180\">L.Milo's answer</a>, since this will actually solve the problem and adding custom CSS will only masquerade it.</p>\n\n<hr>\n\n<p>To add custom CSS to the latest post of a category, the following should work. It does the following</p>\n\n<ol>\n<li>Get the id of the latest post of that category using <a href=\"https://developer.wordpress.org/reference/functions/wp_get_recent_posts/\" rel=\"nofollow noreferrer\"><code>wp_get_recent_posts()</code></a></li>\n<li>Check if currently a single post is displayed and if so, check if it has the id of the latest post (ie., it is the latest post)</li>\n<li>If so, enqueue another stylesheet.</li>\n</ol>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\nfunction wpse_enqueue_on_latest_post() {\n $args = array(\n 'numberposts' => 1,\n 'category' => 12,// id of the category\n );\n list($latest) = wp_get_recent_posts($args);\n\n if (is_single( $latest['ID'] )) {\n wp_enqueue_style( ... );\n }\n}\nadd_action('init', 'wpse_enqueue_on_latest_post');\n</code></pre>\n\n<p>Alternatively, you could add a custom body class and use the same stylesheet, where you differentiate exactly via that class</p>\n\n<pre><code><?php\n\nfunction wpse_add_latest_post_body_class($classes) {\n $args = array(\n 'numberposts' => 1,\n 'category' => 12,// id of the category\n );\n list($latest) = wp_get_recent_posts($args);\n\n if (is_single( $latest['ID'] )) {\n $classes[] = 'latest-of-category-xxx';\n }\n return $classes;\n}\nadd_filter('body_class', 'wpse_add_latest_post_body_class');\n</code></pre>\n"
}
]
| 2017/10/15 | [
"https://wordpress.stackexchange.com/questions/283001",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110570/"
]
| The below is just a scenario to provide context so you understand what im trying to accomplish, However please keep your answers related to the title if possible and a css solution/function.
I have a podcast site that im working on. And i have "next" and "prev" buttons on the podcast post pages that take the user in order to the next podcast episode by date and these buttons only display for the podcast post category.
(so just regular wordpress blog posts in a category called "podcast")
My issue is the most recent podcast post (for example podcast Ep# 150) would display a "next" episode button. - Being that Ep#150 is the newest podcast post there should be no "Next" button displayed. Right now its taking you to "Ep# 1" when you press it which makes sense, but i would rather not direct users to older episodes on our newest posts.
So i just want to "display:none;" that button on the most recent post in the podcast category.
Thanks for any help!
```
<span class="prev-ep-wrap">
<span class="prev-ep">
<?php next_post_link_plus( array( 'order_by' => 'post_date', 'loop' => true, 'tooltip' => 'Previous Episode', 'in_same_cat' => true, 'ex_cats' => '30, 11', 'link' => 'Previous Episode' ) );?>
</span>
</span>
<span class="next-ep-wrap">
<span class="next-ep">
<?php previous_post_link_plus( array( 'order_by' => 'post_date', 'loop' => true, 'tooltip' => 'Next Episode', 'in_same_cat' => true, 'ex_cats' => '30, 11', 'link' => 'Next Episode' ) );?>
</span>
</span>
``` | From the context of your question I understand that you don't use `next_post_link` and `previous_post_link` for the implementation of the *Next* and *Prev* buttons, so you have to use CSS to hide them appropriately.
`next_post_link` and `previous_post_link` simply don't display the links if the current post is the last/first on the loop, so I think it would be better to add them in your template instead of using CSS.
You can check the documentation here:
* [next\_post\_link](https://codex.wordpress.org/Function_Reference/next_post_link)
* [previous\_post\_link](https://codex.wordpress.org/Function_Reference/previous_post_link) |
283,086 | <pre><code>$args = array(
'post_type' => 'events',
'order' => 'ASC',
);
$wp_query = new WP_Query($args);
?>
<script type="application/ld+json">
{
"@context":"http://schema.org",
"@type":"ItemList",
"itemListElement":[
<?php while ( have_posts() ) : the_post(); ?>
{
"@type":"ListItem",
"position":1,
"url":"<?php the_permalink(); ?>"
},
<?php endwhile; ?>
]
}
</script>
</code></pre>
<p>I am putting a schematic to display a Carousels, but it is required to place the <code>"position": 1</code></p>
<p>I need help for the loop to increase the number 1. "position": <strong>1</strong></p>
<p>also remove last comma from last post</p>
| [
{
"answer_id": 283002,
"author": "L.Milo",
"author_id": 129596,
"author_profile": "https://wordpress.stackexchange.com/users/129596",
"pm_score": 1,
"selected": false,
"text": "<p>From the context of your question I understand that you don't use <code>next_post_link</code> and <code>previous_post_link</code> for the implementation of the <em>Next</em> and <em>Prev</em> buttons, so you have to use CSS to hide them appropriately.</p>\n\n<p><code>next_post_link</code> and <code>previous_post_link</code> simply don't display the links if the current post is the last/first on the loop, so I think it would be better to add them in your template instead of using CSS.</p>\n\n<p>You can check the documentation here: </p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/next_post_link\" rel=\"nofollow noreferrer\">next_post_link</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/previous_post_link\" rel=\"nofollow noreferrer\">previous_post_link</a></li>\n</ul>\n"
},
{
"answer_id": 283061,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 0,
"selected": false,
"text": "<p>I highly suggest using <a href=\"https://wordpress.stackexchange.com/a/283002/108180\">L.Milo's answer</a>, since this will actually solve the problem and adding custom CSS will only masquerade it.</p>\n\n<hr>\n\n<p>To add custom CSS to the latest post of a category, the following should work. It does the following</p>\n\n<ol>\n<li>Get the id of the latest post of that category using <a href=\"https://developer.wordpress.org/reference/functions/wp_get_recent_posts/\" rel=\"nofollow noreferrer\"><code>wp_get_recent_posts()</code></a></li>\n<li>Check if currently a single post is displayed and if so, check if it has the id of the latest post (ie., it is the latest post)</li>\n<li>If so, enqueue another stylesheet.</li>\n</ol>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\nfunction wpse_enqueue_on_latest_post() {\n $args = array(\n 'numberposts' => 1,\n 'category' => 12,// id of the category\n );\n list($latest) = wp_get_recent_posts($args);\n\n if (is_single( $latest['ID'] )) {\n wp_enqueue_style( ... );\n }\n}\nadd_action('init', 'wpse_enqueue_on_latest_post');\n</code></pre>\n\n<p>Alternatively, you could add a custom body class and use the same stylesheet, where you differentiate exactly via that class</p>\n\n<pre><code><?php\n\nfunction wpse_add_latest_post_body_class($classes) {\n $args = array(\n 'numberposts' => 1,\n 'category' => 12,// id of the category\n );\n list($latest) = wp_get_recent_posts($args);\n\n if (is_single( $latest['ID'] )) {\n $classes[] = 'latest-of-category-xxx';\n }\n return $classes;\n}\nadd_filter('body_class', 'wpse_add_latest_post_body_class');\n</code></pre>\n"
}
]
| 2017/10/16 | [
"https://wordpress.stackexchange.com/questions/283086",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129093/"
]
| ```
$args = array(
'post_type' => 'events',
'order' => 'ASC',
);
$wp_query = new WP_Query($args);
?>
<script type="application/ld+json">
{
"@context":"http://schema.org",
"@type":"ItemList",
"itemListElement":[
<?php while ( have_posts() ) : the_post(); ?>
{
"@type":"ListItem",
"position":1,
"url":"<?php the_permalink(); ?>"
},
<?php endwhile; ?>
]
}
</script>
```
I am putting a schematic to display a Carousels, but it is required to place the `"position": 1`
I need help for the loop to increase the number 1. "position": **1**
also remove last comma from last post | From the context of your question I understand that you don't use `next_post_link` and `previous_post_link` for the implementation of the *Next* and *Prev* buttons, so you have to use CSS to hide them appropriately.
`next_post_link` and `previous_post_link` simply don't display the links if the current post is the last/first on the loop, so I think it would be better to add them in your template instead of using CSS.
You can check the documentation here:
* [next\_post\_link](https://codex.wordpress.org/Function_Reference/next_post_link)
* [previous\_post\_link](https://codex.wordpress.org/Function_Reference/previous_post_link) |
283,109 | <p>In the list of posts in the 'All Posts' screen, is there a way to display both date -and- time in the Date column? If you hover over the date, the time is part of abbr tag title, but I'd like to display the time, directly. I see that I could unset the current Date column and put in a custom Date column. Just wondering if there is a simpler solution to show the time, since it's already there in the abbr tag?</p>
| [
{
"answer_id": 283113,
"author": "Milan Petrovic",
"author_id": 126702,
"author_profile": "https://wordpress.stackexchange.com/users/126702",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it with some JavaScript:</p>\n\n<pre><code>jQuery(\".column-date abbr\").each(function(){\n jQuery(this).html(jQuery(this).attr(\"title\").replace(\" \", \"<br/>\"));\n jQuery(this).removeAttr(\"title\");\n});\n</code></pre>\n\n<p>This will replace visible date portion with date and time and will clear the title attribute.</p>\n"
},
{
"answer_id": 283118,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 3,
"selected": true,
"text": "<p>Add this code to <code>functions.php</code> of your active theme:</p>\n\n<pre><code>function wpse_posts_list_date_format( $time, $post ) {\n return $post->post_date;\n}\nadd_filter( 'post_date_column_time', 'wpse_posts_list_date_format', 10, 2 );\n</code></pre>\n\n<p>The callback function receives 4 parameters, but we need only 2.</p>\n"
}
]
| 2017/10/16 | [
"https://wordpress.stackexchange.com/questions/283109",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94243/"
]
| In the list of posts in the 'All Posts' screen, is there a way to display both date -and- time in the Date column? If you hover over the date, the time is part of abbr tag title, but I'd like to display the time, directly. I see that I could unset the current Date column and put in a custom Date column. Just wondering if there is a simpler solution to show the time, since it's already there in the abbr tag? | Add this code to `functions.php` of your active theme:
```
function wpse_posts_list_date_format( $time, $post ) {
return $post->post_date;
}
add_filter( 'post_date_column_time', 'wpse_posts_list_date_format', 10, 2 );
```
The callback function receives 4 parameters, but we need only 2. |
283,115 | <p>Using gravity forms as a front end file up-loader, users can upload gallery images via a form which then saves to a ACF ( advanced custom forms ) gallery field.</p>
<p>It works to a point, the form uploads the images and they are stored in gravity form entry (you can view the images just fine). </p>
<p>The second part of the code below attempts to move the image from the gravity form attachment into the media library as a post attachment </p>
<p>This is where it fails, leaving the image file name but a broken image ( 0kb in size ).</p>
<p>The original code can be found here, but I'm at a loss as to where the problem is : <a href="https://joshuadnelson.com/connect-gravity-forms-file-upload-to-acf-gallery-field/" rel="nofollow noreferrer">https://joshuadnelson.com/connect-gravity-forms-file-upload-to-acf-gallery-field/</a></p>
<pre><code>/**
* Attach images uploaded through Gravity Form to ACF Gallery Field
*
* @return void
*/
$gravity_form_id = 10; // gravity form id, or replace {$gravity_form_id} below with this number
add_filter( "gform_after_submission_{$gravity_form_id}", 'jdn_set_post_acf_gallery_field', 10, 2 );
function jdn_set_post_acf_gallery_field( $entry, $form ) {
$gf_images_field_id = 69; // the upload field id
$acf_field_id = 'field_59e260b6e28fd'; // the acf gallery field id
// get post, if there isn't one, bail
if( isset( $entry['post_id'] ) ) {
$post = get_post( $entry['post_id'] );
if( is_null( $post ) )
return;
} else {
return;
}
// Clean up images upload and create array for gallery field
if( isset( $entry[ $gf_images_field_id ] ) ) {
$images = stripslashes( $entry[ $gf_images_field_id ] );
$images = json_decode( $images, true );
if( !empty( $images ) && is_array( $images ) ) {
$gallery = array();
foreach( $images as $key => $value ) {
// NOTE: this is the other function you need: https://gist.github.com/joshuadavidnelson/164a0a0744f0693d5746
if( ! class_exists( 'JDN_Create_Media_File' ) )
break;
// Create the media library attachment and store the attachment id in the gallery array
$create_image = new JDN_Create_Media_File( $value, $post->ID );
$image_id = $create_image->attachment_id;
if( absint( $image_id ) ) {
$gallery[] = $image_id;
}
}
}
}
// Update gallery field with array
if( ! empty( $gallery ) ) {
update_field( $acf_field_id, $gallery, $post->ID );
}
}
</code></pre>
<p>__</p>
<pre><code> <?php
class JDN_Create_Media_File {
var $post_id;
var $image_url;
var $wp_upload_url;
var $attachment_id;
/**
* Setup the class variables
*/
public function __construct( $image_url, $post_id = 0 ) {
// Setup class variables
$this->image_url = esc_url( $image_url );
$this->post_id = absint( $post_id );
$this->wp_upload_url = $this->get_wp_upload_url();
$this->attachment_id = $this->attachment_id ?: false;
return $this->create_image_id();
}
/**
* Set the upload directory
*/
private function get_wp_upload_url() {
$wp_upload_dir = wp_upload_dir();
return isset( $wp_upload_dir['url'] ) ? $wp_upload_dir['url'] : false;
}
/**
* Create the image and return the new media upload id.
*
* @see https://gist.github.com/hissy/7352933
*
* @see http://codex.wordpress.org/Function_Reference/wp_insert_attachment#Example
*/
public function create_image_id() {
if( $this->attachment_id )
return $this->attachment_id;
if( empty( $this->image_url ) || empty( $this->wp_upload_url ) )
return false;
$filename = basename( $this->image_url );
$upload_file = wp_upload_bits( $filename, null, file_get_contents( $this->image_url ) );
if ( ! $upload_file['error'] ) {
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $this->post_id,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $this->post_id );
if( ! is_wp_error( $attachment_id ) ) {
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
$this->attachment_id = $attachment_id;
return $attachment_id;
}
}
return false;
} // end function get_image_id
}
</code></pre>
| [
{
"answer_id": 283157,
"author": "Marcelo Henriques Cortez",
"author_id": 44437,
"author_profile": "https://wordpress.stackexchange.com/users/44437",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similiar problem and found a solution for my specific problem using 'media_handle_upload' (<a href=\"https://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/media_handle_upload</a>).</p>\n\n<p><em>First</em> - Make sure your form has the attribute 'enctype='multipart/form-data'.</p>\n\n<p><em>Second</em> - Be sure that your 'input=file' has no value attribute.</p>\n\n<p><em>Third</em> - Use the 'media_handle_upload' and pass the name of your 'input=file'.</p>\n\n<p><em>Forth</em> - Check if there was an error with 'is_wp_error', for example.</p>\n\n<p><em>Fifth</em> - Update the user meta using the name of the field you want to update (in my case, is the same as the 'name' of the 'input=file'.</p>\n\n<p>My question and complete answer are here: <a href=\"https://wordpress.stackexchange.com/questions/282586/acf-upload-image-in-front-end-with-custom-form/283079#283079\">ACF Upload Image in front-end with custom form</a></p>\n\n<p>Hope my code can help you with your question... It probably can, you just have to adapt it.</p>\n"
},
{
"answer_id": 283297,
"author": "Dave from Gravity Wiz",
"author_id": 50224,
"author_profile": "https://wordpress.stackexchange.com/users/50224",
"pm_score": 1,
"selected": false,
"text": "<p>An even easier option is to use my <a href=\"https://gravitywiz.com/documentation/gravity-forms-media-library/\" rel=\"nofollow noreferrer\">Gravity Forms Media Library</a> plugin. Here's the meat and potatoes of the functionality:</p>\n\n<pre><code>public function maybe_upload_to_media_library( $entry, $form ) {\n\n $has_change = false;\n\n foreach( $form['fields'] as $field ) {\n\n if( ! $this->is_applicable_field( $field ) ) {\n continue;\n }\n\n $value = $entry[ $field->id ];\n\n if( $field->multipleFiles ) {\n $value = json_decode( $value );\n }\n\n if( empty( $value ) ) {\n continue;\n }\n\n $has_change = true;\n $ids = $this->upload_to_media_library( $value, $field, $entry );\n $new_value = array();\n\n if( is_wp_error( $ids ) ) {\n continue;\n }\n\n foreach( $ids as $id ) {\n if( ! is_wp_error( $id ) ) {\n $new_value[] = wp_get_attachment_url( $id );\n }\n }\n\n if( $field->multipleFiles ) {\n $new_value = json_encode( $new_value );\n } else {\n $new_value = $new_value[0];\n $ids = $ids[0];\n }\n\n $entry[ $field->id ] = $new_value;\n\n $this->update_file_ids( $entry['id'], $field->id, $ids );\n\n }\n\n if( $has_change ) {\n GFAPI::update_entry( $entry );\n }\n\n return $entry;\n}\n</code></pre>\n\n<p>But... it also handles a ton of other use-cases you may not be considering such as updating the entry, multi-file uploads, and auto-integration with ACF various image-based custom field types.</p>\n"
}
]
| 2017/10/16 | [
"https://wordpress.stackexchange.com/questions/283115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62291/"
]
| Using gravity forms as a front end file up-loader, users can upload gallery images via a form which then saves to a ACF ( advanced custom forms ) gallery field.
It works to a point, the form uploads the images and they are stored in gravity form entry (you can view the images just fine).
The second part of the code below attempts to move the image from the gravity form attachment into the media library as a post attachment
This is where it fails, leaving the image file name but a broken image ( 0kb in size ).
The original code can be found here, but I'm at a loss as to where the problem is : <https://joshuadnelson.com/connect-gravity-forms-file-upload-to-acf-gallery-field/>
```
/**
* Attach images uploaded through Gravity Form to ACF Gallery Field
*
* @return void
*/
$gravity_form_id = 10; // gravity form id, or replace {$gravity_form_id} below with this number
add_filter( "gform_after_submission_{$gravity_form_id}", 'jdn_set_post_acf_gallery_field', 10, 2 );
function jdn_set_post_acf_gallery_field( $entry, $form ) {
$gf_images_field_id = 69; // the upload field id
$acf_field_id = 'field_59e260b6e28fd'; // the acf gallery field id
// get post, if there isn't one, bail
if( isset( $entry['post_id'] ) ) {
$post = get_post( $entry['post_id'] );
if( is_null( $post ) )
return;
} else {
return;
}
// Clean up images upload and create array for gallery field
if( isset( $entry[ $gf_images_field_id ] ) ) {
$images = stripslashes( $entry[ $gf_images_field_id ] );
$images = json_decode( $images, true );
if( !empty( $images ) && is_array( $images ) ) {
$gallery = array();
foreach( $images as $key => $value ) {
// NOTE: this is the other function you need: https://gist.github.com/joshuadavidnelson/164a0a0744f0693d5746
if( ! class_exists( 'JDN_Create_Media_File' ) )
break;
// Create the media library attachment and store the attachment id in the gallery array
$create_image = new JDN_Create_Media_File( $value, $post->ID );
$image_id = $create_image->attachment_id;
if( absint( $image_id ) ) {
$gallery[] = $image_id;
}
}
}
}
// Update gallery field with array
if( ! empty( $gallery ) ) {
update_field( $acf_field_id, $gallery, $post->ID );
}
}
```
\_\_
```
<?php
class JDN_Create_Media_File {
var $post_id;
var $image_url;
var $wp_upload_url;
var $attachment_id;
/**
* Setup the class variables
*/
public function __construct( $image_url, $post_id = 0 ) {
// Setup class variables
$this->image_url = esc_url( $image_url );
$this->post_id = absint( $post_id );
$this->wp_upload_url = $this->get_wp_upload_url();
$this->attachment_id = $this->attachment_id ?: false;
return $this->create_image_id();
}
/**
* Set the upload directory
*/
private function get_wp_upload_url() {
$wp_upload_dir = wp_upload_dir();
return isset( $wp_upload_dir['url'] ) ? $wp_upload_dir['url'] : false;
}
/**
* Create the image and return the new media upload id.
*
* @see https://gist.github.com/hissy/7352933
*
* @see http://codex.wordpress.org/Function_Reference/wp_insert_attachment#Example
*/
public function create_image_id() {
if( $this->attachment_id )
return $this->attachment_id;
if( empty( $this->image_url ) || empty( $this->wp_upload_url ) )
return false;
$filename = basename( $this->image_url );
$upload_file = wp_upload_bits( $filename, null, file_get_contents( $this->image_url ) );
if ( ! $upload_file['error'] ) {
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $this->post_id,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $this->post_id );
if( ! is_wp_error( $attachment_id ) ) {
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
$this->attachment_id = $attachment_id;
return $attachment_id;
}
}
return false;
} // end function get_image_id
}
``` | An even easier option is to use my [Gravity Forms Media Library](https://gravitywiz.com/documentation/gravity-forms-media-library/) plugin. Here's the meat and potatoes of the functionality:
```
public function maybe_upload_to_media_library( $entry, $form ) {
$has_change = false;
foreach( $form['fields'] as $field ) {
if( ! $this->is_applicable_field( $field ) ) {
continue;
}
$value = $entry[ $field->id ];
if( $field->multipleFiles ) {
$value = json_decode( $value );
}
if( empty( $value ) ) {
continue;
}
$has_change = true;
$ids = $this->upload_to_media_library( $value, $field, $entry );
$new_value = array();
if( is_wp_error( $ids ) ) {
continue;
}
foreach( $ids as $id ) {
if( ! is_wp_error( $id ) ) {
$new_value[] = wp_get_attachment_url( $id );
}
}
if( $field->multipleFiles ) {
$new_value = json_encode( $new_value );
} else {
$new_value = $new_value[0];
$ids = $ids[0];
}
$entry[ $field->id ] = $new_value;
$this->update_file_ids( $entry['id'], $field->id, $ids );
}
if( $has_change ) {
GFAPI::update_entry( $entry );
}
return $entry;
}
```
But... it also handles a ton of other use-cases you may not be considering such as updating the entry, multi-file uploads, and auto-integration with ACF various image-based custom field types. |
283,127 | <p>I'm trying to make home widgets 1, 2, and 3 appear horizontally next to one another. Currently, they are propagating on top of each other, rather than next to each other. I've coded the widgets to include some external links, a facebook link, and a donation link. Unfortunately, this is a project for a class and includes code and information for our professor's personal business, some of which is not prepared for publication. If any information is required about the code, please let me know. I am new to both wordpress and HTML coding, and mainly concerned with organizing these widgets. Is it something that can be done in the wordpress dashboard, or is it a coding issue? Thanks.</p>
| [
{
"answer_id": 283147,
"author": "Anson W Han",
"author_id": 129547,
"author_profile": "https://wordpress.stackexchange.com/users/129547",
"pm_score": 1,
"selected": false,
"text": "<p>The widgets are rendered as 'divs' in the html, which by default appear as blocks that would stack as you are seeing them.</p>\n\n<p>To get the behavior you want, you need to add css styles to your theme's style sheet to either \"float\" these blocks up against each other, or set fixed or percentage widths for each and display as desired inline-blocks.</p>\n\n<p>You can learn more about block VS inline-blocks and other display types for html elements here: <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/display\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/CSS/display</a></p>\n"
},
{
"answer_id": 283249,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 1,
"selected": true,
"text": "<p>Use <code>CSS3 flexbox</code> to control layout of widgets. First, wrap widget divisions in a container division <code><div class=\"widgets-container\"></code>. Add a unique class to each widget division ( in our example: <em>widget-1</em>, <em>widget-2</em>, and <em>widget-3</em> ). Example code:</p>\n\n<pre><code><div class=\"widgets-container\">\n\n <div class=\"widget-1\">\n <!-- widget-1 code below -->\n <h2>Widget 1</h2>\n </div>\n\n <div class=\"widget-2\">\n <!-- widget 2 code below -->\n <h2>Widget 2</h2>\n </div>\n\n <div class=\"widget-2\">\n <!-- widget 3 code below -->\n <h2>Widget 2</h2>\n </div>\n\n</div>\n</code></pre>\n\n<p>This is all for <em>HTML</em> part. The rest is pure <em>CSS</em>:</p>\n\n<pre><code>.widgets-container {\n display: flex;\n -webkit-justify-content: space-between;\n justify-content: space-between;\n}\n\n.widget-1, .widget-2, widget-3 {\n width: 30%; \n text-align: center;\n border: solid thin;\n}\n</code></pre>\n\n<p>More info about <a href=\"https://www.w3schools.com/css/css3_flexbox.asp\" rel=\"nofollow noreferrer\">CSS Flexbox</a>.</p>\n"
}
]
| 2017/10/16 | [
"https://wordpress.stackexchange.com/questions/283127",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| I'm trying to make home widgets 1, 2, and 3 appear horizontally next to one another. Currently, they are propagating on top of each other, rather than next to each other. I've coded the widgets to include some external links, a facebook link, and a donation link. Unfortunately, this is a project for a class and includes code and information for our professor's personal business, some of which is not prepared for publication. If any information is required about the code, please let me know. I am new to both wordpress and HTML coding, and mainly concerned with organizing these widgets. Is it something that can be done in the wordpress dashboard, or is it a coding issue? Thanks. | Use `CSS3 flexbox` to control layout of widgets. First, wrap widget divisions in a container division `<div class="widgets-container">`. Add a unique class to each widget division ( in our example: *widget-1*, *widget-2*, and *widget-3* ). Example code:
```
<div class="widgets-container">
<div class="widget-1">
<!-- widget-1 code below -->
<h2>Widget 1</h2>
</div>
<div class="widget-2">
<!-- widget 2 code below -->
<h2>Widget 2</h2>
</div>
<div class="widget-2">
<!-- widget 3 code below -->
<h2>Widget 2</h2>
</div>
</div>
```
This is all for *HTML* part. The rest is pure *CSS*:
```
.widgets-container {
display: flex;
-webkit-justify-content: space-between;
justify-content: space-between;
}
.widget-1, .widget-2, widget-3 {
width: 30%;
text-align: center;
border: solid thin;
}
```
More info about [CSS Flexbox](https://www.w3schools.com/css/css3_flexbox.asp). |
283,130 | <p>The Featured Image Box is not showing inside the WP admin area for my custom post type (in normal post it does).</p>
<p>Things i've already done: <strong>add the theme support</strong> within action hook with <code>after_setup_theme</code></p>
<pre><code>// Register Theme Features
function custom_theme_features() {
// Add theme support for Post Formats
add_theme_support( 'post-formats', array( 'video' ) );
// Add theme support for Featured Images
add_theme_support( 'post-thumbnails' );
add_theme_support( 'post-thumbnails', array( 'customposttypename' ) );
// Set custom thumbnail dimensions
// set_post_thumbnail_size( 300, 300, true );
// Add theme support for HTML5 Semantic Markup
add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ) );
// Add theme support for document Title tag
add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'custom_theme_features' );
</code></pre>
<p>And inside the <code>register_post_type</code> i added to <code>supports</code> the <code>thumbnail</code> value.</p>
<p>Like this:</p>
<pre><code>function mp_cpt_mycustomposttype() {
$labels = array(
'name' => 'TheName',
'...'
);
$args = array(
'label' => 'TheName',
'description' => 'TheNamePlural',
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'custom-fields', ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => false,
'can_export' => true,
'has_archive' => false,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'customposttypename', $args );
}
add_action( 'init', 'mp_cpt_mycustomposttype', 0 );
</code></pre>
<p><strong>BUT</strong> the box for featured image still won't show at my custom post type.
Of course i double and tripple checked over and over again the display options:</p>
<p><a href="https://i.stack.imgur.com/P4whM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P4whM.png" alt="display options"></a></p>
<p>(Not) surprisingly the featured image box in the default post type <code>post</code> is there.</p>
<p>Maybe some important information for you: my installation is local and made with Trellis and Bedrock. Don't know if there is an impact. Already tried to deactivate the <code>mu-plugins</code> - without any success.</p>
<p>What the heck am i missing about these little sh*tty box?! Drives me completely insane...</p>
<p>Any help to make this work is really appreciated!</p>
| [
{
"answer_id": 283478,
"author": "Ray Gulick",
"author_id": 30,
"author_profile": "https://wordpress.stackexchange.com/users/30",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have a template tag on your listing page?</p>\n\n<p>Template tag for listing page:\nget_the_post_thumbnail( $post->ID, 'thumbnail' );</p>\n"
},
{
"answer_id": 283634,
"author": "Ray Gulick",
"author_id": 30,
"author_profile": "https://wordpress.stackexchange.com/users/30",
"pm_score": 2,
"selected": true,
"text": "<p>I think it's possible the 2 separate enabling statements may be interfering with each other. The purpose of having an array is to combine them into one enabling statement. Try the following in your functions file. </p>\n\n<p>Instead of: </p>\n\n<pre><code>add_theme_support( 'post-thumbnails' ); \nadd_theme_support( 'post-thumbnails', array( 'customposttypename' ) ); \n</code></pre>\n\n<p>This: </p>\n\n<pre><code>add_theme_support( 'post-thumbnails', array( 'post', 'customposttypename' ) );\n</code></pre>\n"
}
]
| 2017/10/16 | [
"https://wordpress.stackexchange.com/questions/283130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129738/"
]
| The Featured Image Box is not showing inside the WP admin area for my custom post type (in normal post it does).
Things i've already done: **add the theme support** within action hook with `after_setup_theme`
```
// Register Theme Features
function custom_theme_features() {
// Add theme support for Post Formats
add_theme_support( 'post-formats', array( 'video' ) );
// Add theme support for Featured Images
add_theme_support( 'post-thumbnails' );
add_theme_support( 'post-thumbnails', array( 'customposttypename' ) );
// Set custom thumbnail dimensions
// set_post_thumbnail_size( 300, 300, true );
// Add theme support for HTML5 Semantic Markup
add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ) );
// Add theme support for document Title tag
add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'custom_theme_features' );
```
And inside the `register_post_type` i added to `supports` the `thumbnail` value.
Like this:
```
function mp_cpt_mycustomposttype() {
$labels = array(
'name' => 'TheName',
'...'
);
$args = array(
'label' => 'TheName',
'description' => 'TheNamePlural',
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'custom-fields', ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => false,
'can_export' => true,
'has_archive' => false,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'customposttypename', $args );
}
add_action( 'init', 'mp_cpt_mycustomposttype', 0 );
```
**BUT** the box for featured image still won't show at my custom post type.
Of course i double and tripple checked over and over again the display options:
[](https://i.stack.imgur.com/P4whM.png)
(Not) surprisingly the featured image box in the default post type `post` is there.
Maybe some important information for you: my installation is local and made with Trellis and Bedrock. Don't know if there is an impact. Already tried to deactivate the `mu-plugins` - without any success.
What the heck am i missing about these little sh\*tty box?! Drives me completely insane...
Any help to make this work is really appreciated! | I think it's possible the 2 separate enabling statements may be interfering with each other. The purpose of having an array is to combine them into one enabling statement. Try the following in your functions file.
Instead of:
```
add_theme_support( 'post-thumbnails' );
add_theme_support( 'post-thumbnails', array( 'customposttypename' ) );
```
This:
```
add_theme_support( 'post-thumbnails', array( 'post', 'customposttypename' ) );
``` |
283,135 | <p>I'm not exactly sure of the best way to ask what I am trying to achieve, so I'm going to describe it here. If someone can identify a more succinct way to ask this, or if it's been answered in a different way, please let me know!</p>
<p>For example sake, I going to describe a photographer's WordPress site, where there would be a Portfolio archive page listing available taxonomies, say Nature, Landscape, and Portraits.</p>
<p>This Portfolio page had a grid of entries, displayed from all various Portfolio taxonomies. Above the grid, would be a navigation bar listing those taxonomies:</p>
<p><strong>All | Nature | Landscape | Portraits</strong></p>
<p>When one of the taxonomy menu options is clicked, the grid filters to the user selection using JavaScript. For example, when "Nature" is clicked, only Nature entries are shown and all others are invisible.</p>
<p>The Nature taxonomy would also have its own page, accessed via the slug: mysite.com/portfolio/nature - I do not want this page to exist.</p>
<p>I would like to be able to use that Nature URL above to go to the Portfolio archive page and have it filtered to the Nature entries by JavaScript when the page is ready.</p>
<p><strong>Essentially, I would like the URL mysite.com/portfolio/nature to act as mysite.com/portfolio/?tax=nature</strong> - where the tax GET var would get registered in PHP (and later outputted to JavaScript) and then the parent Portfolio archive page is loaded.</p>
<p>I'm not looking for any help with the actual JavaScript implementation of this, I'm looking for advice for how to handle the URL rewriting(?) in WordPress.</p>
<p>What's the best way to achieve this? Thanks!</p>
| [
{
"answer_id": 283478,
"author": "Ray Gulick",
"author_id": 30,
"author_profile": "https://wordpress.stackexchange.com/users/30",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have a template tag on your listing page?</p>\n\n<p>Template tag for listing page:\nget_the_post_thumbnail( $post->ID, 'thumbnail' );</p>\n"
},
{
"answer_id": 283634,
"author": "Ray Gulick",
"author_id": 30,
"author_profile": "https://wordpress.stackexchange.com/users/30",
"pm_score": 2,
"selected": true,
"text": "<p>I think it's possible the 2 separate enabling statements may be interfering with each other. The purpose of having an array is to combine them into one enabling statement. Try the following in your functions file. </p>\n\n<p>Instead of: </p>\n\n<pre><code>add_theme_support( 'post-thumbnails' ); \nadd_theme_support( 'post-thumbnails', array( 'customposttypename' ) ); \n</code></pre>\n\n<p>This: </p>\n\n<pre><code>add_theme_support( 'post-thumbnails', array( 'post', 'customposttypename' ) );\n</code></pre>\n"
}
]
| 2017/10/16 | [
"https://wordpress.stackexchange.com/questions/283135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129742/"
]
| I'm not exactly sure of the best way to ask what I am trying to achieve, so I'm going to describe it here. If someone can identify a more succinct way to ask this, or if it's been answered in a different way, please let me know!
For example sake, I going to describe a photographer's WordPress site, where there would be a Portfolio archive page listing available taxonomies, say Nature, Landscape, and Portraits.
This Portfolio page had a grid of entries, displayed from all various Portfolio taxonomies. Above the grid, would be a navigation bar listing those taxonomies:
**All | Nature | Landscape | Portraits**
When one of the taxonomy menu options is clicked, the grid filters to the user selection using JavaScript. For example, when "Nature" is clicked, only Nature entries are shown and all others are invisible.
The Nature taxonomy would also have its own page, accessed via the slug: mysite.com/portfolio/nature - I do not want this page to exist.
I would like to be able to use that Nature URL above to go to the Portfolio archive page and have it filtered to the Nature entries by JavaScript when the page is ready.
**Essentially, I would like the URL mysite.com/portfolio/nature to act as mysite.com/portfolio/?tax=nature** - where the tax GET var would get registered in PHP (and later outputted to JavaScript) and then the parent Portfolio archive page is loaded.
I'm not looking for any help with the actual JavaScript implementation of this, I'm looking for advice for how to handle the URL rewriting(?) in WordPress.
What's the best way to achieve this? Thanks! | I think it's possible the 2 separate enabling statements may be interfering with each other. The purpose of having an array is to combine them into one enabling statement. Try the following in your functions file.
Instead of:
```
add_theme_support( 'post-thumbnails' );
add_theme_support( 'post-thumbnails', array( 'customposttypename' ) );
```
This:
```
add_theme_support( 'post-thumbnails', array( 'post', 'customposttypename' ) );
``` |
283,138 | <p>This is my code for showing categories on post meta:</p>
<pre><code>$categories_list = get_the_category_list( ', ', 'ixn' );
printf( '<span class="cat-links">' . ( 'Category: %1$s', 'ixn' ) . '</span>', $categories_list );
</code></pre>
<p>('ixn' is the theme name)</p>
<p>Is there a simple way to hide a specific category, called "site" from the categories that appear on the post meta?</p>
<p>I have read these supposed solutions, but they may be overkill for what I need and don't fit well with my code as they don't use the <code>get_the_category_list</code>:</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/questions/181182/hide-a-certain-category-name-without-removing-it">Hide a certain category name without removing it?</a></li>
<li><a href="https://rockingwplikeapro.com/hide-category-names-from-display-in-wordpress-theme/" rel="nofollow noreferrer">https://rockingwplikeapro.com/hide-category-names-from-display-in-wordpress-theme/</a></li>
<li><a href="https://www.webhostinghero.com/exclude-specific-categories-from-the-meta-info-in-wordpress/" rel="nofollow noreferrer">https://www.webhostinghero.com/exclude-specific-categories-from-the-meta-info-in-wordpress/</a></li>
</ul>
| [
{
"answer_id": 283478,
"author": "Ray Gulick",
"author_id": 30,
"author_profile": "https://wordpress.stackexchange.com/users/30",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have a template tag on your listing page?</p>\n\n<p>Template tag for listing page:\nget_the_post_thumbnail( $post->ID, 'thumbnail' );</p>\n"
},
{
"answer_id": 283634,
"author": "Ray Gulick",
"author_id": 30,
"author_profile": "https://wordpress.stackexchange.com/users/30",
"pm_score": 2,
"selected": true,
"text": "<p>I think it's possible the 2 separate enabling statements may be interfering with each other. The purpose of having an array is to combine them into one enabling statement. Try the following in your functions file. </p>\n\n<p>Instead of: </p>\n\n<pre><code>add_theme_support( 'post-thumbnails' ); \nadd_theme_support( 'post-thumbnails', array( 'customposttypename' ) ); \n</code></pre>\n\n<p>This: </p>\n\n<pre><code>add_theme_support( 'post-thumbnails', array( 'post', 'customposttypename' ) );\n</code></pre>\n"
}
]
| 2017/10/17 | [
"https://wordpress.stackexchange.com/questions/283138",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
]
| This is my code for showing categories on post meta:
```
$categories_list = get_the_category_list( ', ', 'ixn' );
printf( '<span class="cat-links">' . ( 'Category: %1$s', 'ixn' ) . '</span>', $categories_list );
```
('ixn' is the theme name)
Is there a simple way to hide a specific category, called "site" from the categories that appear on the post meta?
I have read these supposed solutions, but they may be overkill for what I need and don't fit well with my code as they don't use the `get_the_category_list`:
* [Hide a certain category name without removing it?](https://wordpress.stackexchange.com/questions/181182/hide-a-certain-category-name-without-removing-it)
* <https://rockingwplikeapro.com/hide-category-names-from-display-in-wordpress-theme/>
* <https://www.webhostinghero.com/exclude-specific-categories-from-the-meta-info-in-wordpress/> | I think it's possible the 2 separate enabling statements may be interfering with each other. The purpose of having an array is to combine them into one enabling statement. Try the following in your functions file.
Instead of:
```
add_theme_support( 'post-thumbnails' );
add_theme_support( 'post-thumbnails', array( 'customposttypename' ) );
```
This:
```
add_theme_support( 'post-thumbnails', array( 'post', 'customposttypename' ) );
``` |
283,161 | <p>How i can restrict portion of post/page content when user bought specific product?</p>
<p>for example:</p>
<pre><code> some content
...
[wcm_restrict product_id="5"]
this content only show for users that bought product 5
[/wcm_restrict]
...
some other content
</code></pre>
<p>I tried many plug-ins unfortunately doesn't have this feature.
Any help?</p>
| [
{
"answer_id": 283202,
"author": "Reza Ramezanpour",
"author_id": 129731,
"author_profile": "https://wordpress.stackexchange.com/users/129731",
"pm_score": 3,
"selected": true,
"text": "<p>Well, I answering my question.</p>\n\n<p>As @Milan Petrovic mentioned in comments, it's easy to do. just creating shortcode and check if user bought specific product.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>/**\n * [wcr_shortcode description]\n * @param array pid product id from short code\n * @return content shortcode content if user bought product\n */\nfunction wcr_shortcode($atts = [], $content = null, $tag = '')\n{\n // normalize attribute keys, lowercase\n $atts = array_change_key_case((array) $atts, CASE_LOWER);\n\n // start output\n $o = '';\n\n // start box\n $o .= '<div class=\"wcr-box\">';\n\n $current_user = wp_get_current_user();\n\n if ( current_user_can('administrator') || wc_customer_bought_product($current_user->email, $current_user->ID, $atts['pid'])) {\n // enclosing tags\n if (!is_null($content)) {\n // secure output by executing the_content filter hook on $content\n $o .= apply_filters('the_content', $content);\n }\n\n } else {\n // User doesn't bought this product and not an administator\n }\n // end box\n $o .= '</div>';\n\n // return output\n return $o;\n}\n\nadd_shortcode('wcr', 'wcr_shortcode');\n</code></pre>\n\n<p>Shortcode usage example:</p>\n\n<pre><code>[wcr pid=\"72\"]\n This content only show for users that bought product with the id #72\n[/wcr]\n</code></pre>\n\n<h2>References</h2>\n\n<ol>\n<li><a href=\"https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/\" rel=\"nofollow noreferrer\">Shortcodes with Parameters</a></li>\n</ol>\n"
},
{
"answer_id": 283203,
"author": "Jesse Vlasveld",
"author_id": 87884,
"author_profile": "https://wordpress.stackexchange.com/users/87884",
"pm_score": 0,
"selected": false,
"text": "<p>WooCommerce provides a <a href=\"https://docs.woocommerce.com/wc-apidocs/function-wc_customer_bought_product.html\" rel=\"nofollow noreferrer\">function</a> to do this.</p>\n\n<pre><code>$current_user = wp_get_current_user();\nif ( ! wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->id ) ) {\n _e( 'This content is only visible for users who bought this product.' );\n}\n</code></pre>\n"
}
]
| 2017/10/17 | [
"https://wordpress.stackexchange.com/questions/283161",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129731/"
]
| How i can restrict portion of post/page content when user bought specific product?
for example:
```
some content
...
[wcm_restrict product_id="5"]
this content only show for users that bought product 5
[/wcm_restrict]
...
some other content
```
I tried many plug-ins unfortunately doesn't have this feature.
Any help? | Well, I answering my question.
As @Milan Petrovic mentioned in comments, it's easy to do. just creating shortcode and check if user bought specific product.
Here is the code:
```
/**
* [wcr_shortcode description]
* @param array pid product id from short code
* @return content shortcode content if user bought product
*/
function wcr_shortcode($atts = [], $content = null, $tag = '')
{
// normalize attribute keys, lowercase
$atts = array_change_key_case((array) $atts, CASE_LOWER);
// start output
$o = '';
// start box
$o .= '<div class="wcr-box">';
$current_user = wp_get_current_user();
if ( current_user_can('administrator') || wc_customer_bought_product($current_user->email, $current_user->ID, $atts['pid'])) {
// enclosing tags
if (!is_null($content)) {
// secure output by executing the_content filter hook on $content
$o .= apply_filters('the_content', $content);
}
} else {
// User doesn't bought this product and not an administator
}
// end box
$o .= '</div>';
// return output
return $o;
}
add_shortcode('wcr', 'wcr_shortcode');
```
Shortcode usage example:
```
[wcr pid="72"]
This content only show for users that bought product with the id #72
[/wcr]
```
References
----------
1. [Shortcodes with Parameters](https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/) |
283,172 | <p>Programmatically, I want to activate / deactivate a plugin of this specific blog/site in a WordPress Multisite. Any help will be gladly appreciated, thank you!</p>
| [
{
"answer_id": 283182,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": true,
"text": "<p>Use a combination of <code>switch_to_blog()</code>, <code>activate_plugins()</code>, and <code>deactivate_plugins()</code>.</p>\n\n<p>You can put this in functions.php, but you'll want to remove it once it runs:</p>\n\n<pre><code>// hook to admin init\nadd_action('admin_init', 'wpse_swap_plugins');\nfunction wpse_swap_plugins() {\n // set blog ID per your needs\n $blog_id = 3;\n // switch to the site where you want to activate/deactivate plugins\n switch_to_blog($blog_id);\n // activate: set your path, don't set redirect,\n // don't make this network wide, don't prevent activation hooks\n activate_plugins(array(\n '/full/path/to/plugin/you/want/to/activate.php'\n ), '', false, false);\n // deactivate: same arguments as activate\n deactivate_plugins(array(\n '/full/path/to/plugin/to/deactivate.php'\n ), '', false, false);\n // switch context back to original site\n restore_current_blog();\n}\n</code></pre>\n\n<p>Credit to related answer: <a href=\"https://wordpress.stackexchange.com/questions/159085/deactivate-plugin-for-a-specific-user-group\">Deactivate plugin for a specific user group</a></p>\n"
},
{
"answer_id": 283192,
"author": "Yves",
"author_id": 106934,
"author_profile": "https://wordpress.stackexchange.com/users/106934",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Via WP-CLI</strong></p>\n\n<p>Reference: <a href=\"https://developer.wordpress.org/cli/commands/plugin/activate/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/plugin/activate/</a></p>\n\n<p><strong>Syntax:</strong></p>\n\n<pre><code>wp plugin activate <plugin(s)> --url=<url>\n</code></pre>\n\n<hr>\n\n<p><strong>Example:</strong></p>\n\n<ol>\n<li><code>wp plugin activate akismet --url=\"foo.example.com\"</code></li>\n<li><code>wp plugin activate akismet jetpack ninja-forms --url=\"bar.example.com\"</code></li>\n</ol>\n"
}
]
| 2017/10/17 | [
"https://wordpress.stackexchange.com/questions/283172",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106934/"
]
| Programmatically, I want to activate / deactivate a plugin of this specific blog/site in a WordPress Multisite. Any help will be gladly appreciated, thank you! | Use a combination of `switch_to_blog()`, `activate_plugins()`, and `deactivate_plugins()`.
You can put this in functions.php, but you'll want to remove it once it runs:
```
// hook to admin init
add_action('admin_init', 'wpse_swap_plugins');
function wpse_swap_plugins() {
// set blog ID per your needs
$blog_id = 3;
// switch to the site where you want to activate/deactivate plugins
switch_to_blog($blog_id);
// activate: set your path, don't set redirect,
// don't make this network wide, don't prevent activation hooks
activate_plugins(array(
'/full/path/to/plugin/you/want/to/activate.php'
), '', false, false);
// deactivate: same arguments as activate
deactivate_plugins(array(
'/full/path/to/plugin/to/deactivate.php'
), '', false, false);
// switch context back to original site
restore_current_blog();
}
```
Credit to related answer: [Deactivate plugin for a specific user group](https://wordpress.stackexchange.com/questions/159085/deactivate-plugin-for-a-specific-user-group) |
283,227 | <p>I'm not sure if im going about this the right way or not, seems to be alot of people doing this, but with completely different ways of doing it from queries in templates to functions so im not sure which route to go down. </p>
<p>I have a custom post type (business) which has featured posts, Each of these posts have a "featured_listing" post_meta which is either EMPTY or "featured-listing" value** attached to the post. I'd like to display the posts which do not have an empty post_meta value above all other posts in search results and categories. </p>
<p>**Note the - rather than _ for the value.</p>
<p>This is what I thought might work, but I'm starting to think I'm barking up the wrong tree. </p>
<pre><code>// Order posts by meta data
function custom_special_sort( $query ) {
//is this the main query and is this post type of post
if ( $query->is_main_query() && $query->is_post_type( 'business' ) ) {
//Do a meta query
$query->get_post_meta(get_the_ID(), "featured_listing", TRUE);
//sort by a meta value
$query->set( 'orderby', 'featured_listing' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'custom_special_sort' );
</code></pre>
<p>I've also just tried to do it slightly differently, below. But could do with some guidance as to why its not working or if im even doing it correctly: </p>
<pre><code> function custom_special_sort( $query ) {
// Check this is main query and other conditionals as needed
if ( $query->is_main_query() && $query->is_post_type( 'business' ) ) {
$query->set(
'meta_query',
array(
array(
'key' => 'featured_listing',
'value' => 'featured-listing',
'orderby' => 'featured_listing',
'order' => 'DESC'
)
)
);
}
}
add_action( 'pre_get_posts' , 'custom_special_sort' );
</code></pre>
| [
{
"answer_id": 283266,
"author": "FluffyKitten",
"author_id": 63360,
"author_profile": "https://wordpress.stackexchange.com/users/63360",
"pm_score": 2,
"selected": true,
"text": "<p>You have a couple of issues with the code you are trying. </p>\n\n<p><strong>To check the query is for your CPT archive</strong>: You are using <code>$query->is_post_type()</code> but it doesn't work (as far as I know, its not even a function). Instead you can use either:</p>\n\n<pre><code>if (is_post_type_archive('business')) {...}\n</code></pre>\n\n<p><em>or</em> (if its not only on the archive page)</p>\n\n<pre><code>if ($query->get('post_type') == 'business') {...}\n</code></pre>\n\n<p><strong>To order by meta value in pre_get_posts</strong>, you need to set the <code>meta_key</code> as well as the <code>orderby</code> (and optionally <code>order</code>).</p>\n\n<p><br><strong>Complete Function:</strong> Applying these to your \"custom_special_sort\" function, we get:</p>\n\n<pre><code>function custom_special_sort( $query ) {\n\n // if is this the main query and is this post type of business\n if ( $query->is_main_query() && is_post_type_archive( 'business' ) ) {\n\n // order results by the meta_key 'featured_listing'\n $query->set( 'meta_key', 'featured_listing' );\n $query->set( 'orderby', 'featured_listing' );\n $query->set( 'order', 'DESC' );\n }\n}\nadd_action( 'pre_get_posts', 'custom_special_sort' );\n</code></pre>\n"
},
{
"answer_id": 283286,
"author": "Randomer11",
"author_id": 62291,
"author_profile": "https://wordpress.stackexchange.com/users/62291",
"pm_score": 0,
"selected": false,
"text": "<p>I have marked Fluffykittens answer above as the correct answer. I wanted to extend the answer ( Hopefully it will help someone else ).</p>\n\n<p>With the answer provided by Fluffykitten I found that with my particular theme, I'm using different loop for archives and custom taxonomy which resulted in the re-ordering of posts working on my search archives where <code>is_post_type_archive</code> was true. However my taxonomy archives the reordering wasnt happening, so changing the query to include <code>is_tax</code> made it work.</p>\n\n<p>Not sure if its the best way of adding to the query as im a php novice, but it works. Someone is welcome to correct/improve :)</p>\n\n<pre><code>function custom_special_sort( $query ) {\n\n // if is this the main query and is this post type of business\n\n if ( ($query->is_main_query() && is_post_type_archive('business')) || (is_main_query() && is_tax ('location')) ) {\n\n // order results by the meta_key 'featured_listing'\n $query->set( 'meta_key', 'featured_listing' );\n $query->set( 'orderby', 'featured_listing' );\n $query->set( 'order', 'DESC' );\n }\n}\nadd_action( 'pre_get_posts', 'custom_special_sort' );\n</code></pre>\n"
}
]
| 2017/10/17 | [
"https://wordpress.stackexchange.com/questions/283227",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62291/"
]
| I'm not sure if im going about this the right way or not, seems to be alot of people doing this, but with completely different ways of doing it from queries in templates to functions so im not sure which route to go down.
I have a custom post type (business) which has featured posts, Each of these posts have a "featured\_listing" post\_meta which is either EMPTY or "featured-listing" value\*\* attached to the post. I'd like to display the posts which do not have an empty post\_meta value above all other posts in search results and categories.
\*\*Note the - rather than \_ for the value.
This is what I thought might work, but I'm starting to think I'm barking up the wrong tree.
```
// Order posts by meta data
function custom_special_sort( $query ) {
//is this the main query and is this post type of post
if ( $query->is_main_query() && $query->is_post_type( 'business' ) ) {
//Do a meta query
$query->get_post_meta(get_the_ID(), "featured_listing", TRUE);
//sort by a meta value
$query->set( 'orderby', 'featured_listing' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'custom_special_sort' );
```
I've also just tried to do it slightly differently, below. But could do with some guidance as to why its not working or if im even doing it correctly:
```
function custom_special_sort( $query ) {
// Check this is main query and other conditionals as needed
if ( $query->is_main_query() && $query->is_post_type( 'business' ) ) {
$query->set(
'meta_query',
array(
array(
'key' => 'featured_listing',
'value' => 'featured-listing',
'orderby' => 'featured_listing',
'order' => 'DESC'
)
)
);
}
}
add_action( 'pre_get_posts' , 'custom_special_sort' );
``` | You have a couple of issues with the code you are trying.
**To check the query is for your CPT archive**: You are using `$query->is_post_type()` but it doesn't work (as far as I know, its not even a function). Instead you can use either:
```
if (is_post_type_archive('business')) {...}
```
*or* (if its not only on the archive page)
```
if ($query->get('post_type') == 'business') {...}
```
**To order by meta value in pre\_get\_posts**, you need to set the `meta_key` as well as the `orderby` (and optionally `order`).
**Complete Function:** Applying these to your "custom\_special\_sort" function, we get:
```
function custom_special_sort( $query ) {
// if is this the main query and is this post type of business
if ( $query->is_main_query() && is_post_type_archive( 'business' ) ) {
// order results by the meta_key 'featured_listing'
$query->set( 'meta_key', 'featured_listing' );
$query->set( 'orderby', 'featured_listing' );
$query->set( 'order', 'DESC' );
}
}
add_action( 'pre_get_posts', 'custom_special_sort' );
``` |
283,228 | <p>I try to query custom post type called <code>news</code> by a category called <code>Alumni</code> with <code>ID=160</code>.</p>
<p>When I use such arguments, as a result, I get all my custom posts <strong>without</strong> <code>Alumni</code> category:</p>
<pre><code>$args = array(
'posts_per_page' => -1,
'post_type' => 'news',
'orderby' => 'date',
'order' => 'DESC',
'category__not_in' => 160
);
$loop = new WP_Query( $args );
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
...
<?php endwhile; ?>
</code></pre>
<p>However, changing <code>category__not_in</code> to <code>category__in</code> gives an empty list but I would expect the opposite of the initial result. I can't really understand where I make a mistake. </p>
<p>Also, I tried using <code>cat</code> and <code>category_name</code> instead and I played around with different categories but results were always the same.</p>
<p>In my research I came across <code>'tax_query'</code> but I can't get it to work as well. The documentation is not quite clear for me.</p>
| [
{
"answer_id": 283230,
"author": "Randomer11",
"author_id": 62291,
"author_profile": "https://wordpress.stackexchange.com/users/62291",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using something like this in the array, Had a similar problem earlier which this solved. </p>\n\n<pre><code>'taxonomy' => 'your_taxonomy_name',\n</code></pre>\n\n<p>Or something like : </p>\n\n<pre><code> 'tax_query' => array(\n 'taxonomy' => 'your_taxonomy_name',\n 'terms' => 'Alumni',\n 'field' => 'slug',\n 'include_children' => true,\n),\n</code></pre>\n"
},
{
"answer_id": 283242,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 2,
"selected": false,
"text": "<p>Are these custom taxonomies or the regular categories?</p>\n\n<p>if they are just categories you should use:</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'news',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'category_name' => 'Alumni'\n);\n$loop = new WP_Query( $args );\n\n<?php while ( $loop->have_posts() ) : $loop->the_post();?>\n...\n<?php endwhile; ?>\n</code></pre>\n\n<p>if you want to use it by id</p>\n\n<p>use:</p>\n\n<pre><code>'cat' => 160 \n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>'category_name' => 'Alumni'\n</code></pre>\n"
},
{
"answer_id": 283254,
"author": "HeroWeb512",
"author_id": 102280,
"author_profile": "https://wordpress.stackexchange.com/users/102280",
"pm_score": 0,
"selected": false,
"text": "<h1>To get custom post type posts with specific category use custom taxonomy</h1>\n\n<p>Register the taxonomy name of the custom post type like categories and then assign a category to each post when you added new post.\nHere is the example of the code</p>\n\n<pre><code> add_action( 'init', 'news_my_taxonomy');\n function news_my_taxonomy(){\n // custom post type taxonomies\n $labels = array(\n 'name' => 'Categories',\n 'singular_name' => 'Category',\n 'add_new' => 'Add Category',\n 'add_new_item' => 'Add New Category',\n 'all_items' => 'All Categories',\n 'edit_item' => 'Edit Item',\n 'new_item' => 'New Item',\n 'view_item' => 'View Item',\n 'update_item' => 'Update Category',\n 'search_items' => 'Search Categories',\n 'not_found' => 'No record found',\n 'not_found_in_trash' => 'No items found in trash',\n 'parent_item_colon' => 'Parent Item',\n 'menu_name' => 'Categories'\n );\n $args = array(\n 'labels' => $labels,\n 'hierarchical' => true,\n 'has_archive' => true,\n 'rewrite' => array('slug' => 'news_category'),\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'query_var' => true,\n );\n register_taxonomy('news_category', array('news'), $args);\n}\n</code></pre>\n\n<h1>then</h1>\n\n<h1>create taxonomy template page 'taxonomy-news_category.php'</h1>\n\n<p>and add the query to get the posts with this category name</p>\n\n<pre><code> $cat_name = single_cat_title;\n $args = array( 'category_name' => $cat_name, 'posts_per_page' => 12, 'order'=> 'ASC', 'post_type' => 'news', 'paged' => $paged);\n</code></pre>\n\n<p>All the work is done.Good luck</p>\n"
}
]
| 2017/10/17 | [
"https://wordpress.stackexchange.com/questions/283228",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116478/"
]
| I try to query custom post type called `news` by a category called `Alumni` with `ID=160`.
When I use such arguments, as a result, I get all my custom posts **without** `Alumni` category:
```
$args = array(
'posts_per_page' => -1,
'post_type' => 'news',
'orderby' => 'date',
'order' => 'DESC',
'category__not_in' => 160
);
$loop = new WP_Query( $args );
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
...
<?php endwhile; ?>
```
However, changing `category__not_in` to `category__in` gives an empty list but I would expect the opposite of the initial result. I can't really understand where I make a mistake.
Also, I tried using `cat` and `category_name` instead and I played around with different categories but results were always the same.
In my research I came across `'tax_query'` but I can't get it to work as well. The documentation is not quite clear for me. | Are these custom taxonomies or the regular categories?
if they are just categories you should use:
```
$args = array(
'posts_per_page' => -1,
'post_type' => 'news',
'orderby' => 'date',
'order' => 'DESC',
'category_name' => 'Alumni'
);
$loop = new WP_Query( $args );
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
...
<?php endwhile; ?>
```
if you want to use it by id
use:
```
'cat' => 160
```
instead of
```
'category_name' => 'Alumni'
``` |
283,239 | <p>I need the site footer to sit across the bottom of the site at all times.</p>
<p>Currently, it sits across the site bottom when there is content on the page, but with no content on the page it (.site-footer) rises from the bottom to the middle of the visible page as represented in this image:</p>
<p><kbd>
<a href="https://i.stack.imgur.com/wPOMD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wPOMD.png" alt="Footer in the middle of the screen"></a>
</kbd></p>
<p>I was able to answer my own question and posted discovery process below:</p>
| [
{
"answer_id": 283240,
"author": "Kelly",
"author_id": 94686,
"author_profile": "https://wordpress.stackexchange.com/users/94686",
"pm_score": 4,
"selected": true,
"text": "<p>A quick search shows this question has been asked and answered many times.</p>\n\n<p>From StackOverflow: <a href=\"https://stackoverflow.com/questions/3443606/make-footer-stick-to-bottom-of-page-correctly\">Make footer stick to bottom of page correctly</a></p>\n\n<p>From StackOverflow: <a href=\"https://stackoverflow.com/questions/42294/how-do-you-get-the-footer-to-stay-at-the-bottom-of-a-web-page\">How to get the footer to stick to the bottom of your web page.</a></p>\n\n<p>From CSS-Tricks: <a href=\"https://css-tricks.com/couple-takes-sticky-footer/\" rel=\"noreferrer\">5 different ways to make a sticky footer</a></p>\n\n<p>From Code Pen: <a href=\"https://codepen.io/cbracco/pen/zekgx\" rel=\"noreferrer\">\"Always on the bottom\" Footer</a> </p>\n\n<p>From WordPress: <a href=\"https://wordpress.org/support/topic/how-to-make-footer-fixed-to-the-bottom-of-the-screen/\" rel=\"noreferrer\">How to make footer fixed to the bottom of the screen?</a> </p>\n\n<p><strong>I used the WordPress answer for my answer:</strong></p>\n\n<pre><code>.site-footer{\n position: fixed;\n bottom: 0;\n left: 0;\n right: 0; \n}\n</code></pre>\n\n<p><kbd>\n<a href=\"https://i.stack.imgur.com/0JbmQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0JbmQ.png\" alt=\"Footer properly stuck to site floor.\"></a>\n</kbd></p>\n"
},
{
"answer_id": 283251,
"author": "HeroWeb512",
"author_id": 102280,
"author_profile": "https://wordpress.stackexchange.com/users/102280",
"pm_score": 2,
"selected": false,
"text": "<p>Add CSS for your footer, it will fix the position of footer to the bottom of the page.</p>\n\n<pre><code> .site-footer{\n position:fixed;\n bottom:0px;\n left:0px;\n right:0px;\n width:100%;\n }\n</code></pre>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283239",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94686/"
]
| I need the site footer to sit across the bottom of the site at all times.
Currently, it sits across the site bottom when there is content on the page, but with no content on the page it (.site-footer) rises from the bottom to the middle of the visible page as represented in this image:
`[](https://i.stack.imgur.com/wPOMD.png)`
I was able to answer my own question and posted discovery process below: | A quick search shows this question has been asked and answered many times.
From StackOverflow: [Make footer stick to bottom of page correctly](https://stackoverflow.com/questions/3443606/make-footer-stick-to-bottom-of-page-correctly)
From StackOverflow: [How to get the footer to stick to the bottom of your web page.](https://stackoverflow.com/questions/42294/how-do-you-get-the-footer-to-stay-at-the-bottom-of-a-web-page)
From CSS-Tricks: [5 different ways to make a sticky footer](https://css-tricks.com/couple-takes-sticky-footer/)
From Code Pen: ["Always on the bottom" Footer](https://codepen.io/cbracco/pen/zekgx)
From WordPress: [How to make footer fixed to the bottom of the screen?](https://wordpress.org/support/topic/how-to-make-footer-fixed-to-the-bottom-of-the-screen/)
**I used the WordPress answer for my answer:**
```
.site-footer{
position: fixed;
bottom: 0;
left: 0;
right: 0;
}
```
`[](https://i.stack.imgur.com/0JbmQ.png)` |
283,256 | <p>I've built my own custom 'recent posts' widget to display some more content than the default core WP recent posts widget does. I'm struggling with controlling my list of entries. Currently, the widget always returns 1 additional post to the list selected. So if I select 1 post to show, it will actually show 2, and so forth. I'm not really sure where my code is going wrong:</p>
<pre><code>// Run query to build posts listing
public function getPostsListings($numberOfListings,$showExcerpt,$showDate,$showFeatImage,$post_excerpt_length)
{
$post_listings = new WP_Query();
$post_listings->query('posts_per_page=' . $numberOfListings, 'ignore_sticky_posts' => 1);
if ($post_listings->found_posts > 0) {
echo '<ul class="posts_widget">';
while ($post_listings->have_posts()) {
$post_listings->the_post();
$listItem = '<li>';
if ( !empty($showFeatImage) && has_post_thumbnail() ) {
$listItem .= '<img src="'. get_the_post_thumbnail_url(get_the_ID(),'thumbnail') .'" />';
}
$listItem .= '<a href="' . get_permalink() . '">';
$listItem .= get_the_title() . '</a>';
if (!empty($showDate)) {
$listItem .= '<span class="post-date"> Posted: ' . get_the_date() . '</span>';
}
if (!empty($showExcerpt)) {
$listItem .= '<span class="post-excerpt">' .wp_trim_words( get_the_excerpt(), $post_excerpt_length). '</span>';
}
$listItem .= '</li>';
echo $listItem;
}
echo '</ul>';
wp_reset_postdata();
} else {
echo '<p>No posts were found</p>';
}
}
</code></pre>
<p>Obviously there is more code to the widget than that, but I'm sparing it for the sake of brevity as I'm fairly sure my while loop is the core issue.</p>
| [
{
"answer_id": 283285,
"author": "Anson W Han",
"author_id": 129547,
"author_profile": "https://wordpress.stackexchange.com/users/129547",
"pm_score": 1,
"selected": false,
"text": "<p>Anytime you call WP_Query, be sure to filter for only published posts. \nAlso as a general guide, for any custom queries that you expect or could have more than one result for, try to always pass arguments for:</p>\n\n<ol>\n<li>Publish status</li>\n<li>Limit / number of results</li>\n<li>Field to sort by</li>\n<li>Sort order</li>\n</ol>\n\n<p>Refer to the codex page (<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a>) for a full list of arguments you can pass. </p>\n"
},
{
"answer_id": 283370,
"author": "Ryan Coolwebs",
"author_id": 105819,
"author_profile": "https://wordpress.stackexchange.com/users/105819",
"pm_score": 0,
"selected": false,
"text": "<p>As @jacob and @Sneha mentioned earlier in comments - my issue was with sticky posts not counting towards 'posts_per_page. My updated code is below:</p>\n\n<pre><code>// Run query to build posts listing\npublic function getPostsListings($numberOfListings,$showExcerpt,$showDate,$showFeatImage,$post_excerpt_length)\n{\n global $post;\n $args = array( 'numberposts' => $numberOfListings, 'ignore_sticky_posts' => 1);\n $recent_posts = get_posts( $args );\n if ( have_posts() ) {\n echo '<ul class=\"posts_widget\">';\n foreach( $recent_posts as $post ) : setup_postdata($post);\n setup_postdata($post);\n $listItem = '<li>';\n if ( !empty($showFeatImage) && has_post_thumbnail() ) {\n $listItem .= '<img src=\"'. get_the_post_thumbnail_url(get_the_ID(),'thumbnail') .'\" />';\n }\n $listItem .= '<a href=\"' . get_permalink() . '\">';\n $listItem .= get_the_title() . '</a>';\n if (!empty($showDate)) {\n $listItem .= '<span class=\"post-date\"> Posted: ' . get_the_date() . '</span>';\n }\n if (!empty($showExcerpt)) {\n $listItem .= '<span class=\"post-excerpt\">' .wp_trim_words( get_the_excerpt(), $post_excerpt_length). '</span>';\n }\n $listItem .= '</li>';\n echo $listItem;\n endforeach;\n echo '</ul>';\n wp_reset_postdata();\n } else {\n echo '<p>No posts were found</p>';\n }\n}\n</code></pre>\n\n<p>I did manage to solve it another alternative way by re appropriating code examples from here: <a href=\"https://themefuse.com/how-to-create-a-recent-posts-wordpress-plugin/\" rel=\"nofollow noreferrer\">https://themefuse.com/how-to-create-a-recent-posts-wordpress-plugin/</a></p>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105819/"
]
| I've built my own custom 'recent posts' widget to display some more content than the default core WP recent posts widget does. I'm struggling with controlling my list of entries. Currently, the widget always returns 1 additional post to the list selected. So if I select 1 post to show, it will actually show 2, and so forth. I'm not really sure where my code is going wrong:
```
// Run query to build posts listing
public function getPostsListings($numberOfListings,$showExcerpt,$showDate,$showFeatImage,$post_excerpt_length)
{
$post_listings = new WP_Query();
$post_listings->query('posts_per_page=' . $numberOfListings, 'ignore_sticky_posts' => 1);
if ($post_listings->found_posts > 0) {
echo '<ul class="posts_widget">';
while ($post_listings->have_posts()) {
$post_listings->the_post();
$listItem = '<li>';
if ( !empty($showFeatImage) && has_post_thumbnail() ) {
$listItem .= '<img src="'. get_the_post_thumbnail_url(get_the_ID(),'thumbnail') .'" />';
}
$listItem .= '<a href="' . get_permalink() . '">';
$listItem .= get_the_title() . '</a>';
if (!empty($showDate)) {
$listItem .= '<span class="post-date"> Posted: ' . get_the_date() . '</span>';
}
if (!empty($showExcerpt)) {
$listItem .= '<span class="post-excerpt">' .wp_trim_words( get_the_excerpt(), $post_excerpt_length). '</span>';
}
$listItem .= '</li>';
echo $listItem;
}
echo '</ul>';
wp_reset_postdata();
} else {
echo '<p>No posts were found</p>';
}
}
```
Obviously there is more code to the widget than that, but I'm sparing it for the sake of brevity as I'm fairly sure my while loop is the core issue. | Anytime you call WP\_Query, be sure to filter for only published posts.
Also as a general guide, for any custom queries that you expect or could have more than one result for, try to always pass arguments for:
1. Publish status
2. Limit / number of results
3. Field to sort by
4. Sort order
Refer to the codex page (<https://codex.wordpress.org/Class_Reference/WP_Query>) for a full list of arguments you can pass. |
283,291 | <pre><code>wp_enqueue_style( 'style', THEMEROOT . '/css/style.css' );
wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css' );
</code></pre>
<p>I am using the above method to enqueue stylesheet, but what I want is not achieved.</p>
<p>Whatever I write in <code>responsive.css</code> should be prioritized(that means CSS written here should override everything else written in style.css.), but that is not happening. Is there a way to achieve it through something that WordPress provide?</p>
<h1>Update →</h1>
<p>the whole idea is not to use <code>!important</code>, but still when the website is loaded in smaller screens than responsive.css should dominate or override style.css without using any <code>!important</code> tag.</p>
| [
{
"answer_id": 283292,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to make sure the second stylesheet loads after the first, you can use the third argument of <code>wp_enqueue_style</code> to set a dependency, eg:</p>\n\n<pre><code>wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css', array() );\nwp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css', array('styles') );\n</code></pre>\n\n<p>As for having <strong>all</strong> the styles in <em>responsive.css</em> override <em>style.css</em>, that is going to entirely depend on the specificity of the targeting in each stylesheet, CSS being a Cascading Style Sheet, it would be worth researching exactly what that means if you aren't fully sure how it works.</p>\n"
},
{
"answer_id": 283293,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 2,
"selected": false,
"text": "<p>Generally, what is loaded later will take prevalence if both are similar in their specificity, e.g. <code>body { background-color: white; } body { background-color: black; }</code> will lead to a black background-color, while <code>body.myclass { background-color: white; } body { background-color: black; }</code> will result in a white background if body has the class myclass.</p>\n\n<p>You can use three ways: load the overriding styles later, make them more specific or add !important after the attributes that you want to override, e.g.</p>\n\n<pre><code>body {\n background-color: white !important;\n}\nbody.myclass {\n background-color: black;\n}\n</code></pre>\n\n<p>will get you a white background. You can easily find out which one is loaded first by looking at your document source. If that is in the right order (if it isn't, tell WP that your responsive.css requires the original css and WP will make sure it's in the right order), make sure that your overriding styles are at least as specific as your original styles. If that is the case as well, make sure that your original style doesn't use <code>!important</code> for the attributes you want to override.</p>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283291",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
]
| ```
wp_enqueue_style( 'style', THEMEROOT . '/css/style.css' );
wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css' );
```
I am using the above method to enqueue stylesheet, but what I want is not achieved.
Whatever I write in `responsive.css` should be prioritized(that means CSS written here should override everything else written in style.css.), but that is not happening. Is there a way to achieve it through something that WordPress provide?
Update →
========
the whole idea is not to use `!important`, but still when the website is loaded in smaller screens than responsive.css should dominate or override style.css without using any `!important` tag. | If you want to make sure the second stylesheet loads after the first, you can use the third argument of `wp_enqueue_style` to set a dependency, eg:
```
wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css', array() );
wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css', array('styles') );
```
As for having **all** the styles in *responsive.css* override *style.css*, that is going to entirely depend on the specificity of the targeting in each stylesheet, CSS being a Cascading Style Sheet, it would be worth researching exactly what that means if you aren't fully sure how it works. |
283,294 | <p>I create a custom field to a image gallery called <strong>views</strong></p>
<p><a href="https://i.stack.imgur.com/hGeTJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hGeTJ.jpg" alt="enter image description here"></a></p>
<p>My problem is how can I retrieve the field in my template gallery? See img, I'd like to display <strong>views</strong> below caption where the red arrow is pointing.</p>
<p><a href="https://i.stack.imgur.com/Vt1Hl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vt1Hl.jpg" alt="enter image description here"></a></p>
<p>Any suggestions?</p>
| [
{
"answer_id": 283292,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to make sure the second stylesheet loads after the first, you can use the third argument of <code>wp_enqueue_style</code> to set a dependency, eg:</p>\n\n<pre><code>wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css', array() );\nwp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css', array('styles') );\n</code></pre>\n\n<p>As for having <strong>all</strong> the styles in <em>responsive.css</em> override <em>style.css</em>, that is going to entirely depend on the specificity of the targeting in each stylesheet, CSS being a Cascading Style Sheet, it would be worth researching exactly what that means if you aren't fully sure how it works.</p>\n"
},
{
"answer_id": 283293,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 2,
"selected": false,
"text": "<p>Generally, what is loaded later will take prevalence if both are similar in their specificity, e.g. <code>body { background-color: white; } body { background-color: black; }</code> will lead to a black background-color, while <code>body.myclass { background-color: white; } body { background-color: black; }</code> will result in a white background if body has the class myclass.</p>\n\n<p>You can use three ways: load the overriding styles later, make them more specific or add !important after the attributes that you want to override, e.g.</p>\n\n<pre><code>body {\n background-color: white !important;\n}\nbody.myclass {\n background-color: black;\n}\n</code></pre>\n\n<p>will get you a white background. You can easily find out which one is loaded first by looking at your document source. If that is in the right order (if it isn't, tell WP that your responsive.css requires the original css and WP will make sure it's in the right order), make sure that your overriding styles are at least as specific as your original styles. If that is the case as well, make sure that your original style doesn't use <code>!important</code> for the attributes you want to override.</p>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283294",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129841/"
]
| I create a custom field to a image gallery called **views**
[](https://i.stack.imgur.com/hGeTJ.jpg)
My problem is how can I retrieve the field in my template gallery? See img, I'd like to display **views** below caption where the red arrow is pointing.
[](https://i.stack.imgur.com/Vt1Hl.jpg)
Any suggestions? | If you want to make sure the second stylesheet loads after the first, you can use the third argument of `wp_enqueue_style` to set a dependency, eg:
```
wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css', array() );
wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css', array('styles') );
```
As for having **all** the styles in *responsive.css* override *style.css*, that is going to entirely depend on the specificity of the targeting in each stylesheet, CSS being a Cascading Style Sheet, it would be worth researching exactly what that means if you aren't fully sure how it works. |
283,309 | <p>i have a little big problem with meta queries.
I Designed a query to retrieve posts where any of these words exists in the custom field pickup_address. the field has this string in its meta value: 43 Longview Drive, Papamoa</p>
<p><strong>EDIT</strong></p>
<p>this is the meta query that Im using:</p>
<pre><code>$args = array(
'post_type' => 'posts',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'pickup_address',
'value' => 'Papamoa',
'compare' => 'LIKE',
),
array(
'key' => 'pickup_address',
'value' => 'Bah�a',
'compare' => 'LIKE',
),
array(
'key' => 'pickup_address',
'value' => 'de',
'compare' => 'LIKE',
),
array(
'key' => 'pickup_address',
'value' => 'Plenty',
'compare' => 'LIKE',
),
),
</code></pre>
<p>);</p>
<p>this is the code I generate from the meta queries:</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS wpiw_posts.ID FROM wpiw_posts INNER JOIN
wpiw_postmeta ON ( wpiw_posts.ID = wpiw_postmeta.post_id ) WHERE 1=1
AND ( (
( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Papamoa%' ) OR
( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Bah�a%' ) OR
( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%de%' ) OR
( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Plenty%' ) ) )
AND wpiw_posts.post_type = 'project' AND ((wpiw_posts.post_status = 'publish')) GROUP BY wpiw_posts.ID ORDER BY wpiw_posts.post_date DESC LIMIT 0, 10
</code></pre>
<p>I tried to replace the special character � but doesn't work either</p>
<p>Wordpress give me nothing on the Wp_Query($query_args) but if I run this in MySql it Works. Any help qould be appreciated</p>
<p><strong>EDIT 2</strong></p>
<p>I capture the query that Wordpress executes to MySql after converting the meta_query arguments:</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS wpiw_posts.ID FROM wpiw_posts
INNER JOIN wpiw_postmeta ON ( wpiw_posts.ID = wpiw_postmeta.post_id )
INNER JOIN wpiw_postmeta AS mt1 ON ( wpiw_posts.ID = mt1.post_id )
WHERE 1=1 AND
( ( ( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Papamoa%' )
OR ( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%BahÃa%' )
OR ( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%de%' )
OR ( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Plenty%' ) )
AND ( mt1.meta_key = 'deliver_address' AND mt1.meta_value LIKE '%Auckland%' ) )
AND wpiw_posts.post_type = 'project' AND ((wpiw_posts.post_status = 'publish')) GROUP BY wpiw_posts.ID ORDER BY wpiw_posts.post_date DESC LIMIT 0, 10
</code></pre>
<p>I notice the weird chacarters 'BahÃa', but when i take this query and run it on MySql, it works! retrieves 1 row because one post have a pickup_address field with the word Papamoa and have a deliver_address field with the work Auckland.</p>
| [
{
"answer_id": 283292,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to make sure the second stylesheet loads after the first, you can use the third argument of <code>wp_enqueue_style</code> to set a dependency, eg:</p>\n\n<pre><code>wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css', array() );\nwp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css', array('styles') );\n</code></pre>\n\n<p>As for having <strong>all</strong> the styles in <em>responsive.css</em> override <em>style.css</em>, that is going to entirely depend on the specificity of the targeting in each stylesheet, CSS being a Cascading Style Sheet, it would be worth researching exactly what that means if you aren't fully sure how it works.</p>\n"
},
{
"answer_id": 283293,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 2,
"selected": false,
"text": "<p>Generally, what is loaded later will take prevalence if both are similar in their specificity, e.g. <code>body { background-color: white; } body { background-color: black; }</code> will lead to a black background-color, while <code>body.myclass { background-color: white; } body { background-color: black; }</code> will result in a white background if body has the class myclass.</p>\n\n<p>You can use three ways: load the overriding styles later, make them more specific or add !important after the attributes that you want to override, e.g.</p>\n\n<pre><code>body {\n background-color: white !important;\n}\nbody.myclass {\n background-color: black;\n}\n</code></pre>\n\n<p>will get you a white background. You can easily find out which one is loaded first by looking at your document source. If that is in the right order (if it isn't, tell WP that your responsive.css requires the original css and WP will make sure it's in the right order), make sure that your overriding styles are at least as specific as your original styles. If that is the case as well, make sure that your original style doesn't use <code>!important</code> for the attributes you want to override.</p>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283309",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129847/"
]
| i have a little big problem with meta queries.
I Designed a query to retrieve posts where any of these words exists in the custom field pickup\_address. the field has this string in its meta value: 43 Longview Drive, Papamoa
**EDIT**
this is the meta query that Im using:
```
$args = array(
'post_type' => 'posts',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'pickup_address',
'value' => 'Papamoa',
'compare' => 'LIKE',
),
array(
'key' => 'pickup_address',
'value' => 'Bah�a',
'compare' => 'LIKE',
),
array(
'key' => 'pickup_address',
'value' => 'de',
'compare' => 'LIKE',
),
array(
'key' => 'pickup_address',
'value' => 'Plenty',
'compare' => 'LIKE',
),
),
```
);
this is the code I generate from the meta queries:
```
SELECT SQL_CALC_FOUND_ROWS wpiw_posts.ID FROM wpiw_posts INNER JOIN
wpiw_postmeta ON ( wpiw_posts.ID = wpiw_postmeta.post_id ) WHERE 1=1
AND ( (
( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Papamoa%' ) OR
( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Bah�a%' ) OR
( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%de%' ) OR
( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Plenty%' ) ) )
AND wpiw_posts.post_type = 'project' AND ((wpiw_posts.post_status = 'publish')) GROUP BY wpiw_posts.ID ORDER BY wpiw_posts.post_date DESC LIMIT 0, 10
```
I tried to replace the special character � but doesn't work either
Wordpress give me nothing on the Wp\_Query($query\_args) but if I run this in MySql it Works. Any help qould be appreciated
**EDIT 2**
I capture the query that Wordpress executes to MySql after converting the meta\_query arguments:
```
SELECT SQL_CALC_FOUND_ROWS wpiw_posts.ID FROM wpiw_posts
INNER JOIN wpiw_postmeta ON ( wpiw_posts.ID = wpiw_postmeta.post_id )
INNER JOIN wpiw_postmeta AS mt1 ON ( wpiw_posts.ID = mt1.post_id )
WHERE 1=1 AND
( ( ( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Papamoa%' )
OR ( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%BahÃa%' )
OR ( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%de%' )
OR ( wpiw_postmeta.meta_key = 'pickup_address' AND wpiw_postmeta.meta_value LIKE '%Plenty%' ) )
AND ( mt1.meta_key = 'deliver_address' AND mt1.meta_value LIKE '%Auckland%' ) )
AND wpiw_posts.post_type = 'project' AND ((wpiw_posts.post_status = 'publish')) GROUP BY wpiw_posts.ID ORDER BY wpiw_posts.post_date DESC LIMIT 0, 10
```
I notice the weird chacarters 'BahÃa', but when i take this query and run it on MySql, it works! retrieves 1 row because one post have a pickup\_address field with the word Papamoa and have a deliver\_address field with the work Auckland. | If you want to make sure the second stylesheet loads after the first, you can use the third argument of `wp_enqueue_style` to set a dependency, eg:
```
wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css', array() );
wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css', array('styles') );
```
As for having **all** the styles in *responsive.css* override *style.css*, that is going to entirely depend on the specificity of the targeting in each stylesheet, CSS being a Cascading Style Sheet, it would be worth researching exactly what that means if you aren't fully sure how it works. |
283,316 | <p>I'm of the understanding that Wordpress' .htaccess, like below:</p>
<pre><code># 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]
</IfModule>
# END WordPress
</code></pre>
<p>sends all queries through to the index.php (unless the filename exists on the server etc). </p>
<p>So, if I go to <code>http://example.com/checkout</code> Wordpress rewrites that as <code>http://example.com/index.php?pagename=checkout</code>.</p>
<p>But what I don't understand is that I have, at the top of a page template </p>
<pre><code><?php print_r($_GET) ?>
</code></pre>
<p>and when I navigate to <code>http://example.com/checkout</code> that returns <code>Array()</code>. I'd expect something like <code>Array('pagename' => 'checkout')</code>;</p>
<p>How can I access the variables that Wordpress uses when handling a URL?</p>
| [
{
"answer_id": 283318,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 1,
"selected": false,
"text": "<p>It calls <code>index.php</code>, not <code>index.php?page=..</code>.</p>\n\n<p>I'm not sure how WordPress does its routing, but you could use <code>$_SERVER['PATH_INFO']</code> or <code>$_SERVER['REQUEST_URI']</code></p>\n"
},
{
"answer_id": 283321,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>It's not really rewriting the URL in the conventional sense, URL parsing happens entirely within PHP.</p>\n\n<p>You can access the query vars in the global <code>$wp_query->query_vars</code>, or with the <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\"><code>get_query_var</code></a> function.</p>\n\n<p>Also note that <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/parse_request\" rel=\"nofollow noreferrer\"><code>parse_request</code></a> is the earliest action where this info will be available.</p>\n"
},
{
"answer_id": 283322,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 1,
"selected": false,
"text": "<p>Don't get fooled by the names. mod_rewrite Rewrite Rules and WordPress Rewrite Rules are two very different things.</p>\n\n<p>In the .htaccess, there are mod_rewrite rules that don't do anything other than run WP's index.php for any requests that don't directly hit an existing file or directory.</p>\n\n<p>To figure out, what /checkout means, WordPress then relies on its' own set of rewrite rules which have nothing at all to do with mod_rewrite, so don't get confused.</p>\n\n<p>WordPress' <code>$redirect</code> part looks like it passes variables via HTTP GET, but that isn't really the case. Those will be used as rewrite tags. See the <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow noreferrer\">documentation for add_rewrite_rule</a> for a few examples and further explanation.</p>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283316",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27866/"
]
| I'm of the understanding that Wordpress' .htaccess, like below:
```
# 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]
</IfModule>
# END WordPress
```
sends all queries through to the index.php (unless the filename exists on the server etc).
So, if I go to `http://example.com/checkout` Wordpress rewrites that as `http://example.com/index.php?pagename=checkout`.
But what I don't understand is that I have, at the top of a page template
```
<?php print_r($_GET) ?>
```
and when I navigate to `http://example.com/checkout` that returns `Array()`. I'd expect something like `Array('pagename' => 'checkout')`;
How can I access the variables that Wordpress uses when handling a URL? | It's not really rewriting the URL in the conventional sense, URL parsing happens entirely within PHP.
You can access the query vars in the global `$wp_query->query_vars`, or with the [`get_query_var`](https://codex.wordpress.org/Function_Reference/get_query_var) function.
Also note that [`parse_request`](https://codex.wordpress.org/Plugin_API/Action_Reference/parse_request) is the earliest action where this info will be available. |
283,331 | <p>Want to enforce the visitor to load the new version of your stylesheets and scripts</p>
| [
{
"answer_id": 283332,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like you are talking about cachebusting. Changing the querystring makes the browser interpret the URL as a new resource. Unless you want to change the entire filename there really isn't a better way to do this.</p>\n\n<p>Use the <code>$ver</code> argument of <code>wp_enqueue_script</code> and <code>wp_enqueue_style</code> to make it easier. You could even set <code>$ver = time()</code> to force download everytime, however it is probably preferable to use the <code>filemtime</code> of the filepath for the best of both worlds - refreshing the resource only when it has actually changed.</p>\n"
},
{
"answer_id": 283345,
"author": "Jesse Vlasveld",
"author_id": 87884,
"author_profile": "https://wordpress.stackexchange.com/users/87884",
"pm_score": 3,
"selected": true,
"text": "<p>If you want to enforce the visitor to load the new version of your stylesheets and scripts, then (as @majick suggested) changing the version via query string is the way to go. This is just how the caching works.</p>\n\n<p>My suggestion would be to make sure you update the theme version on every major, or crucial CSS and JS update, and use the theme version in the <code>wp_enqueue_script</code> version arg (which is how most themes do it).</p>\n\n<p>In case it's a development issue (sometimes the caching gets in the way), you could consider making use of the <code>SCRIPT_DEBUG</code> constant, which you can set in your <code>wp-config.php</code> file. This is actually used to get a non-minified version of a file for development purposes, but you could use it to add a version to your <code>wp_enqueue_scripts</code> action like this:</p>\n\n<pre><code>$theme = wp_get_theme();\n$theme_version = $theme->get( 'Version' );\n$dev_version = filemtime( get_template_directory_uri() . '/path/to.js' );\n\n$version = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? $dev_version : $theme_version;\n\nwp_enqueue_scripts( 'your-script', get_template_directory_uri() . '/path/to.js', array(), $version );\n</code></pre>\n\n<p>This way you could set it for all enqueues, and you would only have to change the setting in your <code>wp-config.php</code> file.</p>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283331",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64554/"
]
| Want to enforce the visitor to load the new version of your stylesheets and scripts | If you want to enforce the visitor to load the new version of your stylesheets and scripts, then (as @majick suggested) changing the version via query string is the way to go. This is just how the caching works.
My suggestion would be to make sure you update the theme version on every major, or crucial CSS and JS update, and use the theme version in the `wp_enqueue_script` version arg (which is how most themes do it).
In case it's a development issue (sometimes the caching gets in the way), you could consider making use of the `SCRIPT_DEBUG` constant, which you can set in your `wp-config.php` file. This is actually used to get a non-minified version of a file for development purposes, but you could use it to add a version to your `wp_enqueue_scripts` action like this:
```
$theme = wp_get_theme();
$theme_version = $theme->get( 'Version' );
$dev_version = filemtime( get_template_directory_uri() . '/path/to.js' );
$version = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? $dev_version : $theme_version;
wp_enqueue_scripts( 'your-script', get_template_directory_uri() . '/path/to.js', array(), $version );
```
This way you could set it for all enqueues, and you would only have to change the setting in your `wp-config.php` file. |
283,334 | <p>Someone very kindly helped me out on another question, which has now lead to this problem of two functions causing a database error. From what I've read it could have something to do with <code>LEFT JOIN</code> and/or no <code>wp_reset_query()</code> or <code>wp_reset_postdata()</code>. The error I'm getting is :</p>
<pre><code>WordPress database error: [Not unique table/alias: 'wp_postmeta']
SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (567) ) AND ( wp_postmeta.meta_key = 'featured_listing' ) AND wp_posts.post_type = 'business' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value DESC LIMIT 0, 10
</code></pre>
<p>I've narrowed it down to two functions one being : </p>
<pre><code>// Order posts for featured posts first in search and categories
function custom_special_sort( $query ) {
// if is this the main query and is this post type of business
if ( ($query->is_main_query() && is_post_type_archive('business') ) || (is_main_query() && is_tax ('location') ) ) {
// order results by the meta_key 'featured_listing'
$query->set( 'meta_key', 'featured_listing' );
$query->set( 'orderby', 'featured_listing' );
$query->set( 'order', 'DESC' );
}
}
add_action( 'pre_get_posts', 'custom_special_sort' );
</code></pre>
<p>and the other being : </p>
<pre><code>function cf_search_join( $join ) {
global $wpdb;
if ( is_search() ) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
add_filter('posts_join', 'cf_search_join' );
</code></pre>
<p>+</p>
<pre><code>function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
</code></pre>
<p>+</p>
<pre><code>function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT";
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
</code></pre>
<p>The first function changes the order of posts in a search result, to order them with a certain post_meta above the rest. </p>
<p>The second function, add custom fields to the search query instead of wordpress just searching for post content and titles. </p>
<p>Any help in resolving the conflict would be much appreciated. If I remove one of the functions, the other one operates as it should but they just won't work together, from my reading i assume its because they are trying to edit the same query ?</p>
| [
{
"answer_id": 283348,
"author": "Milan Petrovic",
"author_id": 126702,
"author_profile": "https://wordpress.stackexchange.com/users/126702",
"pm_score": 4,
"selected": true,
"text": "<p>You JOIN two elements both with the same table. When you need to join one table more than once, you need to make each join unique by giving the table alias. When WP makes the whole query, it takes that into account, but you have added your own code that doesn't do that.</p>\n<p>So, first function:</p>\n<pre><code>function cf_search_join( $join ) {\n global $wpdb;\n\n if ( is_search() ) { \n $join .=' LEFT JOIN '.$wpdb->postmeta. ' cfmeta ON '. $wpdb->posts . '.ID = cfmeta.post_id ';\n }\n\n return $join;\n}\nadd_filter('posts_join', 'cf_search_join' );\n</code></pre>\n<p>This sets postmeta table alias 'cfmeta' and uses it in the ON.</p>\n<p>And the second one:</p>\n<pre><code>function cf_search_where( $where ) {\n global $pagenow, $wpdb;\n\n if ( is_search() ) {\n $where = preg_replace(\n "/\\(\\s*".$wpdb->posts.".post_title\\s+LIKE\\s*(\\'[^\\']+\\')\\s*\\)/",\n "(".$wpdb->posts.".post_title LIKE $1) OR (cfmeta.meta_value LIKE $1)", $where );\n }\n\n return $where;\n}\nadd_filter( 'posts_where', 'cf_search_where' );\n</code></pre>\n<p>Using the 'cfmeta' instead of wp_postmeta.</p>\n<p>Milan</p>\n"
},
{
"answer_id": 402527,
"author": "Benjamin Vaughan",
"author_id": 183902,
"author_profile": "https://wordpress.stackexchange.com/users/183902",
"pm_score": 0,
"selected": false,
"text": "<p>If anyone is still looking at this issue and cannot fix it by the wonderful solution provided above, take a look that you don't have any display errors / error reporting code still active.</p>\n<p>I was looking for a very long time for this solution and it seems like these options below can adjust the queries and cause errors.</p>\n<p>Removing this code fixed the problem.</p>\n<pre><code>ini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\n</code></pre>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283334",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62291/"
]
| Someone very kindly helped me out on another question, which has now lead to this problem of two functions causing a database error. From what I've read it could have something to do with `LEFT JOIN` and/or no `wp_reset_query()` or `wp_reset_postdata()`. The error I'm getting is :
```
WordPress database error: [Not unique table/alias: 'wp_postmeta']
SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (567) ) AND ( wp_postmeta.meta_key = 'featured_listing' ) AND wp_posts.post_type = 'business' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value DESC LIMIT 0, 10
```
I've narrowed it down to two functions one being :
```
// Order posts for featured posts first in search and categories
function custom_special_sort( $query ) {
// if is this the main query and is this post type of business
if ( ($query->is_main_query() && is_post_type_archive('business') ) || (is_main_query() && is_tax ('location') ) ) {
// order results by the meta_key 'featured_listing'
$query->set( 'meta_key', 'featured_listing' );
$query->set( 'orderby', 'featured_listing' );
$query->set( 'order', 'DESC' );
}
}
add_action( 'pre_get_posts', 'custom_special_sort' );
```
and the other being :
```
function cf_search_join( $join ) {
global $wpdb;
if ( is_search() ) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
add_filter('posts_join', 'cf_search_join' );
```
+
```
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
```
+
```
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT";
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
```
The first function changes the order of posts in a search result, to order them with a certain post\_meta above the rest.
The second function, add custom fields to the search query instead of wordpress just searching for post content and titles.
Any help in resolving the conflict would be much appreciated. If I remove one of the functions, the other one operates as it should but they just won't work together, from my reading i assume its because they are trying to edit the same query ? | You JOIN two elements both with the same table. When you need to join one table more than once, you need to make each join unique by giving the table alias. When WP makes the whole query, it takes that into account, but you have added your own code that doesn't do that.
So, first function:
```
function cf_search_join( $join ) {
global $wpdb;
if ( is_search() ) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' cfmeta ON '. $wpdb->posts . '.ID = cfmeta.post_id ';
}
return $join;
}
add_filter('posts_join', 'cf_search_join' );
```
This sets postmeta table alias 'cfmeta' and uses it in the ON.
And the second one:
```
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (cfmeta.meta_value LIKE $1)", $where );
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
```
Using the 'cfmeta' instead of wp\_postmeta.
Milan |
283,342 | <p>Im trying to update my front end post form which allows me to save my custom taxonomy parent term, but now I need to save the child term that's selected.</p>
<p>NHB is for Neighborhood which are child terms for the city-type taxonomy. Here's my code on top for the relevant fields -- </p>
<pre><code> $city_type = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
$city_type = array_reverse($city_type);
if (!empty($city_type)) {
$city_term = get_term($city_type[0], 'city-type');
$city_type_value = $city_term->slug;
}
$nhb = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
if (!empty($nhb)) {
$term = get_term($nhb[0], 'city-type');
$nhb_type_value = $term->name;
</code></pre>
<p>And -</p>
<pre><code> wp_set_object_terms($pid, $nhb_type_value, 'city-type');
update_post_meta($pid, 'imic_property_custom_city', $property_custom_city);
$city_for_update = get_term_by('slug', $city_type_value, 'city-type');
$term_array = array();
while ($city_for_update->parent != 0) {
$city_for_update = get_term_by('id', $city_for_update->parent, 'city-type');
array_push($term_array, $city_for_update->slug);
}
array_push($term_array, $city_type_value);
wp_set_object_terms($pid, $term_array, 'city-type');
</code></pre>
<p>Then my drop down for the child terms on my post form on the front end --</p>
<pre><code><?php $taxonomyName = "city-type";
$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );
echo "<select name='nhb' class='form-control' id='p-nhb'>";
echo "<option class='button' value='Any'>All</option>";
foreach ( $parent_terms as $pterm ) {
//Get the Child terms
$terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
foreach ( $terms as $term ) {
$selected = ($nhb_type_value == $term->name) ? "selected" : "";
echo "<option data-val='" . $pterm->slug . "' value='" . $term->slug . "' ' . $selected . '>" . $term->name . "</option>";
}
}
echo "</select>";
?>
</code></pre>
<p>How can I get that to save as a child term and also output? I currently output the parent term like this -- </p>
<pre><code><?php $terms = wp_get_post_terms(get_the_ID(), 'city-type');
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo '' . $term->name . '';
}
} ?>
</code></pre>
<p><strong>UPDATE</strong></p>
<p>On top of my page I have the following to save the terms. $city_type is for the "city-type" taxonomy parent terms. $nhb is for the child terms that correspond with the selected/saved parent term.</p>
<pre><code><?php
/*
Template Name: Front End Form
*/
get_header();
global $current_user, // Use global
get_currentuserinfo(); // Make sure global is set, if not set it.
$subdraft = $_POST['subdraft'];
$edit_url = imic_get_template_url('template-edit-property-new.php');
if ((user_can($current_user, "administrator"))||(user_can($current_user, "edit_others_posts")) ):
global $imic_options;
$msg = '';
$flag = 0;
$Property_Id = $property_title = $city_type_value = $nhb_type_value = '';
if (get_query_var('site')) {
$Property_Id = get_query_var('site');
$property_title = get_the_title($Property_Id);
$city_type = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
$city_type = array_reverse($city_type);
if (!empty($city_type)) {
$city_term = get_term($city_type[0], 'city-type');
$city_type_value = $city_term->slug;
}
$nhb = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
if (!empty($nhb)) {
$term = get_term($nhb[0], 'city-type');
$nhb_type_value = $term->name;
}
}
$Property_Status = get_post_meta(get_the_ID(), 'imic_property_status', true);
// Check if the form was submitted
if ('POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST['action'])) {
$property_title = $_POST['title'];
$nhb_type_value = $_POST['nhb'];
if (isset($_POST['textonomies_city']) && !empty($_POST['textonomies_city'])) {
$reverce_data = array_reverse($_POST['textonomies_city']);
foreach ($reverce_data as $textonomies_city) {
if (!empty($textonomies_city)) {
$city_type_value = $textonomies_city;
break;
}
}
$property_custom_city = '';
}
if (($city_type_value == 'other') || ($city_type_value == 'city')) {
$city_type_value = '';
}
if ($msg == '') {
if (get_query_var('site')) {
$post = array(
'ID' => get_query_var('site'),
'post_title' => $property_title,
'post_content' => $property_content,
'post_date' => $property_listdate_value,
'post_status' => 'publish', // Choose: publish, preview, future, etc.
'post_type' => 'property' // Use a custom post type if you want to
);
$pid = wp_update_post($post);
// Pass the value of $post to WordPress the insert function
$flag = 1;
} else {
$post_status = 'draft';
}
$post = array(
'post_title' => $property_title,
'post_content' => $property_content,
'post_status' => $post_status,
'post_date' => $property_listdate_value,
'post_type' => 'property' // Use a custom post type if you want to
);
$pid = wp_insert_post($post);
$total_property = get_user_meta($current_user->ID, 'property_value', true);
$new_value = ($total_property != 0) ? ($total_property - 1) : $total_property;
update_user_meta($current_user->ID, 'property_value', $new_value);
$flag = 1;
}
wp_set_object_terms($pid, $nhb_type_value, 'city-type');
if ('POST' == $_SERVER['REQUEST_METHOD']) {
// Set Terms For Tax
wp_set_object_terms($pid, $nhb_type_value, 'city-type');
$city_for_update = get_term_by('slug', $city_type_value, 'city-type');
$term_array = array();
while ($city_for_update->parent != 0) {
$city_for_update = get_term_by('id', $city_for_update->parent, 'city-type');
array_push($term_array, $city_for_update->slug);
}
array_push($term_array, $city_type_value);
wp_set_object_terms($pid, $term_array, 'city-type');
if (get_query_var('site')) {
$Property_Id = get_query_var('site');
$property_title = get_the_title($Property_Id);
$nhb = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
if (!empty($nhb)) {
$terms = get_term($nhb[0], 'city-type');
$nhb_type_value = $terms->name;
}
}
}
}
if(get_query_var('remove')){
$delete_id = get_query_var('remove');
$post_author = get_post_field('post_author',$delete_id);
$user_name= $current_user->ID;
if($post_author==$user_name){
wp_trash_post($delete_id); }
}
if (get_query_var('site')) {
$current_Id = get_query_var('site');
} else {
$current_Id = get_the_ID();
}
?>
</code></pre>
<p>The form -</p>
<pre><code> <form action="" method="post" enctype="multipart/form-data">
</code></pre>
<p>The child terms drop down select -</p>
<pre><code><?php $taxonomyName = "city-type";
$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );
echo "<select name='nhb' class='form-control' id='p-nhb'>";
echo "<option class='button' value='Any'>All</option>";
foreach ( $parent_terms as $pterm ) {
//Get the Child terms
$terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
foreach ( $terms as $term ) {
$selected = ($nhb_type_value == $term->name) ? "selected" : "";
echo "<option data-val='" . $pterm->slug . "' value='" . $term->slug . "' " . $selected . ">" . $term->name . "</option>";
}
}
echo "</select>";
?>
</code></pre>
| [
{
"answer_id": 283962,
"author": "Tom",
"author_id": 3482,
"author_profile": "https://wordpress.stackexchange.com/users/3482",
"pm_score": 2,
"selected": false,
"text": "<p>With saving child terms, I believe you can add them to the <code>$term_array</code> group where the parent lives. From the perspective of a post (or custom post type) saving the taxonomy has nothing to do with parent or child. </p>\n\n<p>The WP Codex states <strong><em>\"For hierarchical terms (such as categories), you must always pass the id rather than the term name to avoid confusion where there may be another child with the same name.\"</em></strong> This implies that you should be able to pass the child ID and it will be categorized in the child term.</p>\n\n<p>Source: <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_post_terms#Notes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_set_post_terms#Notes</a> </p>\n\n<p>Regarding displaying the children, you can do it one of two ways. The first, you can continue looping through children based on your code:</p>\n\n<pre><code>/*\nDisplay child terms:\n\nSource:\nhttps://developer.wordpress.org/reference/functions/get_term_children/\n*/\n$parent_terms = wp_get_post_terms(get_the_ID(), 'city-type');\nif ( ! empty( $parent_terms ) && ! is_wp_error( $parent_terms ) ){\n foreach ( $parent_terms as $parent ) {\n echo '' . $parent->name . '';\n\n $children = get_term_children($parent->ID, 'city-type'); //term_id, taxonomy\n if(!empty($children) && ! is_wp_error( $children )){\n foreach($children as $child){\n echo '' . $child->name . '';\n }\n }\n }\n}\n</code></pre>\n\n<p>Or you can loop through children after getting them from the parent (in the case that you may have a parent but need it's children:</p>\n\n<pre><code>/* OR YOU CAN GET CHILDREN DIRECTLY */\n$children = get_terms(array(\n 'parent' => 10 //ID_OF_PARENT_YOU_WANT\n));\n\nif(!empty($children) && ! is_wp_error( $children )){\n foreach($children as $child){\n echo '' . $child->name . '';\n }\n}\n</code></pre>\n\n<p>EDIT: Showing an example save function.</p>\n\n<pre><code>wp_set_object_terms($pid, $nhb_type_value, 'city-type');\n\nupdate_post_meta($pid, 'imic_property_custom_city', $property_custom_city);\n$city_for_update = get_term_by('slug', $city_type_value, 'city-type');\n$term_array = array();\nwhile ($city_for_update->parent != 0) {\n $city_for_update = get_term_by('id', $city_for_update->parent, 'city-type');\n array_push($term_array, $city_for_update->slug);\n}\narray_push($term_array, $city_type_value);\n\n/*Find child ID the user selected*/\nwhile ($child_term->parent != 0) {\n $child_term = get_term_by('id', $child_term->ID, 'city-type');\n //Get child term object and add to term_array\n array_push($term_array, $child_term->slug);\n}\n\nwp_set_object_terms($pid, $term_array, 'city-type');\n</code></pre>\n"
},
{
"answer_id": 285786,
"author": "730wavy",
"author_id": 24067,
"author_profile": "https://wordpress.stackexchange.com/users/24067",
"pm_score": 2,
"selected": true,
"text": "<p>Ok I figured it out using @TomMorton suggestion. </p>\n\n<p>I had to updated my code to this which updates the terms --</p>\n\n<pre><code>$city_for_update = get_term_by('slug', $city_type_value, 'city-type');\n$term_array = array();\nwhile ($city_for_update->parent != 0) {\n $city_for_update = get_term_by('id', $city_for_update->parent, 'city-type');\n array_push($term_array, $city_for_update->slug);\n}\narray_push($term_array, $city_type_value);\n\n$child_term = get_term_by('slug', $nhb_type_value, 'city-type');\n$term_array = array();\n/*Find child ID the user selected*/\nwhile ($child_term->parent != 0) {\n $child_term = get_term_by('id', $child_term->ID, 'city-type');\n //Get child term object and add to term_array\n array_push($term_array, $child_term->slug);\n}\narray_push($term_array, $nhb_type_value);\n</code></pre>\n\n<p>And this to set them --</p>\n\n<pre><code>$nhb_type_value = $_POST['nhb'];\n\n$nhb_type = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));\n$nhb_type = array_reverse($nhb_type);\n if (!empty($nhb_type)) {\n $terms = get_term($nhb_type[0], 'city-type');\n $nhb_type_value = $terms->slug;\n }\n</code></pre>\n\n<p>The only thing I had to change on my drop down was this, I was using term name but I changed it to term slug -</p>\n\n<pre><code>$selected = ($nhb_type_value == $term->slug) ? \"selected\" : \"\";\n</code></pre>\n\n<p>Then just make sure the terms are being set, using --</p>\n\n<pre><code>wp_set_object_terms($pid, $nhb_type_value, 'city-type');\n</code></pre>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283342",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24067/"
]
| Im trying to update my front end post form which allows me to save my custom taxonomy parent term, but now I need to save the child term that's selected.
NHB is for Neighborhood which are child terms for the city-type taxonomy. Here's my code on top for the relevant fields --
```
$city_type = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
$city_type = array_reverse($city_type);
if (!empty($city_type)) {
$city_term = get_term($city_type[0], 'city-type');
$city_type_value = $city_term->slug;
}
$nhb = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
if (!empty($nhb)) {
$term = get_term($nhb[0], 'city-type');
$nhb_type_value = $term->name;
```
And -
```
wp_set_object_terms($pid, $nhb_type_value, 'city-type');
update_post_meta($pid, 'imic_property_custom_city', $property_custom_city);
$city_for_update = get_term_by('slug', $city_type_value, 'city-type');
$term_array = array();
while ($city_for_update->parent != 0) {
$city_for_update = get_term_by('id', $city_for_update->parent, 'city-type');
array_push($term_array, $city_for_update->slug);
}
array_push($term_array, $city_type_value);
wp_set_object_terms($pid, $term_array, 'city-type');
```
Then my drop down for the child terms on my post form on the front end --
```
<?php $taxonomyName = "city-type";
$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );
echo "<select name='nhb' class='form-control' id='p-nhb'>";
echo "<option class='button' value='Any'>All</option>";
foreach ( $parent_terms as $pterm ) {
//Get the Child terms
$terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
foreach ( $terms as $term ) {
$selected = ($nhb_type_value == $term->name) ? "selected" : "";
echo "<option data-val='" . $pterm->slug . "' value='" . $term->slug . "' ' . $selected . '>" . $term->name . "</option>";
}
}
echo "</select>";
?>
```
How can I get that to save as a child term and also output? I currently output the parent term like this --
```
<?php $terms = wp_get_post_terms(get_the_ID(), 'city-type');
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo '' . $term->name . '';
}
} ?>
```
**UPDATE**
On top of my page I have the following to save the terms. $city\_type is for the "city-type" taxonomy parent terms. $nhb is for the child terms that correspond with the selected/saved parent term.
```
<?php
/*
Template Name: Front End Form
*/
get_header();
global $current_user, // Use global
get_currentuserinfo(); // Make sure global is set, if not set it.
$subdraft = $_POST['subdraft'];
$edit_url = imic_get_template_url('template-edit-property-new.php');
if ((user_can($current_user, "administrator"))||(user_can($current_user, "edit_others_posts")) ):
global $imic_options;
$msg = '';
$flag = 0;
$Property_Id = $property_title = $city_type_value = $nhb_type_value = '';
if (get_query_var('site')) {
$Property_Id = get_query_var('site');
$property_title = get_the_title($Property_Id);
$city_type = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
$city_type = array_reverse($city_type);
if (!empty($city_type)) {
$city_term = get_term($city_type[0], 'city-type');
$city_type_value = $city_term->slug;
}
$nhb = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
if (!empty($nhb)) {
$term = get_term($nhb[0], 'city-type');
$nhb_type_value = $term->name;
}
}
$Property_Status = get_post_meta(get_the_ID(), 'imic_property_status', true);
// Check if the form was submitted
if ('POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST['action'])) {
$property_title = $_POST['title'];
$nhb_type_value = $_POST['nhb'];
if (isset($_POST['textonomies_city']) && !empty($_POST['textonomies_city'])) {
$reverce_data = array_reverse($_POST['textonomies_city']);
foreach ($reverce_data as $textonomies_city) {
if (!empty($textonomies_city)) {
$city_type_value = $textonomies_city;
break;
}
}
$property_custom_city = '';
}
if (($city_type_value == 'other') || ($city_type_value == 'city')) {
$city_type_value = '';
}
if ($msg == '') {
if (get_query_var('site')) {
$post = array(
'ID' => get_query_var('site'),
'post_title' => $property_title,
'post_content' => $property_content,
'post_date' => $property_listdate_value,
'post_status' => 'publish', // Choose: publish, preview, future, etc.
'post_type' => 'property' // Use a custom post type if you want to
);
$pid = wp_update_post($post);
// Pass the value of $post to WordPress the insert function
$flag = 1;
} else {
$post_status = 'draft';
}
$post = array(
'post_title' => $property_title,
'post_content' => $property_content,
'post_status' => $post_status,
'post_date' => $property_listdate_value,
'post_type' => 'property' // Use a custom post type if you want to
);
$pid = wp_insert_post($post);
$total_property = get_user_meta($current_user->ID, 'property_value', true);
$new_value = ($total_property != 0) ? ($total_property - 1) : $total_property;
update_user_meta($current_user->ID, 'property_value', $new_value);
$flag = 1;
}
wp_set_object_terms($pid, $nhb_type_value, 'city-type');
if ('POST' == $_SERVER['REQUEST_METHOD']) {
// Set Terms For Tax
wp_set_object_terms($pid, $nhb_type_value, 'city-type');
$city_for_update = get_term_by('slug', $city_type_value, 'city-type');
$term_array = array();
while ($city_for_update->parent != 0) {
$city_for_update = get_term_by('id', $city_for_update->parent, 'city-type');
array_push($term_array, $city_for_update->slug);
}
array_push($term_array, $city_type_value);
wp_set_object_terms($pid, $term_array, 'city-type');
if (get_query_var('site')) {
$Property_Id = get_query_var('site');
$property_title = get_the_title($Property_Id);
$nhb = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
if (!empty($nhb)) {
$terms = get_term($nhb[0], 'city-type');
$nhb_type_value = $terms->name;
}
}
}
}
if(get_query_var('remove')){
$delete_id = get_query_var('remove');
$post_author = get_post_field('post_author',$delete_id);
$user_name= $current_user->ID;
if($post_author==$user_name){
wp_trash_post($delete_id); }
}
if (get_query_var('site')) {
$current_Id = get_query_var('site');
} else {
$current_Id = get_the_ID();
}
?>
```
The form -
```
<form action="" method="post" enctype="multipart/form-data">
```
The child terms drop down select -
```
<?php $taxonomyName = "city-type";
$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );
echo "<select name='nhb' class='form-control' id='p-nhb'>";
echo "<option class='button' value='Any'>All</option>";
foreach ( $parent_terms as $pterm ) {
//Get the Child terms
$terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
foreach ( $terms as $term ) {
$selected = ($nhb_type_value == $term->name) ? "selected" : "";
echo "<option data-val='" . $pterm->slug . "' value='" . $term->slug . "' " . $selected . ">" . $term->name . "</option>";
}
}
echo "</select>";
?>
``` | Ok I figured it out using @TomMorton suggestion.
I had to updated my code to this which updates the terms --
```
$city_for_update = get_term_by('slug', $city_type_value, 'city-type');
$term_array = array();
while ($city_for_update->parent != 0) {
$city_for_update = get_term_by('id', $city_for_update->parent, 'city-type');
array_push($term_array, $city_for_update->slug);
}
array_push($term_array, $city_type_value);
$child_term = get_term_by('slug', $nhb_type_value, 'city-type');
$term_array = array();
/*Find child ID the user selected*/
while ($child_term->parent != 0) {
$child_term = get_term_by('id', $child_term->ID, 'city-type');
//Get child term object and add to term_array
array_push($term_array, $child_term->slug);
}
array_push($term_array, $nhb_type_value);
```
And this to set them --
```
$nhb_type_value = $_POST['nhb'];
$nhb_type = wp_get_object_terms($Property_Id, 'city-type', array('fields' => 'ids'));
$nhb_type = array_reverse($nhb_type);
if (!empty($nhb_type)) {
$terms = get_term($nhb_type[0], 'city-type');
$nhb_type_value = $terms->slug;
}
```
The only thing I had to change on my drop down was this, I was using term name but I changed it to term slug -
```
$selected = ($nhb_type_value == $term->slug) ? "selected" : "";
```
Then just make sure the terms are being set, using --
```
wp_set_object_terms($pid, $nhb_type_value, 'city-type');
``` |
283,352 | <p>I have a problem with a WordPress hook. I want to call an action in another actions callback, but it doesn't seem to work. I want to call <code>add_meta_tag</code> action only if the page is saved. This is what I have:</p>
<pre><code>function saveCustomField($post_id)
{
add_action( 'wp_head', 'add_meta_tag' );
}
add_action( 'save_post', 'saveCustomField' );
function add_meta_tag(){
echo "TEST";
}
</code></pre>
<p>How can I get the above to work properly?</p>
| [
{
"answer_id": 283361,
"author": "Greg36",
"author_id": 64017,
"author_profile": "https://wordpress.stackexchange.com/users/64017",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>save_post</code> hook is fired after the data is saved to the database - whenever post or page is created or updated - only on admin pages.</p>\n\n<p>The <code>wp_head</code> hook fires when <code>wp_head()</code> function is run and this do not happen on admin pages.</p>\n\n<p>This won't work. Where and when you want to add the meta tag?</p>\n"
},
{
"answer_id": 283373,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 0,
"selected": false,
"text": "<p>The short answer: you can't.</p>\n\n<p>The code is fine, but there is a flaw in logic. <code>wp_head</code> action is set too late. Headers are already sent, therefore <code>wp_head</code> will never fire! This code below, will prove two points. First: <code>save_post</code> will fire on both, admin pages, and on front end, as well. Second: it's easy to prevent an infinite loop in callback function.</p>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>function saveCustomField($post_id) {\n\n // to prevent an infinite loop\n remove_action('save_post', 'saveCustomField', 10);\n\n // to prove that function was called\n error_log('I am here to add action');\n\n add_action('wp_head', 'add_meta_tag');\n}\nadd_action('save_post', 'saveCustomField');\n\nfunction add_meta_tag(){\n error_log('TEST');\n //echo \"TEST\";\n}\n</code></pre>\n\n<p>In my page template ( front end ):</p>\n\n<pre><code>wp_update_post(array('ID' => 79, 'post_title' => 'My Current Test',));\n</code></pre>\n\n<p>In error_log:</p>\n\n<pre><code>[19-Oct-2017 02:57:08 UTC] I am here to add action\n</code></pre>\n\n<p>My post's title had been updated, <code>save_post</code> was fired, and <code>wp_head</code> wasn't.</p>\n"
},
{
"answer_id": 283375,
"author": "Skatox Nike",
"author_id": 129869,
"author_profile": "https://wordpress.stackexchange.com/users/129869",
"pm_score": 0,
"selected": false,
"text": "<p>I want to add the meta tag when publish/update button is fired. I have a checkbox on the admin page that add/remove meta tag. For info, it's intended for a plugin.</p>\n\n<pre><code>function saveCustomField($post_id)\n{\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {\n return;\n}\n\nif (\n !isset($_POST['my_custom_nonce']) ||\n !wp_verify_nonce($_POST['my_custom_nonce'], 'my_custom_nonce_'.$post_id)\n) {\n return;\n}\n\nif (!current_user_can('edit_post', $post_id)) {\n return;\n}\n\nif (isset($_POST['_my_custom_field'])) {\n update_post_meta($post_id, '_my_custom_field', $_POST['_my_custom_field']);\n // here\n // >>>>> add_action('wp_head', 'add_meta_tag');\n} else {\n delete_post_meta($post_id, '_my_custom_field');\n}\n</code></pre>\n\n<p>}</p>\n\n<pre><code>add_action( 'save_post', 'saveCustomField' );\n\nfunction add_meta_tag(){\n echo \"TEST\";\n}\n</code></pre>\n"
},
{
"answer_id": 283384,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You're thinking about this entirely wrong. A meta tag isn't something you add when a post gets saved, it's something that gets added to the output when a post is <em>viewed</em>.</p>\n\n<p>So instead of trying to hook the action inside <code>save_post</code>, you hook it on every page load, and <em>inside</em> the hook you check if your custom field exists on the post being viewed. If it is, you output the tag.</p>\n\n<pre><code>function wpse_283352_add_meta_tag() {\n if ( is_singular() {\n $post_id = get_queried_object_id();\n $meta = get_post_meta( $post_id, '_my_custom_field', true );\n\n if ( $meta ) {\n echo '<meta name=\"my_custom_field\" content=\"' . esc_attr( $meta ) . '\">';\n }\n }\n}\nadd_action( 'wp_head', 'wpse_283352_add_meta_tag' );\n</code></pre>\n\n<p>That function just goes in your plugin file/functions file, not inside any other hook.</p>\n"
}
]
| 2017/10/18 | [
"https://wordpress.stackexchange.com/questions/283352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129869/"
]
| I have a problem with a WordPress hook. I want to call an action in another actions callback, but it doesn't seem to work. I want to call `add_meta_tag` action only if the page is saved. This is what I have:
```
function saveCustomField($post_id)
{
add_action( 'wp_head', 'add_meta_tag' );
}
add_action( 'save_post', 'saveCustomField' );
function add_meta_tag(){
echo "TEST";
}
```
How can I get the above to work properly? | You're thinking about this entirely wrong. A meta tag isn't something you add when a post gets saved, it's something that gets added to the output when a post is *viewed*.
So instead of trying to hook the action inside `save_post`, you hook it on every page load, and *inside* the hook you check if your custom field exists on the post being viewed. If it is, you output the tag.
```
function wpse_283352_add_meta_tag() {
if ( is_singular() {
$post_id = get_queried_object_id();
$meta = get_post_meta( $post_id, '_my_custom_field', true );
if ( $meta ) {
echo '<meta name="my_custom_field" content="' . esc_attr( $meta ) . '">';
}
}
}
add_action( 'wp_head', 'wpse_283352_add_meta_tag' );
```
That function just goes in your plugin file/functions file, not inside any other hook. |
283,386 | <p>Please assist, I am trying to load this Jquery on my Wordpress website with no luck.</p>
<p>I have used this script just BEFORE the <code></body></code> tag in my functions.php :</p>
<pre><code><script type="text/javascript"
src="<?php bloginfo("template_url"); ?>/js/menu-hover.js"></script>
</code></pre>
<p>I have used this code in the of my functions.php file:</p>
<pre><code><?php
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/js/jquery.min.js", false, null);
wp_enqueue_script('jquery');
}
?>
</code></pre>
<p>This is my Jquery/Javascript code:</p>
<pre><code>jQuery( "#panel-2-1-0-0" ).hover( //Print and Document
function() {
jQuery('#mega-menu-item-475').addClass('mega-toggle-on');
}, function() {
jQuery('#mega-menu-item-475').removeClass('mega-toggle-on');
}
);
jQuery( "#panel-2-1-1-0" ).hover( //Telecom
function() {
jQuery('#mega-menu-item-477').addClass('mega-toggle-on');
}, function() {
jQuery('#mega-menu-item-477').removeClass('mega-toggle-on');
}
);
jQuery( "#panel-2-1-0-1" ).hover( //IT Dev
function() {
jQuery('#mega-menu-item-476').addClass('mega-toggle-on');
}, function() {
jQuery('#mega-menu-item-476').removeClass('mega-toggle-on');
}
);
jQuery( "#panel-2-1-1-1" ).hover( // Safety and Security
function() {
jQuery('#mega-menu-item-478').addClass('mega-toggle-on');
}, function() {
jQuery('#mega-menu-item-478').removeClass('mega-toggle-on');
}
);
</code></pre>
| [
{
"answer_id": 283416,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li><a href=\"https://pippinsplugins.com/why-loading-your-own-jquery-is-irresponsible/\" rel=\"nofollow noreferrer\">Don't enqueue your own version of jQuery</a>. You're just going to cause conflict issues with other plugins and there's nothing in your script that requires a different version.</li>\n<li>Even if you were, <a href=\"https://twitter.com/paul_irish/status/588502455530311680\" rel=\"nofollow noreferrer\">just load the https:// version</a>, there's no reason to bother checking what your own server is doing.</li>\n<li>Don't bother checking <code>!is_admin()</code> on your enqueue function, <code>wp_enqueue_scripts</code> doesn't even run in admin.</li>\n<li>Don't add script tags in templates, use <code>wp_enqueue_script()</code>.</li>\n<li>The proper way, these days, to get the URL to a theme file is <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_theme_file_uri()</code></a>.</li>\n<li>When you say \"I have used this script just BEFORE the <code></body></code> tag in my functions.php :\", you don't actually mean your <code></body></code> tag is in functions.php do you?</li>\n</ol>\n\n<p>Put all together, your code should just be this, in your functions.php file:</p>\n\n<pre><code>function wpse_283386_enqueue_scripts() {\n wp_enqueue_script( 'menu-hover', get_theme_file_uri( 'js/menu-hover.js' ), array( 'jquery' ), '', true );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_283386_enqueue_scripts' );\n</code></pre>\n\n<p>The only reasons it wouldn't work after this are:</p>\n\n<ol>\n<li>The IDs you're targeting in your script don't exist.</li>\n<li>The classes you're adding and removing don't do anything in your CSS.</li>\n<li><code>/wp-content/themes/{your theme}/js/menu-hover.js</code> doesn't exist.</li>\n</ol>\n"
},
{
"answer_id": 283426,
"author": "Bradley",
"author_id": 129843,
"author_profile": "https://wordpress.stackexchange.com/users/129843",
"pm_score": 0,
"selected": false,
"text": "<p><strong>This is the code I am using in the themes functions.php, exactly as advised:</strong> </p>\n\n<p><a href=\"https://i.stack.imgur.com/qr6XU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qr6XU.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>This is the path where menu-hover.js exists:</strong> </p>\n\n<p><a href=\"https://i.stack.imgur.com/s4MjD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s4MjD.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/10/19 | [
"https://wordpress.stackexchange.com/questions/283386",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129843/"
]
| Please assist, I am trying to load this Jquery on my Wordpress website with no luck.
I have used this script just BEFORE the `</body>` tag in my functions.php :
```
<script type="text/javascript"
src="<?php bloginfo("template_url"); ?>/js/menu-hover.js"></script>
```
I have used this code in the of my functions.php file:
```
<?php
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/js/jquery.min.js", false, null);
wp_enqueue_script('jquery');
}
?>
```
This is my Jquery/Javascript code:
```
jQuery( "#panel-2-1-0-0" ).hover( //Print and Document
function() {
jQuery('#mega-menu-item-475').addClass('mega-toggle-on');
}, function() {
jQuery('#mega-menu-item-475').removeClass('mega-toggle-on');
}
);
jQuery( "#panel-2-1-1-0" ).hover( //Telecom
function() {
jQuery('#mega-menu-item-477').addClass('mega-toggle-on');
}, function() {
jQuery('#mega-menu-item-477').removeClass('mega-toggle-on');
}
);
jQuery( "#panel-2-1-0-1" ).hover( //IT Dev
function() {
jQuery('#mega-menu-item-476').addClass('mega-toggle-on');
}, function() {
jQuery('#mega-menu-item-476').removeClass('mega-toggle-on');
}
);
jQuery( "#panel-2-1-1-1" ).hover( // Safety and Security
function() {
jQuery('#mega-menu-item-478').addClass('mega-toggle-on');
}, function() {
jQuery('#mega-menu-item-478').removeClass('mega-toggle-on');
}
);
``` | 1. [Don't enqueue your own version of jQuery](https://pippinsplugins.com/why-loading-your-own-jquery-is-irresponsible/). You're just going to cause conflict issues with other plugins and there's nothing in your script that requires a different version.
2. Even if you were, [just load the https:// version](https://twitter.com/paul_irish/status/588502455530311680), there's no reason to bother checking what your own server is doing.
3. Don't bother checking `!is_admin()` on your enqueue function, `wp_enqueue_scripts` doesn't even run in admin.
4. Don't add script tags in templates, use `wp_enqueue_script()`.
5. The proper way, these days, to get the URL to a theme file is [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/).
6. When you say "I have used this script just BEFORE the `</body>` tag in my functions.php :", you don't actually mean your `</body>` tag is in functions.php do you?
Put all together, your code should just be this, in your functions.php file:
```
function wpse_283386_enqueue_scripts() {
wp_enqueue_script( 'menu-hover', get_theme_file_uri( 'js/menu-hover.js' ), array( 'jquery' ), '', true );
}
add_action( 'wp_enqueue_scripts', 'wpse_283386_enqueue_scripts' );
```
The only reasons it wouldn't work after this are:
1. The IDs you're targeting in your script don't exist.
2. The classes you're adding and removing don't do anything in your CSS.
3. `/wp-content/themes/{your theme}/js/menu-hover.js` doesn't exist. |
283,393 | <p>I'm really new to php editing but I'm trying to learn. My woocommerce products that are set to "hidden" under catalog visibility are still showing up under search results. How do I keep hidden products out of my search results? I found this thread (<a href="https://wordpress.stackexchange.com/questions/231118/wp-query-exclude-hidden-products-from-woocommerce-product-list">WP_Query: Exclude hidden products from WooCommerce product list</a>) and tried adding the below code mentioned at the bottom of the thread (I'm using Woocommerce 3.2.1) to my child theme's functions.php file. It gave me the white screen of death and this error:</p>
<blockquote>
<p>Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW).</p>
</blockquote>
<pre><code><?php
/*
Code to remove hidden woocommerce products from being displayed in a site search
*/
'tax_query' => array(
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => 'NOT IN',
)
)
</code></pre>
<p>Appreciate help in what I'm doing wrong. Thanks!</p>
| [
{
"answer_id": 283397,
"author": "Milan Petrovic",
"author_id": 126702,
"author_profile": "https://wordpress.stackexchange.com/users/126702",
"pm_score": 2,
"selected": false,
"text": "<p>This code can't be added anywhere you want, and it can't be added to functions.php or any other php file like this. This is a element for the array used to create the WordPress query object. It has to be added via WP_Query class or get_posts and query_posts functions, or via the filter to modify the main page query.</p>\n\n<p>But, without knowing more on how your search template works, there is no way to provide the help with this. If you work with classic search template, this is the code that will apply the taxonomy filter you need to use, and you can add this to the functions.php:</p>\n\n<pre><code>add_action('pre_get_posts', 'wpse_187444_search_query_pre');\n\nfunction wpse_187444_search_query_pre($query) {\n if ($query->is_search() && $query->is_main_query()) {\n $tax_query = $query->get('tax_query', array());\n\n $tax_query[] = array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'exclude-from-catalog',\n 'operator' => 'NOT IN',\n );\n\n $query->set('tax_query', $tax_query);\n }\n}\n</code></pre>\n\n<p>But, this might not work for you, it depends on your search template and the way search results are queried.</p>\n"
},
{
"answer_id": 372009,
"author": "Meloman",
"author_id": 191010,
"author_profile": "https://wordpress.stackexchange.com/users/191010",
"pm_score": 1,
"selected": false,
"text": "<p>The only working solution for me (I tried all snippet combinations), has been to install a free plugin called <a href=\"http://wordpress.org/plugins/search-exclude/\" rel=\"nofollow noreferrer\">search-exclude</a>.</p>\n<p><a href=\"https://i.stack.imgur.com/avhUv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/avhUv.png\" alt=\"enter image description here\" /></a></p>\n<p>It Works like a charm with my <a href=\"https://woocommerce.com/\" rel=\"nofollow noreferrer\">Woocommerce</a> online shop products.</p>\n"
}
]
| 2017/10/19 | [
"https://wordpress.stackexchange.com/questions/283393",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129888/"
]
| I'm really new to php editing but I'm trying to learn. My woocommerce products that are set to "hidden" under catalog visibility are still showing up under search results. How do I keep hidden products out of my search results? I found this thread ([WP\_Query: Exclude hidden products from WooCommerce product list](https://wordpress.stackexchange.com/questions/231118/wp-query-exclude-hidden-products-from-woocommerce-product-list)) and tried adding the below code mentioned at the bottom of the thread (I'm using Woocommerce 3.2.1) to my child theme's functions.php file. It gave me the white screen of death and this error:
>
> Parse error: syntax error, unexpected '=>' (T\_DOUBLE\_ARROW).
>
>
>
```
<?php
/*
Code to remove hidden woocommerce products from being displayed in a site search
*/
'tax_query' => array(
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => 'NOT IN',
)
)
```
Appreciate help in what I'm doing wrong. Thanks! | This code can't be added anywhere you want, and it can't be added to functions.php or any other php file like this. This is a element for the array used to create the WordPress query object. It has to be added via WP\_Query class or get\_posts and query\_posts functions, or via the filter to modify the main page query.
But, without knowing more on how your search template works, there is no way to provide the help with this. If you work with classic search template, this is the code that will apply the taxonomy filter you need to use, and you can add this to the functions.php:
```
add_action('pre_get_posts', 'wpse_187444_search_query_pre');
function wpse_187444_search_query_pre($query) {
if ($query->is_search() && $query->is_main_query()) {
$tax_query = $query->get('tax_query', array());
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => 'NOT IN',
);
$query->set('tax_query', $tax_query);
}
}
```
But, this might not work for you, it depends on your search template and the way search results are queried. |
283,405 | <p>I know that there are a few ways of doing this but for everything that I have tried I can only manage to get the first category. For example:</p>
<pre><code><?php echo get_the_category_list(); ?>
</code></pre>
<p>Only shows one. Like:</p>
<pre><code><?php
foreach((get_the_category()) as $category){
echo $category->name."<br>";
echo category_description($category);
}
?>
</code></pre>
<p>Shouldn't this functions get me the full list of existing categories?</p>
| [
{
"answer_id": 283406,
"author": "Dejan Gavrilovic",
"author_id": 129636,
"author_profile": "https://wordpress.stackexchange.com/users/129636",
"pm_score": 0,
"selected": false,
"text": "<p>This code should work.\nPlease check if you have post assigned to your categories.\nCategory should not be displayed if empty. </p>\n"
},
{
"answer_id": 283414,
"author": "Sergi",
"author_id": 115742,
"author_profile": "https://wordpress.stackexchange.com/users/115742",
"pm_score": 0,
"selected": false,
"text": "<p>In my case, this worked and displayed all of the categories:</p>\n\n<pre><code>wp_list_categories();\n</code></pre>\n"
},
{
"answer_id": 283415,
"author": "L.Milo",
"author_id": 129596,
"author_profile": "https://wordpress.stackexchange.com/users/129596",
"pm_score": 3,
"selected": true,
"text": "<p>It should be noted that both </p>\n\n<pre><code><?php echo get_the_category_list(); ?>\n</code></pre>\n\n<p>and </p>\n\n<pre><code><?php \n foreach((get_the_category()) as $category){\n echo $category->name.\"<br>\";\n echo category_description($category);\n }\n ?>\n</code></pre>\n\n<p>display ALL categories that are assigned to the current post in the loop.</p>\n\n<p>From your question's title, I understand that you want to display all available categories that exist in the website, so <code>wp_list_categories()</code> is more suitable. So using: </p>\n\n<pre><code><ul>\n <?php wp_list_categories(); ?> \n</ul> \n</code></pre>\n\n<p>will return a list of all categories that have been assigned to at least one post. You can see the documentation for the function <a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow noreferrer\">here</a>. </p>\n"
}
]
| 2017/10/19 | [
"https://wordpress.stackexchange.com/questions/283405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115742/"
]
| I know that there are a few ways of doing this but for everything that I have tried I can only manage to get the first category. For example:
```
<?php echo get_the_category_list(); ?>
```
Only shows one. Like:
```
<?php
foreach((get_the_category()) as $category){
echo $category->name."<br>";
echo category_description($category);
}
?>
```
Shouldn't this functions get me the full list of existing categories? | It should be noted that both
```
<?php echo get_the_category_list(); ?>
```
and
```
<?php
foreach((get_the_category()) as $category){
echo $category->name."<br>";
echo category_description($category);
}
?>
```
display ALL categories that are assigned to the current post in the loop.
From your question's title, I understand that you want to display all available categories that exist in the website, so `wp_list_categories()` is more suitable. So using:
```
<ul>
<?php wp_list_categories(); ?>
</ul>
```
will return a list of all categories that have been assigned to at least one post. You can see the documentation for the function [here](https://developer.wordpress.org/reference/functions/wp_list_categories/). |
283,453 | <p>I want to query posts using the <code>get_posts()</code> function and am having trouble getting the query to work properly. The <code>$country</code>, <code>$us_state</code>, <code>$ca_state</code>, <code>$mx_state</code> values will be pulled from a Gravity Forms entry.</p>
<p>Here is the query:</p>
<pre><code>$post_type = 'reps';
$state_meta_key = 'rep_state';
$country_meta_key = 'rep_country';
$country = 'Mexico';
$us_state = '';
$ca_state = '';
$mx_state = '';
$reps = get_posts(
array(
'posts_per_page' => -1,
'post_type' => $post_type,
'meta_query' => array(
array(
'key' => $country_meta_key,
'value' => $country,
'compare' => 'LIKE'
),
array(
'key' => $state_meta_key,
'value' => $us_state,
'compare' => 'LIKE'
),
array(
'key' => $state_meta_key,
'value' => $ca_state,
'compare' => 'LIKE'
),
array(
'key' => $state_meta_key,
'value' => $mx_state,
'compare' => 'LIKE'
)
)
)
);
</code></pre>
<p>With this query, I will get a positive result because there is a post with meta data for <code>$country_meta_key</code> AND <code>$state_meta_key</code>, but if I change the <code>$country</code> value to Ireland, I will NOT get a result. </p>
<p>This is because the post that has a value of Ireland for the <code>$country_meta_key</code> does NOT have a value for <code>$state_meta_key</code>.</p>
<p>All posts with a <code>$state_meta_key</code> value will automatically have a <code>$country_meta_key</code> value because the Country value must exist before a State value can be chosen. BUT not all posts will have a <code>$state_meta_key</code> value (a post can have a Country value and keep the State value blank).</p>
<p>Here is an example of 2 posts:</p>
<p><strong>Post 1</strong><br>
rep_country = Mexico<br>
rep_state = Mexico - Estado de</p>
<p><strong>Post 2</strong><br>
rep_country = Ireland<br>
rep_state =</p>
<h1>Update 1</h1>
<p>The following code works to give a result when the state value is null, but (obviously) this code will not allow for querying any post by State value:</p>
<pre><code>array(
'key' => $country_meta_key,
'value' => $country,
'compare' => 'LIKE'
),
array(
'key' => $state_meta_key,
'compare' => 'NOT EXISTS'
)
</code></pre>
<p>Whenever I use the OR relation, that opens up the query to all posts within this post type (it's not specific enough).</p>
<p>How can I query the posts by Country value (where the post will NOT have State value) OR by State value (where the post will always have a Country value)?</p>
| [
{
"answer_id": 283406,
"author": "Dejan Gavrilovic",
"author_id": 129636,
"author_profile": "https://wordpress.stackexchange.com/users/129636",
"pm_score": 0,
"selected": false,
"text": "<p>This code should work.\nPlease check if you have post assigned to your categories.\nCategory should not be displayed if empty. </p>\n"
},
{
"answer_id": 283414,
"author": "Sergi",
"author_id": 115742,
"author_profile": "https://wordpress.stackexchange.com/users/115742",
"pm_score": 0,
"selected": false,
"text": "<p>In my case, this worked and displayed all of the categories:</p>\n\n<pre><code>wp_list_categories();\n</code></pre>\n"
},
{
"answer_id": 283415,
"author": "L.Milo",
"author_id": 129596,
"author_profile": "https://wordpress.stackexchange.com/users/129596",
"pm_score": 3,
"selected": true,
"text": "<p>It should be noted that both </p>\n\n<pre><code><?php echo get_the_category_list(); ?>\n</code></pre>\n\n<p>and </p>\n\n<pre><code><?php \n foreach((get_the_category()) as $category){\n echo $category->name.\"<br>\";\n echo category_description($category);\n }\n ?>\n</code></pre>\n\n<p>display ALL categories that are assigned to the current post in the loop.</p>\n\n<p>From your question's title, I understand that you want to display all available categories that exist in the website, so <code>wp_list_categories()</code> is more suitable. So using: </p>\n\n<pre><code><ul>\n <?php wp_list_categories(); ?> \n</ul> \n</code></pre>\n\n<p>will return a list of all categories that have been assigned to at least one post. You can see the documentation for the function <a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow noreferrer\">here</a>. </p>\n"
}
]
| 2017/10/19 | [
"https://wordpress.stackexchange.com/questions/283453",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58519/"
]
| I want to query posts using the `get_posts()` function and am having trouble getting the query to work properly. The `$country`, `$us_state`, `$ca_state`, `$mx_state` values will be pulled from a Gravity Forms entry.
Here is the query:
```
$post_type = 'reps';
$state_meta_key = 'rep_state';
$country_meta_key = 'rep_country';
$country = 'Mexico';
$us_state = '';
$ca_state = '';
$mx_state = '';
$reps = get_posts(
array(
'posts_per_page' => -1,
'post_type' => $post_type,
'meta_query' => array(
array(
'key' => $country_meta_key,
'value' => $country,
'compare' => 'LIKE'
),
array(
'key' => $state_meta_key,
'value' => $us_state,
'compare' => 'LIKE'
),
array(
'key' => $state_meta_key,
'value' => $ca_state,
'compare' => 'LIKE'
),
array(
'key' => $state_meta_key,
'value' => $mx_state,
'compare' => 'LIKE'
)
)
)
);
```
With this query, I will get a positive result because there is a post with meta data for `$country_meta_key` AND `$state_meta_key`, but if I change the `$country` value to Ireland, I will NOT get a result.
This is because the post that has a value of Ireland for the `$country_meta_key` does NOT have a value for `$state_meta_key`.
All posts with a `$state_meta_key` value will automatically have a `$country_meta_key` value because the Country value must exist before a State value can be chosen. BUT not all posts will have a `$state_meta_key` value (a post can have a Country value and keep the State value blank).
Here is an example of 2 posts:
**Post 1**
rep\_country = Mexico
rep\_state = Mexico - Estado de
**Post 2**
rep\_country = Ireland
rep\_state =
Update 1
========
The following code works to give a result when the state value is null, but (obviously) this code will not allow for querying any post by State value:
```
array(
'key' => $country_meta_key,
'value' => $country,
'compare' => 'LIKE'
),
array(
'key' => $state_meta_key,
'compare' => 'NOT EXISTS'
)
```
Whenever I use the OR relation, that opens up the query to all posts within this post type (it's not specific enough).
How can I query the posts by Country value (where the post will NOT have State value) OR by State value (where the post will always have a Country value)? | It should be noted that both
```
<?php echo get_the_category_list(); ?>
```
and
```
<?php
foreach((get_the_category()) as $category){
echo $category->name."<br>";
echo category_description($category);
}
?>
```
display ALL categories that are assigned to the current post in the loop.
From your question's title, I understand that you want to display all available categories that exist in the website, so `wp_list_categories()` is more suitable. So using:
```
<ul>
<?php wp_list_categories(); ?>
</ul>
```
will return a list of all categories that have been assigned to at least one post. You can see the documentation for the function [here](https://developer.wordpress.org/reference/functions/wp_list_categories/). |
283,463 | <p>I am trying to get the tags from the post (there will only be one tag), then create a new variable with that tag name but with the spaces replaced with dashes. </p>
<p>This is what a have so far, but I cannot get it to display the value of the tag (both with spaces and without) instead of "Array". In the code below, I'm only trying to get it to display with the dashes right now. </p>
<pre><code> $posttags = get_the_tags();
$newname = str_replace(' ', '-', $posttags);
if ($posttags) {
foreach ($posttags as $tag){
echo 'Post by: <a href="/meet-the-team/employees/'. $newname .'/">'. $newname .'</a>';
}
}
</code></pre>
| [
{
"answer_id": 283464,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>If you use <code>str_replace</code> on an array, you get an array back. So <code>$newname</code> is rightly an array.</p>\n\n<p>You may want to do the <code>str_replace</code> inside your <code>foreach</code> loop instead - that way it works on each individual item and then you display the individual item.</p>\n\n<p>Or, if you keep using <code>str_replace</code> on the full array, you need to change your <code>foreach</code> loop to: <code>foreach($newname as $tag)</code> and echo <code>$tag</code> not <code>$newname</code>.</p>\n"
},
{
"answer_id": 283466,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Lets break this apart using your question title:</p>\n\n<blockquote>\n <p>Get the tags as an array, convert the tag into a string, and then replace spaces with dash</p>\n</blockquote>\n\n<h2>Get the tags as an array</h2>\n\n<p><code>get_the_tags</code> is the correct function, you now have one of 2 things:</p>\n\n<ul>\n<li>an array of term objects ( a tag is a term in the tags taxonomy )</li>\n<li><code>false</code>, there are no tags on this post</li>\n<li>A <code>WP_Error</code> object, something went wrong</li>\n</ul>\n\n<p>So we need to check for those cases, afterall if we assume tags are returned but there are none, what will happen? We have to tell it what will happen or undefined things will happen, and that could be anything, probably a 500 error</p>\n\n<p>So lets update the first bit of code:</p>\n\n<pre><code>$tags = get_the_tags();\n\nif ( is_wp_error( $tags ) ) {\n return; // there was an error\n}\nif ( false === $tags ) {\n return; // there were no tags on this post\n}\n// now we can do stuff with the tags\n</code></pre>\n\n<h2>Convert The Tag into a string</h2>\n\n<p>Nifty, now we have an array of tags. You mentioned there should only be 1 tag, but who knows what plugins might be adding their own tags, so lets make sure your code handles that correctly:</p>\n\n<pre><code>foreach ( $tags as $tag ) {\n // do something with our tag\n break; // exit after the first one\n}\n</code></pre>\n\n<h2>Replace the spaces with dashes</h2>\n\n<p>Each <code>$tag</code> is a <code>WP_Term</code> object, you can use the terms slug with <code>$tag->name</code>, which will already have the URL friendly version</p>\n\n<p>However, why bother? There's a function for that! We can replace this:</p>\n\n<pre><code>echo 'Post by: <a href=\"/meet-the-team/employees/'. $newname .'/\">'. $newname .'</a>';\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>$url = get_term_link( $tag, 'tags' );\necho 'Post by: <a href=\"'.esc_url( $url ).'\">'.esc_html( $tag->name ).'</a>';\n</code></pre>\n\n<p>Notice I added escaping. Escaping is important and will prevent most hacks. Despite it's anti-hacking superpowers, it's almost never applied to WordPress code :(</p>\n"
}
]
| 2017/10/19 | [
"https://wordpress.stackexchange.com/questions/283463",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119096/"
]
| I am trying to get the tags from the post (there will only be one tag), then create a new variable with that tag name but with the spaces replaced with dashes.
This is what a have so far, but I cannot get it to display the value of the tag (both with spaces and without) instead of "Array". In the code below, I'm only trying to get it to display with the dashes right now.
```
$posttags = get_the_tags();
$newname = str_replace(' ', '-', $posttags);
if ($posttags) {
foreach ($posttags as $tag){
echo 'Post by: <a href="/meet-the-team/employees/'. $newname .'/">'. $newname .'</a>';
}
}
``` | Lets break this apart using your question title:
>
> Get the tags as an array, convert the tag into a string, and then replace spaces with dash
>
>
>
Get the tags as an array
------------------------
`get_the_tags` is the correct function, you now have one of 2 things:
* an array of term objects ( a tag is a term in the tags taxonomy )
* `false`, there are no tags on this post
* A `WP_Error` object, something went wrong
So we need to check for those cases, afterall if we assume tags are returned but there are none, what will happen? We have to tell it what will happen or undefined things will happen, and that could be anything, probably a 500 error
So lets update the first bit of code:
```
$tags = get_the_tags();
if ( is_wp_error( $tags ) ) {
return; // there was an error
}
if ( false === $tags ) {
return; // there were no tags on this post
}
// now we can do stuff with the tags
```
Convert The Tag into a string
-----------------------------
Nifty, now we have an array of tags. You mentioned there should only be 1 tag, but who knows what plugins might be adding their own tags, so lets make sure your code handles that correctly:
```
foreach ( $tags as $tag ) {
// do something with our tag
break; // exit after the first one
}
```
Replace the spaces with dashes
------------------------------
Each `$tag` is a `WP_Term` object, you can use the terms slug with `$tag->name`, which will already have the URL friendly version
However, why bother? There's a function for that! We can replace this:
```
echo 'Post by: <a href="/meet-the-team/employees/'. $newname .'/">'. $newname .'</a>';
```
With:
```
$url = get_term_link( $tag, 'tags' );
echo 'Post by: <a href="'.esc_url( $url ).'">'.esc_html( $tag->name ).'</a>';
```
Notice I added escaping. Escaping is important and will prevent most hacks. Despite it's anti-hacking superpowers, it's almost never applied to WordPress code :( |
283,504 | <p>I'm fairly new to WordPress and I'm trying to figure out how to best set up permissions. </p>
<p>I want to restrict groups of people to only edit certain pages (IT department to only edit IT pages, HR department to only edit HR pages and so on). </p>
<p>From what I've read you take away permissions to 'edit others pages' from a role and then set the author of the page to the person you want to edit it. </p>
<p>Is there a standard way to set multiple authors or maybe a way to make a role an author rather than a single user?</p>
<p>Thanks</p>
| [
{
"answer_id": 283464,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>If you use <code>str_replace</code> on an array, you get an array back. So <code>$newname</code> is rightly an array.</p>\n\n<p>You may want to do the <code>str_replace</code> inside your <code>foreach</code> loop instead - that way it works on each individual item and then you display the individual item.</p>\n\n<p>Or, if you keep using <code>str_replace</code> on the full array, you need to change your <code>foreach</code> loop to: <code>foreach($newname as $tag)</code> and echo <code>$tag</code> not <code>$newname</code>.</p>\n"
},
{
"answer_id": 283466,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Lets break this apart using your question title:</p>\n\n<blockquote>\n <p>Get the tags as an array, convert the tag into a string, and then replace spaces with dash</p>\n</blockquote>\n\n<h2>Get the tags as an array</h2>\n\n<p><code>get_the_tags</code> is the correct function, you now have one of 2 things:</p>\n\n<ul>\n<li>an array of term objects ( a tag is a term in the tags taxonomy )</li>\n<li><code>false</code>, there are no tags on this post</li>\n<li>A <code>WP_Error</code> object, something went wrong</li>\n</ul>\n\n<p>So we need to check for those cases, afterall if we assume tags are returned but there are none, what will happen? We have to tell it what will happen or undefined things will happen, and that could be anything, probably a 500 error</p>\n\n<p>So lets update the first bit of code:</p>\n\n<pre><code>$tags = get_the_tags();\n\nif ( is_wp_error( $tags ) ) {\n return; // there was an error\n}\nif ( false === $tags ) {\n return; // there were no tags on this post\n}\n// now we can do stuff with the tags\n</code></pre>\n\n<h2>Convert The Tag into a string</h2>\n\n<p>Nifty, now we have an array of tags. You mentioned there should only be 1 tag, but who knows what plugins might be adding their own tags, so lets make sure your code handles that correctly:</p>\n\n<pre><code>foreach ( $tags as $tag ) {\n // do something with our tag\n break; // exit after the first one\n}\n</code></pre>\n\n<h2>Replace the spaces with dashes</h2>\n\n<p>Each <code>$tag</code> is a <code>WP_Term</code> object, you can use the terms slug with <code>$tag->name</code>, which will already have the URL friendly version</p>\n\n<p>However, why bother? There's a function for that! We can replace this:</p>\n\n<pre><code>echo 'Post by: <a href=\"/meet-the-team/employees/'. $newname .'/\">'. $newname .'</a>';\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>$url = get_term_link( $tag, 'tags' );\necho 'Post by: <a href=\"'.esc_url( $url ).'\">'.esc_html( $tag->name ).'</a>';\n</code></pre>\n\n<p>Notice I added escaping. Escaping is important and will prevent most hacks. Despite it's anti-hacking superpowers, it's almost never applied to WordPress code :(</p>\n"
}
]
| 2017/10/20 | [
"https://wordpress.stackexchange.com/questions/283504",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128158/"
]
| I'm fairly new to WordPress and I'm trying to figure out how to best set up permissions.
I want to restrict groups of people to only edit certain pages (IT department to only edit IT pages, HR department to only edit HR pages and so on).
From what I've read you take away permissions to 'edit others pages' from a role and then set the author of the page to the person you want to edit it.
Is there a standard way to set multiple authors or maybe a way to make a role an author rather than a single user?
Thanks | Lets break this apart using your question title:
>
> Get the tags as an array, convert the tag into a string, and then replace spaces with dash
>
>
>
Get the tags as an array
------------------------
`get_the_tags` is the correct function, you now have one of 2 things:
* an array of term objects ( a tag is a term in the tags taxonomy )
* `false`, there are no tags on this post
* A `WP_Error` object, something went wrong
So we need to check for those cases, afterall if we assume tags are returned but there are none, what will happen? We have to tell it what will happen or undefined things will happen, and that could be anything, probably a 500 error
So lets update the first bit of code:
```
$tags = get_the_tags();
if ( is_wp_error( $tags ) ) {
return; // there was an error
}
if ( false === $tags ) {
return; // there were no tags on this post
}
// now we can do stuff with the tags
```
Convert The Tag into a string
-----------------------------
Nifty, now we have an array of tags. You mentioned there should only be 1 tag, but who knows what plugins might be adding their own tags, so lets make sure your code handles that correctly:
```
foreach ( $tags as $tag ) {
// do something with our tag
break; // exit after the first one
}
```
Replace the spaces with dashes
------------------------------
Each `$tag` is a `WP_Term` object, you can use the terms slug with `$tag->name`, which will already have the URL friendly version
However, why bother? There's a function for that! We can replace this:
```
echo 'Post by: <a href="/meet-the-team/employees/'. $newname .'/">'. $newname .'</a>';
```
With:
```
$url = get_term_link( $tag, 'tags' );
echo 'Post by: <a href="'.esc_url( $url ).'">'.esc_html( $tag->name ).'</a>';
```
Notice I added escaping. Escaping is important and will prevent most hacks. Despite it's anti-hacking superpowers, it's almost never applied to WordPress code :( |
283,528 | <p>I'm adding custom options to my theme using the customizer api. For example:</p>
<pre><code>$wp_customize->add_setting( 'header_textcolor' , array(
'default' => '#000000'
) );
$wp_customize->add_setting( 'footer_textcolor' , array(
'default' => '#333333'
) );
</code></pre>
<p>Is it possible to return an array of all my custom settings from customizer?</p>
| [
{
"answer_id": 283551,
"author": "Misha Rudrastyh",
"author_id": 85985,
"author_profile": "https://wordpress.stackexchange.com/users/85985",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>$all_settings = get_theme_mods();\nprint_r( $all_settings );\n</code></pre>\n"
},
{
"answer_id": 283572,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 2,
"selected": true,
"text": "<p>Yes. You can get an array of all registered settings via <code>$wp_customize->settings()</code>. If you want to display them all you could do this:</p>\n\n<pre><code>if ( is_customize_preview() ) {\n global $wp_customize;\n $theme_mods = array();\n foreach ( $wp_customize->settings() as $setting ) {\n if ( 'theme_mod' === $setting->type ) {\n $theme_mods[ $setting->id ] = $setting->value();\n }\n }\n echo '<pre>' . json_encode( $theme_mods, JSON_PRETTY_PRINT ) . '</pre>';\n}\n</code></pre>\n"
}
]
| 2017/10/20 | [
"https://wordpress.stackexchange.com/questions/283528",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111085/"
]
| I'm adding custom options to my theme using the customizer api. For example:
```
$wp_customize->add_setting( 'header_textcolor' , array(
'default' => '#000000'
) );
$wp_customize->add_setting( 'footer_textcolor' , array(
'default' => '#333333'
) );
```
Is it possible to return an array of all my custom settings from customizer? | Yes. You can get an array of all registered settings via `$wp_customize->settings()`. If you want to display them all you could do this:
```
if ( is_customize_preview() ) {
global $wp_customize;
$theme_mods = array();
foreach ( $wp_customize->settings() as $setting ) {
if ( 'theme_mod' === $setting->type ) {
$theme_mods[ $setting->id ] = $setting->value();
}
}
echo '<pre>' . json_encode( $theme_mods, JSON_PRETTY_PRINT ) . '</pre>';
}
``` |
283,546 | <p>I am trying to implement auto set featured image from my post content and if there is no image in the post content then set a default featured image automatically..</p>
<p>I have tried different code from different source but nothing seems to be working. My post content image is set from other source and these are not hosted in my site wp media library. Could this be a problem ?</p>
<p>I had one code that set featured image once the post is saved and these images was in the Wp library.. But my images are from other third party soruce and set it like this way below</p>
<p><code><img src="google.com/j.jpg" /></code> or like that.. These images are not hosted in my wp media library.</p>
<p>You will have a clear Idea if you see this </p>
<p><a href="https://i.stack.imgur.com/yki71.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yki71.png" alt="enter image description here"></a></p>
<p>So finally what I want is that set a featured image automatically from post content for new created posts and for old posts as well these are already there.. If there is no image in the Post content then just simply set a default image which can be static source..</p>
<p>Thanks in Advance</p>
| [
{
"answer_id": 283548,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": -1,
"selected": false,
"text": "<p>I guess this is something you're looking for, first it checks if post thumbnail is present, otherwise display a fallback image.</p>\n\n<pre><code><?php if(has_post_thumbnail()) : ?>\n <?php the_post_thumanail(); ?>\n<?php else : ?>\n <img src=\"http://via.placeholder.com/1350x450\"/>\n<?php endif; ?>\n</code></pre>\n\n<p><strong>Note</strong>: Replace the image <code>src</code> on the <code>else</code> statement to your static resource.</p>\n"
},
{
"answer_id": 283741,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 2,
"selected": true,
"text": "<p>Ok guys.. I got it finally working with my below code. </p>\n\n<pre><code>function wpse55748_filter_post_thumbnail_html( $html ) {\n\n // If there is no post thumbnail,\n // Return a default image\n global $post;\n $pID = $post->ID;\n $thumb = 'large';\n $imgsrc = FALSE;\n if (has_post_thumbnail()) {\n $imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($pID),$thumb);\n $imgsrc = $imgsrc[0];\n } elseif ($postimages = get_children(\"post_parent=$pID&post_type=attachment&post_mime_type=image&numberposts=0\")) {\n foreach($postimages as $postimage) {\n $imgsrc = wp_get_attachment_image_src($postimage->ID, $thumb);\n $imgsrc = $imgsrc[0];\n }\n } elseif (preg_match('/<img [^>]*src=[\"|\\']([^\"|\\']+)/i', get_the_content(), $match) != FALSE) {\n $imgsrc = $match[1];\n }\n if($imgsrc) {\n $imgsrc = '<img src=\"'.$imgsrc.'\" alt=\"'.get_the_title().'\" class=\"summary-image\" />';\n $html = $imgsrc;\n }\n\n if ( '' == $html ) {\n return '<img src=\"' . get_template_directory_uri() . '/images/default-featured-image.png\" />';\n }\n // Else, return the post thumbnail\n return $html;\n}\nadd_filter( 'post_thumbnail_html', 'wpse55748_filter_post_thumbnail_html' );\n</code></pre>\n\n<p>Here I first search the post content with regex if the content have any kind if \n"
}
]
| 2017/10/20 | [
"https://wordpress.stackexchange.com/questions/283546",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109213/"
]
| I am trying to implement auto set featured image from my post content and if there is no image in the post content then set a default featured image automatically..
I have tried different code from different source but nothing seems to be working. My post content image is set from other source and these are not hosted in my site wp media library. Could this be a problem ?
I had one code that set featured image once the post is saved and these images was in the Wp library.. But my images are from other third party soruce and set it like this way below
`<img src="google.com/j.jpg" />` or like that.. These images are not hosted in my wp media library.
You will have a clear Idea if you see this
[](https://i.stack.imgur.com/yki71.png)
So finally what I want is that set a featured image automatically from post content for new created posts and for old posts as well these are already there.. If there is no image in the Post content then just simply set a default image which can be static source..
Thanks in Advance | Ok guys.. I got it finally working with my below code.
```
function wpse55748_filter_post_thumbnail_html( $html ) {
// If there is no post thumbnail,
// Return a default image
global $post;
$pID = $post->ID;
$thumb = 'large';
$imgsrc = FALSE;
if (has_post_thumbnail()) {
$imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($pID),$thumb);
$imgsrc = $imgsrc[0];
} elseif ($postimages = get_children("post_parent=$pID&post_type=attachment&post_mime_type=image&numberposts=0")) {
foreach($postimages as $postimage) {
$imgsrc = wp_get_attachment_image_src($postimage->ID, $thumb);
$imgsrc = $imgsrc[0];
}
} elseif (preg_match('/<img [^>]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
$imgsrc = $match[1];
}
if($imgsrc) {
$imgsrc = '<img src="'.$imgsrc.'" alt="'.get_the_title().'" class="summary-image" />';
$html = $imgsrc;
}
if ( '' == $html ) {
return '<img src="' . get_template_directory_uri() . '/images/default-featured-image.png" />';
}
// Else, return the post thumbnail
return $html;
}
add_filter( 'post_thumbnail_html', 'wpse55748_filter_post_thumbnail_html' );
```
Here I first search the post content with regex if the content have any kind if |
283,558 | <p>I have created a dashboard widget and this widget will show content which i'll add from an specific page.
So, i created a option page and made a textarea field with wordpress editor.</p>
<pre><code>wp_editor(html_entity_decode(stripcslashes($widget_content)), 'widget_wp_content');
</code></pre>
<p>But when i am calling this field value in widget area than its giving correct image as image not image html. But for caption its showing caption shortcode.like</p>
<pre><code> [caption id="attachment_25613" align="alignnone" width="200"]image display and caption_content[/caption].
</code></pre>
<p>I am using code to print value is</p>
<pre><code>echo html_entity_decode(stripslashes($val['content']));
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 283566,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You need to run it through <code>do_shortcode()</code>. <code>do_shortcode()</code> 'runs' any shortcodes in text passed to it:</p>\n\n<pre><code>echo do_shortcode( html_entity_decode( stripslashes( $val['content'] ) ) );\n</code></pre>\n"
},
{
"answer_id": 283569,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": -1,
"selected": false,
"text": "<p>I think you need to enable shortcode in your widget ?</p>\n\n<pre><code>add_filter('widget_text','do_shortcode');\n</code></pre>\n"
}
]
| 2017/10/20 | [
"https://wordpress.stackexchange.com/questions/283558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102820/"
]
| I have created a dashboard widget and this widget will show content which i'll add from an specific page.
So, i created a option page and made a textarea field with wordpress editor.
```
wp_editor(html_entity_decode(stripcslashes($widget_content)), 'widget_wp_content');
```
But when i am calling this field value in widget area than its giving correct image as image not image html. But for caption its showing caption shortcode.like
```
[caption id="attachment_25613" align="alignnone" width="200"]image display and caption_content[/caption].
```
I am using code to print value is
```
echo html_entity_decode(stripslashes($val['content']));
```
Thanks | You need to run it through `do_shortcode()`. `do_shortcode()` 'runs' any shortcodes in text passed to it:
```
echo do_shortcode( html_entity_decode( stripslashes( $val['content'] ) ) );
``` |
283,575 | <p>I have a site-plugin to centralize most of the theme customization. I want to override the default <em>footer.php</em> template with a <em>customfooter.php</em> (removes the <em>Proudly Powered by WordPress</em>) stored inside the /plugins directory structure. I found <a href="https://wordpress.stackexchange.com/questions/257662/page-templates-from-plugin-not-working-after-upgrading-wp-to-4-7-or-upper-versio#new-answer?newreg=5b288fc8c76248b59434222b98e258ae">this resource on StackExchange</a>, <a href="https://9seeds.com/including-templates-inside-a-plugin/" rel="nofollow noreferrer">one here</a>, and tried some. Obviously, I am making errors. Could someone please advise how to achieve this without touching the theme files / directories?</p>
<pre><code>add_filter( 'theme_page_templates', 'force_customization', 101 );
function force_customization( $newtemplate ) {
if ( is_singular( 'footer' ) ) {
$newtemplate = plugin_dir_path( __FILE__ ) . 'customization/customfooter.php';
}
return $newtemplate;
}
</code></pre>
<p>Any / all help is welcome.</p>
<p>Kind regards</p>
<p>Abhijeet</p>
| [
{
"answer_id": 283566,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You need to run it through <code>do_shortcode()</code>. <code>do_shortcode()</code> 'runs' any shortcodes in text passed to it:</p>\n\n<pre><code>echo do_shortcode( html_entity_decode( stripslashes( $val['content'] ) ) );\n</code></pre>\n"
},
{
"answer_id": 283569,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": -1,
"selected": false,
"text": "<p>I think you need to enable shortcode in your widget ?</p>\n\n<pre><code>add_filter('widget_text','do_shortcode');\n</code></pre>\n"
}
]
| 2017/10/21 | [
"https://wordpress.stackexchange.com/questions/283575",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130012/"
]
| I have a site-plugin to centralize most of the theme customization. I want to override the default *footer.php* template with a *customfooter.php* (removes the *Proudly Powered by WordPress*) stored inside the /plugins directory structure. I found [this resource on StackExchange](https://wordpress.stackexchange.com/questions/257662/page-templates-from-plugin-not-working-after-upgrading-wp-to-4-7-or-upper-versio#new-answer?newreg=5b288fc8c76248b59434222b98e258ae), [one here](https://9seeds.com/including-templates-inside-a-plugin/), and tried some. Obviously, I am making errors. Could someone please advise how to achieve this without touching the theme files / directories?
```
add_filter( 'theme_page_templates', 'force_customization', 101 );
function force_customization( $newtemplate ) {
if ( is_singular( 'footer' ) ) {
$newtemplate = plugin_dir_path( __FILE__ ) . 'customization/customfooter.php';
}
return $newtemplate;
}
```
Any / all help is welcome.
Kind regards
Abhijeet | You need to run it through `do_shortcode()`. `do_shortcode()` 'runs' any shortcodes in text passed to it:
```
echo do_shortcode( html_entity_decode( stripslashes( $val['content'] ) ) );
``` |
283,628 | <p>I have created a child theme for my parent theme. Just added <code>style.css</code> and <code>functions.php</code> files in child theme.</p>
<p>Original Theme Name: Verb Lite (Directory name verb-lite)</p>
<p>I created new folder <code>verb-lite-child</code> in themes folder, added the following files.</p>
<p><code>style.css</code> file</p>
<pre><code>/*
Theme Name: Verb Lite Child Theme
Description: A child theme of the Verb Lite theme
Template: verb-lite
Version: 1.0.0
*/
</code></pre>
<p><code>functions.php</code> file to enqueue parent styles,</p>
<pre><code><?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() .
'/style.css' );
}
?>
</code></pre>
<p>Now when I preview my theme, the styles are broken, the parent styles are not loaded.</p>
<p>Is there anything I missed there.</p>
| [
{
"answer_id": 283629,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>There is wrong <code>$handle</code> for the parent theme you use. Change <code>parent-style</code> to <em>Verb Lite's</em> <code>verb-lite-styles</code>.</p>\n<pre><code><?php\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\nfunction theme_enqueue_styles() {\n wp_enqueue_style(\n 'verb-lite-styles', // See here\n get_template_directory_uri() . '/style.css'\n );\n}\n</code></pre>\n<blockquote>\n<p><code>parent-style</code> is the same <code>$handle</code> used in the parent theme when it registers its stylesheet</p>\n</blockquote>\n<p>(Citation from <a href=\"https://codex.wordpress.org/Child_Themes#Creating_a_Child_Theme_from_an_Unmodified_Parent_Theme\" rel=\"nofollow noreferrer\">Codex</a>)</p>\n<h2>Updated</h2>\n<p>according the OP's self-answer.</p>\n<p><em>Verb Lite's</em> 'enqueue styles' is poorly programmed and doesn't use style dependencies, as could be seen in it's <a href=\"https://themes.trac.wordpress.org/browser/verb-lite/1.1.6/inc/enqueue.php\" rel=\"nofollow noreferrer\"><code>inc/enqueue.php</code></a> file.</p>\n<p>Enqueue all the styles with the respect of their dependencies:</p>\n<pre><code><?php\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\n\nfunction theme_enqueue_styles() {\n\n wp_enqueue_style(\n 'verb-lite-understrap-styles',\n get_template_directory_uri() . '/css/theme.min.css',\n array() // no dependencies\n );\n wp_enqueue_style(\n 'verb-lite-google-fonts',\n 'https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i|Open+Sans:100,300,400,600,700,700italic,600italic,400italic'),\n array(\n 'verb-lite-understrap-styles', // depends on understrap\n )\n );\n wp_enqueue_style(\n 'verb-lite-styles',\n get_template_directory_uri() . '/style.css',\n array(\n 'verb-lite-understrap-styles', // depends on both understrap and Google fonts\n 'verb-lite-google-fonts'\n )\n );\n}\n</code></pre>\n"
},
{
"answer_id": 283631,
"author": "Mann",
"author_id": 114693,
"author_profile": "https://wordpress.stackexchange.com/users/114693",
"pm_score": 1,
"selected": false,
"text": "<p>If I open syyle.css from original theme I see </p>\n\n<p><code>*/\n/* Themely is based off of Understrap which uses the Underscores starter theme merged with the Bootstrap Framework. The default styles can be found in /css/theme.css and /css.theme.min.css.</code> </p>\n\n<p>The styles loaded when I enqueued <code>theme.css</code> ad <code>theme.min.css</code> files.</p>\n\n<p>My <code>functions.php</code> file now</p>\n\n<pre><code><?php\n\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\nfunction theme_enqueue_styles() {\n wp_enqueue_style( 'verb-lite-styles', get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'verb-lite-cssstyles', get_template_directory_uri() . '/css/theme.css' );\n wp_enqueue_style( 'verb-lite-cssMinstyles', get_template_directory_uri() . '/css/theme.min.css' );\n}\n?>\n</code></pre>\n"
}
]
| 2017/10/22 | [
"https://wordpress.stackexchange.com/questions/283628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114693/"
]
| I have created a child theme for my parent theme. Just added `style.css` and `functions.php` files in child theme.
Original Theme Name: Verb Lite (Directory name verb-lite)
I created new folder `verb-lite-child` in themes folder, added the following files.
`style.css` file
```
/*
Theme Name: Verb Lite Child Theme
Description: A child theme of the Verb Lite theme
Template: verb-lite
Version: 1.0.0
*/
```
`functions.php` file to enqueue parent styles,
```
<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() .
'/style.css' );
}
?>
```
Now when I preview my theme, the styles are broken, the parent styles are not loaded.
Is there anything I missed there. | If I open syyle.css from original theme I see
`*/
/* Themely is based off of Understrap which uses the Underscores starter theme merged with the Bootstrap Framework. The default styles can be found in /css/theme.css and /css.theme.min.css.`
The styles loaded when I enqueued `theme.css` ad `theme.min.css` files.
My `functions.php` file now
```
<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'verb-lite-styles', get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'verb-lite-cssstyles', get_template_directory_uri() . '/css/theme.css' );
wp_enqueue_style( 'verb-lite-cssMinstyles', get_template_directory_uri() . '/css/theme.min.css' );
}
?>
``` |
283,664 | <p>Why doesn't the <a href="https://developer.wordpress.org/reference/classes/wp_term_query/__construct/" rel="nofollow noreferrer">get_terms()</a> call return 10 max results as requested? I'm baffled.</p>
<pre><code> $args = array(
'taxonomy' => 'video_tag',
'parent' => 0,
'number' => 10
);
error_log("JPH get_terms args: " . print_r($args,true));
$children = get_terms( $args );
error_log("JPH taxonomy: " . count( $children) . " total");
</code></pre>
<p>Resulting output in log is</p>
<blockquote>
<p>JPH get_terms args: Array\n(\n [parent] => 0\n [number] => 10\n
[taxonomy] => video_tag\n)\n JPH taxonomy: 24806 total</p>
</blockquote>
<p>I'm using PHP 7.1 and WordPress 4.8.2</p>
| [
{
"answer_id": 283667,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<p>Note this condition on the limit part of the <code>WP_Term_Query</code><a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class-wp-term-query.php#L554\" rel=\"nofollow noreferrer\"> [src]</a>:</p>\n\n<pre><code>// Don't limit the query results when we have to descend the family tree.\nif ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {\n if ( $offset ) {\n $limits = 'LIMIT ' . $offset . ',' . $number;\n } else {\n $limits = 'LIMIT ' . $number;\n }\n} else {\n $limits = '';\n}\n</code></pre>\n\n<p>where by default <em>child_of</em> is 0, <em>parent</em> is an empty string and <em>hierarchical</em> is <code>true</code>.</p>\n\n<p>Let's check two cases:</p>\n\n<p><strong>A)</strong> To limit the term results to top-level terms of a <strong>hierarchical</strong> taxonomy, we can use:</p>\n\n<pre><code>$args = [\n 'taxonomy' => 'category',\n 'parent' => 0,\n 'number' => 10,\n];\n</code></pre>\n\n<p>In this case the <code>WP_Term_Query</code> fetches all top-level terms and then uses an array slice [<a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class-wp-term-query.php#L802\" rel=\"nofollow noreferrer\">src</a>] to limit the results, according to the <em>number</em> input. For pagination, we can also add the <em>offset</em>.</p>\n\n<p><strong>B)</strong> In the case of a <strong>non-hierarchical</strong> taxonomy, we can use:</p>\n\n<pre><code>$args = [\n 'taxonomy' => 'post_tag',\n 'number' => 10,\n];\n</code></pre>\n\n<p>where we shouldn't need to explicitly set the <em>parent</em> as 0. Every term is top-level. Here the term results are limited by the <code>LIMIT</code> in the SQL query.</p>\n"
},
{
"answer_id": 284267,
"author": "johnh10",
"author_id": 50675,
"author_profile": "https://wordpress.stackexchange.com/users/50675",
"pm_score": 1,
"selected": false,
"text": "<p>So here's some info for any other people with this issue.</p>\n\n<p><code>get_terms</code> will not use the <code>number</code> parameter under certain conditions, such as if you pass in a <code>parent</code> parameter or if the <code>hierarchical</code> parameter is <code>true</code>. In these cases I have tried two workarounds, neither very good.</p>\n\n<ol>\n<li><p>You can call <code>get_terms</code> then do an <code>array_slice</code> on the results afterwards. However if you have a ton of taxonomies then WordPress can run out of memory during the <code>get_terms</code> call, which was my original issue.</p></li>\n<li><p>You can hook into the filter <code>terms_clauses</code> and force the <code>get_terms</code> call to use a LIMIT in its sql call. However this applies to all calls of <code>get_terms</code> across WordPress and not just the one in my custom code, and I don't want to cause unintended consequences.</p></li>\n</ol>\n"
}
]
| 2017/10/22 | [
"https://wordpress.stackexchange.com/questions/283664",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50675/"
]
| Why doesn't the [get\_terms()](https://developer.wordpress.org/reference/classes/wp_term_query/__construct/) call return 10 max results as requested? I'm baffled.
```
$args = array(
'taxonomy' => 'video_tag',
'parent' => 0,
'number' => 10
);
error_log("JPH get_terms args: " . print_r($args,true));
$children = get_terms( $args );
error_log("JPH taxonomy: " . count( $children) . " total");
```
Resulting output in log is
>
> JPH get\_terms args: Array\n(\n [parent] => 0\n [number] => 10\n
> [taxonomy] => video\_tag\n)\n JPH taxonomy: 24806 total
>
>
>
I'm using PHP 7.1 and WordPress 4.8.2 | So here's some info for any other people with this issue.
`get_terms` will not use the `number` parameter under certain conditions, such as if you pass in a `parent` parameter or if the `hierarchical` parameter is `true`. In these cases I have tried two workarounds, neither very good.
1. You can call `get_terms` then do an `array_slice` on the results afterwards. However if you have a ton of taxonomies then WordPress can run out of memory during the `get_terms` call, which was my original issue.
2. You can hook into the filter `terms_clauses` and force the `get_terms` call to use a LIMIT in its sql call. However this applies to all calls of `get_terms` across WordPress and not just the one in my custom code, and I don't want to cause unintended consequences. |
283,743 | <p>This is my first post here, I am very new to PHP so bare with me. </p>
<p>I need to add USPS's variable shipping rates for priority mail based on cart total. I have tried plugins but none of them work right with the USPS shipping plugin client insists on using and I have maxed budget for buying any other plugins. </p>
<p>I have created a child theme and added a new functions.php. That is the correct way of adding update-proof php correct? </p>
<p>I found a php function on Git that adds a rate based on an over/under cart amount but I need to add more else if conditions for 7 variable cart totals. Below is my best attempt at adding the conditions I need with my very limited knowledge of php. Can someone please help me get this code working? What am I missing to allow for multiple else if conditions? </p>
<pre><code>add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
</code></pre>
<p>function woocommerce_custom_surcharge() {
global $woocommerce;</p>
<pre><code>if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ( strpos($chosen_shipping, 'USPS_Simple_Shipping_Method' ) !== false ) {
// this compare needed since if the string is found at beg of target, it returns '0', which is a false value
$insurance_fee = 0;
if ( $woocommerce->cart->cart_contents_total <= 50 ) {
$insurance_fee = 0;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 50 ) {
$insurance_fee = 2.05;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 100 ) {
$insurance_fee = 2.45;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 200 ) {
$insurance_fee = 4.60;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 300 ) {
$insurance_fee = 5.50;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 400 ) {
$insurance_fee = 6.40;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 500 ) {
$insurance_fee = 7.30;
return;
}
$woocommerce->cart->add_fee( 'Insurance', $insurance_fee, true, '' );
}
return;
</code></pre>
<p>}</p>
| [
{
"answer_id": 283690,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 2,
"selected": false,
"text": "<p>What's keeping you from using the <a href=\"https://docs.woocommerce.com/document/product-csv-importer-exporter/\" rel=\"nofollow noreferrer\">officially documented way to import products from csv</a>? If you're running on an older version, there's <a href=\"https://woocommerce.com/products/product-csv-import-suite/\" rel=\"nofollow noreferrer\">an extension</a> that does the same thing.</p>\n"
},
{
"answer_id": 283691,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>While it's possible to insert the data directly into the Database, it's pretty much work and an error in the insertion / changes in the dataset structure would render the import completely useless, the API would be the better and safer way to insert the products.</p>\n\n<p>However, 5000 Products are a lot, and using one function to insert them all could easily outrun the PHP Execution Time limit. So, if you use a \"manual\" importer (e.g. you click a button and the import runs), the best way of action would be to create an admin screen that works in two steps.</p>\n\n<p>Step 1: Import the CSV and read the datasets. Save the datasets to a temporary database table or a table on the admin screen.</p>\n\n<p>Step 2: Write an Ajax-Function to import 1 Product on the admin screen by API. Include information about which product was successfully (or unsuccessfully) imported in the returned data.</p>\n\n<p>Step 3: Write a jQuery each function that sends only 1 Product at a time to the Ajax-Import-Function. You can use the jQuery timing plugin to ensure that one product each x milliseconds is sent via ajax. Start the function by a click. Now you just have to wait until all the products are imported. If you throw in a progress-bar, you will have a nice visual feedback how many products are imported yet.</p>\n\n<p>The pasted code below is just a general idea of how you can accomplish that. Be aware that the parts where you actually DO SOMETHING with your data is not in it as i a) don't know how your CSV-File is built and b) am too lazy to look up how the woocommerce api works exactly.</p>\n\n<pre><code><?php\nadd_action('admin_menu', 'add_menu_page_for_big_import');\n\nfunction add_menu_page_for_big_import() {\n add_menu_page('Import all the products', 'Imports', 'manage_options', 'product-imports', 'all_the_products_import_output','dashicons-welcome-add-page' ,22);\n}\n\nfunction all_the_products_import_output(){\n wp_enqueue_media();\n wp_enqueue_script('jquery');\n wp_enqueue_script('media-upload');\n wp_enqueue_script('jquery-timing','http://creativecouple.github.io/jquery-timing/jquery-timing.min.js',array('jquery'));\n wp_enqueue_script('jquery-ui-progressbar');\n wp_enqueue_style('jquery-ui-smoothness-style','http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css');\n ?>\n <div class=\"wrap\">\n <?php \n if(isset($_POST['filename'])) {\n //do whatever you need to do with the csv. Import it, put it in an array\n ?>\n <table class=\"imports\">\n <?php\n $import_counter = 0;\n foreach($product_array as $product){\n $import_counter++;\n ?>\n <tr data-prodnumber=\"<?php echo $product['product_number']; ?>\">\n <?php\n foreach($product as $key => $productfield){\n ?>\n <td class=\"<?php echo $key; ?>\"><?php echo $productfield; ?></td>\n <?php\n }\n ?>\n </tr>\n <?php\n }\n ?>\n </table>\n <span class=\"importpreview\"><?php echo $import_counter; ?> Products for import.</span>\n <p>Click the button to start the import. Don't close the window until import is finished.</p>\n <div id=\"progressbar\"></div>\n <p>\n <a class=\"button goimport\" href=\"#\" id=\"import_start\">Start import</a> \n </p>\n <span class=\"resultlabel\">Result: </span><br />\n <span class=\"result\" data-errors=\"0\" data-imported=\"0\">\n Products imported: <span class=\"updated\">0</span><br />\n Errors: <span class=\"error\">0</span>\n </span><br />\n <script>\n var progressbar;\n var aktval = 0;\n jQuery(document).ready(function($){\n progressbar = $('#progressbar').progressbar({\n max: <?php echo $import_counter; ?>\n });\n });\n </script>\n <?php\n } else {\n ?>\n <h2>Import Products</h2>\n<form name=\"import_form\" method=\"post\" action=\"<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>\">\n <label for=\"filename\">CSV-File</label>\n <input id=\"upload_txt\" type=\"text\" name=\"filename\" value=\"\" />\n <input id=\"upload_button\" type=\"button\" value=\"upload csv file\" />\n <input type=\"submit\" value=\"next step\" />\n</form>\n<?php } ?>\n<script>\n jQuery(document).ready(function($) {\n $('.goimport').click(function(event){\n event.preventDefault();\n var mycounter = 0;\n $('table.importdata tr').each($).wait(500,function(){\n //by using the wait command (supplied by the jquery timing plugin), we ensure that not all the\n //products are sent at once, but only every .5 seconds\n mycounter++;\n postdata = new Object();\n postdata['action'] = 'import_all_the_products_action';\n //put into the postdata all the data from the table you need like this:\n postdata['keyname'] = $(this).find('td.keyname').html();\n $.post(ajaxurl, postdata, function(response){\n if(response.message == 'SUCCESS'){\n $('span.result').data('imported',parseInt($('span.result').data('imported'))+1);\n $('span.result .updated').html(parseInt($('span.result .updated').html())+1);\n }else if(response.message == 'ERROR'){\n $('span.result').data('errors',parseInt($('span.result').data('errors'))+1);\n $('span.result .error').html(parseInt($('span.result .error').html())+1);\n }\n aktval++;\n progressbar.progressbar( \"value\", aktval );\n },\"json\");\n }\n });\n });\n var _custom_media = true,\n _orig_send_attachment = wp.media.editor.send.attachment;\n $('#upload_button').click(function(e) {\n var send_attachment_bkp = wp.media.editor.send.attachment;\n var button = $(this);\n _custom_media = true;\n wp.media.editor.send.attachment = function(props, attachment){\n if ( _custom_media ) {\n $(\"#upload_txt\").val(attachment.url);\n } else {\n return _orig_send_attachment.apply( this, [props, attachment] );\n };\n }\n wp.media.editor.open(button);\n return false;\n });\n });\n </script>\n</div>\n<?php \n}\n\nadd_action( 'wp_ajax_import_all_the_products_action', 'import_products_ajax_action' );\n\nfunction import_products_ajax_action() {\n //get all the data you need from the $_POST Variable like this.\n $keyname = $_POST['keyname'];\n //do whatever you need to do with the product data. Import by api, or whatever.\n //put $success to true to give the info back to the admin screen\n //in $data, you can give back additional data\n if($success){\n echo json_encode(array('message' => 'SUCCESS','data' => $data));\n die();\n } else {\n echo json_encode(array('message' => 'ERROR','data' => $data));\n die();\n }\n}\n</code></pre>\n"
}
]
| 2017/10/23 | [
"https://wordpress.stackexchange.com/questions/283743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129936/"
]
| This is my first post here, I am very new to PHP so bare with me.
I need to add USPS's variable shipping rates for priority mail based on cart total. I have tried plugins but none of them work right with the USPS shipping plugin client insists on using and I have maxed budget for buying any other plugins.
I have created a child theme and added a new functions.php. That is the correct way of adding update-proof php correct?
I found a php function on Git that adds a rate based on an over/under cart amount but I need to add more else if conditions for 7 variable cart totals. Below is my best attempt at adding the conditions I need with my very limited knowledge of php. Can someone please help me get this code working? What am I missing to allow for multiple else if conditions?
```
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
```
function woocommerce\_custom\_surcharge() {
global $woocommerce;
```
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ( strpos($chosen_shipping, 'USPS_Simple_Shipping_Method' ) !== false ) {
// this compare needed since if the string is found at beg of target, it returns '0', which is a false value
$insurance_fee = 0;
if ( $woocommerce->cart->cart_contents_total <= 50 ) {
$insurance_fee = 0;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 50 ) {
$insurance_fee = 2.05;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 100 ) {
$insurance_fee = 2.45;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 200 ) {
$insurance_fee = 4.60;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 300 ) {
$insurance_fee = 5.50;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 400 ) {
$insurance_fee = 6.40;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 500 ) {
$insurance_fee = 7.30;
return;
}
$woocommerce->cart->add_fee( 'Insurance', $insurance_fee, true, '' );
}
return;
```
} | What's keeping you from using the [officially documented way to import products from csv](https://docs.woocommerce.com/document/product-csv-importer-exporter/)? If you're running on an older version, there's [an extension](https://woocommerce.com/products/product-csv-import-suite/) that does the same thing. |
283,828 | <p>In order to avoid poor performance with multiple <code><script></code> tags I do concatenation of scripts regularly and produce one single <code>bundle.min.js</code> JS file and <code>'jsbundle'</code> identifier.</p>
<p>Problem is, things added subsequently, like plugins, may depend on registered one or more libraries that <strong>are present</strong>, but packed in generic <code>'jsbundle'</code>. </p>
<p>Is there a way to inform Wordpress that <code>'jsbundle'</code> implies, for example <code>'jquery'</code>, <code>'backbone'</code>, ... in order for 1) resource not being loaded twice 2) things not failing because of unfulfilled dependency
<strong>?</strong></p>
<p>I've tried with source of <code>wp_register_script</code>, found <code>WP_Scripts()</code> class and tried to "lie" WP about available scripts, yet no luck.</p>
| [
{
"answer_id": 284521,
"author": "Levi Dulstein",
"author_id": 101988,
"author_profile": "https://wordpress.stackexchange.com/users/101988",
"pm_score": 0,
"selected": false,
"text": "<p>The solution proposed by Alexander looks reasonable. You can keep all minified dependencies (libs.js in my example) in one file and your scripts in second file like so:</p>\n\n<pre><code>wp_enqueue_script( 'libs', get_template_directory_uri() . '/assets/js/libs.js', [], '1.0.0', true );\n\n// third parameter here will make sure that libs.js is loaded before jsbundle:\n\nwp_enqueue_script( 'jsbundle', get_template_directory_uri() . '/assets/js/jsbundle.min.js', [ 'libs' ], '1.0.0', true );\n</code></pre>\n\n<p>Even though bundling scripts is a well known practice for optimising page load speed and is a good idea most of the time, it might not always be the most performant solution. I would always consider some other options and decide what works best for particular use case.</p>\n\n<h2>CDN</h2>\n\n<p>You might wanna use one of available CDN's for your third party libraries to get all advantages that are listed <a href=\"https://stackoverflow.com/questions/2180391/why-should-i-use-googles-cdn-for-jquery\">in this answer</a>. </p>\n\n<p>E.g. If you use Google's or Facebook's CDN, there is a big chance, that your visitors already got popular scripts cached in their browsers and wouldn't need to download it again. </p>\n\n<p>In that case, bundling 3rd party scripts takes away this advantage, and the whole bundle needs to be downloaded, even if the user has part of it already saved in browser's cache.</p>\n\n<p>You can easily enqueue scripts from CDN with <code>wp_enqueue_script()</code>, just omit the <code>$ver</code> parameter, 'cause you don't want to refresh the cached script:</p>\n\n<pre><code>wp_enqueue_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', [], null, true );\n</code></pre>\n\n<h2>Conditional tags</h2>\n\n<p>The other thing I would consider is registering more scripts and calling them only on pages where they are actually used. This works well especially if you update your scripts often.</p>\n\n<p>If you keep all scripts in a bundle, applying one little changes requires busting cache for the whole script. Sometimes it might be better to keep parts of your scripts separated, so you can change version only for the chunk that you actually edited. </p>\n\n<p>Let's say I use <code>foo.js</code> script on my homepage and there's not much going on there so I don't plan to change it anytime soon, but at the same time I have a complicated <code>bar.js</code> script that I need to maintain and refresh often. In that case it might be better to register scripts separately.</p>\n\n<p>Also, some of your libraries might be used only on subpages that are not visited very often (let's say I use <code>masonry</code> on one less popular subpage), so preloading them on your home page might not be the way to go. In that case I'd do:\n // register masonry but don't enqueue it just yet\n wp_register_script( 'masonry', get_template_directory_uri() . '/assets/js/masonry.min.js', [], 1.0, true );</p>\n\n<pre><code>// foo.js is my implementation of masonry.js\nwp_register_script( 'foo.js', get_template_directory_uri() . '/assets/js/masonry.min.js', [ 'masonry' ], 1.0, true );\n\n// in bar.js I keep functions used all over my page so I enqueue it everywhere immediately\nwp_enqueue_script( 'bar.js', get_template_directory_uri() . '/assets/js/masonry.min.js', [], 1.0, true );\n\n// masonry.js and foo.js can wait until the user reaches my less popular subpage as it won't be needed most of the time\nif ( is_post_type_archive( 'unpopular-posts' ) ){\n wp_enqueue_script( 'foo.js' );\n}\n</code></pre>\n"
},
{
"answer_id": 284532,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 3,
"selected": true,
"text": "<p>To have the JavaScript Libraries not to load since you already created a bundle of them, do the following:</p>\n\n<p>Asumming the following, usual enqueue:</p>\n\n<pre><code>function the_js() {\n wp_enqueue_script('bundle_js', get_template_directory_uri() . '/js/bundle.js', array(), false, false);\n}\n\nadd_action('wp_enqueue_scripts', 'the_js');\n</code></pre>\n\n<p>and lets say you have in your bundle the following libraries (listing the handles):</p>\n\n<ol>\n<li><code>jquery</code></li>\n<li><code>backbone</code></li>\n<li><code>colorpicker</code> </li>\n<li><code>bootstrap_js</code></li>\n</ol>\n\n<p>1,2,3 are already in core, 4 is a third party, you bundled all 4 because you dont want the 4 to be loaded as separate resources.</p>\n\n<p>You have to deregister (if they are registered, core ones would be already) and register each one of them, each one of the libraries that are in your bundle:</p>\n\n<pre><code>function the_js() {\n wp_enqueue_script('bundle_js', get_template_directory_uri() . '/js/bundle.js', array(), false, false);\n\n //DEREGISTER the SCRIPTS THAT ARE IN YOUR BUNDLE\n wp_deregister_script('jquery'); //because its a Core-Registered Script\n wp_deregister_script('backbone'); //because its a Core-Registered Script\n wp_deregister_script('colorpicker'); //because its a Core-Registered Script\n\n //REGISTER THEM THIS TIME USING YOUR BUNDLE AS DEPENDENCY\n wp_register_script('jquery', FALSE, array('bundle_js'), '', FALSE);//THE KEY HERE IS THE SRC BEING FALSE\n wp_register_script('backbone', FALSE, array('bundle_js'), '', FALSE);\n wp_register_script('colorpicker', FALSE, array('bundle_js'), '', FALSE);\n\n}\n\nadd_action('wp_enqueue_scripts', 'the_js');\n</code></pre>\n\n<p>the key here is to set the <code>$src</code> as <code>FALSE</code> so the registered script will be an alias, check <a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-scripts.php#L327\" rel=\"nofollow noreferrer\">this line</a> in the core code:</p>\n\n<pre><code>// A single item may alias a set of items, by having dependencies, but no source.\nif ( ! $obj->src ) {\n return true;\n}\n</code></pre>\n\n<p>its what currently <code>jquery</code> does, when putting <code>jquery</code> as a dependency, it doesnt load <code>jquery</code> it loads <code>jquery-core</code> and <code>jquery-migrate</code>, this is the registered object for <code>jquery</code>:</p>\n\n<pre><code>object(_WP_Dependency)#329 (6) {\n [\"handle\"]=>\n string(6) \"jquery\"\n [\"src\"]=>\n bool(false)\n [\"deps\"]=>\n array(2) {\n [0]=>\n string(11) \"jquery-core\"\n [1]=>\n string(14) \"jquery-migrate\"\n }\n [\"ver\"]=>\n string(6) \"1.12.4\"\n [\"args\"]=>\n NULL\n [\"extra\"]=>\n array(0) {\n }\n}\n</code></pre>\n\n<p>so, <code>bundle_js</code> its going to be loaded when a script has as dependency of any of the libraries (<code>jquery</code>, <code>backbone</code>, <code>colorpicker</code>) and it will be loaded 1 time, since the logic in <code>WP_Dependencies</code> checks if its already in the <code>queue</code> array.</p>\n\n<p>If you want to check if a script is already registered use:</p>\n\n<pre><code>global $wp_scripts;\n$wp_scripts->query('jquery'); //jquery as example handle\n</code></pre>\n\n<p>it will return a <code>WP_dependency</code> object if its registered, <code>false</code> if its not.</p>\n\n<p>Some links for further understanding:<br>\n<a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-dependencies.php\" rel=\"nofollow noreferrer\">class.wp-dependencies.php</a><br>\n<a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-scripts.php\" rel=\"nofollow noreferrer\">class.wp-scripts.php</a><br>\n<a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/functions.wp-scripts.php\" rel=\"nofollow noreferrer\">functions.wp-scripts.php</a></p>\n"
},
{
"answer_id": 284550,
"author": "Levi Dulstein",
"author_id": 101988,
"author_profile": "https://wordpress.stackexchange.com/users/101988",
"pm_score": 0,
"selected": false,
"text": "<p>Quick exchange with @janh under my previous answer inspired me to think about different approach. I would still go with minifying all third party libraries to one separate bundle file (<code>bundlejs</code>), and then work with with global <code>$wp_scripts</code> variable (credit for that idea goes to <a href=\"https://stackoverflow.com/questions/20101896/proper-way-to-replace-enqueued-scripts-in-wordpress\">this thread</a>)</p>\n\n<p>It's never going to be fully automated - as Janh noticed, it's impossible to predict how other people would call the scripts in their plugins or themes. In my function I use an array of script names that my bundle file contains. To double the chances of hitting possible duplicates, I added also the support for script file names instead of handles only.</p>\n\n<p>Bear in mind that some admin scripts shouldn't be touched at all (see <a href=\"https://developer.wordpress.org/reference/functions/wp_deregister_script/\" rel=\"nofollow noreferrer\">codex</a>)</p>\n\n<p>Solution is pretty raw, I'm sure it can be perfected in many ways, definitely could use some refactoring and WP cache support. \nAlso I'm not sure how it affects performance in real life case. But it's here for you to get the general idea and maybe some inspiration:</p>\n\n<pre><code>function switch_dependencies_to_bundle(){\n global $wp_scripts;\n\n /**\n * array of scripts that our bundle file contains - can be either script name or handle name\n * it's never going to be bulletproof tho', as plugin authors can change file names, i.e.\n * include other version of script\n */\n $bundled = [\n 'jquery',\n 'masonry',\n 'masonry-js',\n 'masonry.js',\n 'masonry.min.js', //we can use file name too\n 'backbone',\n 'backbone.min.js'\n ];\n\n $deps_to_remove = [];\n\n // register our bundle script\n wp_register_script( 'bundlejs', get_template_directory_uri() . '/assets/js/bundle.min.js', [], '1.0.0', true );\n wp_enqueue_script( 'bundlejs' );\n\n // get registered scripts that our bundle file would duplicate\n foreach( $wp_scripts->registered as $handle => $script ){\n $file_name = substr( $script->src , strrpos( $script->src, \"/\" ) + 1 );\n if ( in_array( $handle, $bundled, true ) || in_array( $file_name, $bundled, true ) ){\n $deps_to_remove[] = $handle;\n }\n }\n\n //get rid of redundant scripts with deregister and dequeue.\n //NOTE: does not work for some admin scripts, see codex\n foreach( $deps_to_remove as $script ){\n wp_deregister_script( $script );\n wp_dequeue_script( $script );\n }\n\n // take care of remaining scripts' dependencies (they wouldn't load with deps missing)\n // add our bundle as dependency, as it contains the same scripts that we just removed\n foreach( $wp_scripts->registered as $script ){\n if ( ! empty( array_intersect( $deps_to_remove, $script->deps ) ) ) {\n $script->deps[] = 'bundlejs';\n $script->deps = array_diff( $script->deps, $deps_to_remove );\n }\n }\n}\n\n// load the function with high priority so it kickes in after other plugins registered their scripts\nadd_action('wp_enqueue_scripts', 'switch_dependencies_to_bundle', 9999);\n</code></pre>\n"
}
]
| 2017/10/24 | [
"https://wordpress.stackexchange.com/questions/283828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20317/"
]
| In order to avoid poor performance with multiple `<script>` tags I do concatenation of scripts regularly and produce one single `bundle.min.js` JS file and `'jsbundle'` identifier.
Problem is, things added subsequently, like plugins, may depend on registered one or more libraries that **are present**, but packed in generic `'jsbundle'`.
Is there a way to inform Wordpress that `'jsbundle'` implies, for example `'jquery'`, `'backbone'`, ... in order for 1) resource not being loaded twice 2) things not failing because of unfulfilled dependency
**?**
I've tried with source of `wp_register_script`, found `WP_Scripts()` class and tried to "lie" WP about available scripts, yet no luck. | To have the JavaScript Libraries not to load since you already created a bundle of them, do the following:
Asumming the following, usual enqueue:
```
function the_js() {
wp_enqueue_script('bundle_js', get_template_directory_uri() . '/js/bundle.js', array(), false, false);
}
add_action('wp_enqueue_scripts', 'the_js');
```
and lets say you have in your bundle the following libraries (listing the handles):
1. `jquery`
2. `backbone`
3. `colorpicker`
4. `bootstrap_js`
1,2,3 are already in core, 4 is a third party, you bundled all 4 because you dont want the 4 to be loaded as separate resources.
You have to deregister (if they are registered, core ones would be already) and register each one of them, each one of the libraries that are in your bundle:
```
function the_js() {
wp_enqueue_script('bundle_js', get_template_directory_uri() . '/js/bundle.js', array(), false, false);
//DEREGISTER the SCRIPTS THAT ARE IN YOUR BUNDLE
wp_deregister_script('jquery'); //because its a Core-Registered Script
wp_deregister_script('backbone'); //because its a Core-Registered Script
wp_deregister_script('colorpicker'); //because its a Core-Registered Script
//REGISTER THEM THIS TIME USING YOUR BUNDLE AS DEPENDENCY
wp_register_script('jquery', FALSE, array('bundle_js'), '', FALSE);//THE KEY HERE IS THE SRC BEING FALSE
wp_register_script('backbone', FALSE, array('bundle_js'), '', FALSE);
wp_register_script('colorpicker', FALSE, array('bundle_js'), '', FALSE);
}
add_action('wp_enqueue_scripts', 'the_js');
```
the key here is to set the `$src` as `FALSE` so the registered script will be an alias, check [this line](https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-scripts.php#L327) in the core code:
```
// A single item may alias a set of items, by having dependencies, but no source.
if ( ! $obj->src ) {
return true;
}
```
its what currently `jquery` does, when putting `jquery` as a dependency, it doesnt load `jquery` it loads `jquery-core` and `jquery-migrate`, this is the registered object for `jquery`:
```
object(_WP_Dependency)#329 (6) {
["handle"]=>
string(6) "jquery"
["src"]=>
bool(false)
["deps"]=>
array(2) {
[0]=>
string(11) "jquery-core"
[1]=>
string(14) "jquery-migrate"
}
["ver"]=>
string(6) "1.12.4"
["args"]=>
NULL
["extra"]=>
array(0) {
}
}
```
so, `bundle_js` its going to be loaded when a script has as dependency of any of the libraries (`jquery`, `backbone`, `colorpicker`) and it will be loaded 1 time, since the logic in `WP_Dependencies` checks if its already in the `queue` array.
If you want to check if a script is already registered use:
```
global $wp_scripts;
$wp_scripts->query('jquery'); //jquery as example handle
```
it will return a `WP_dependency` object if its registered, `false` if its not.
Some links for further understanding:
[class.wp-dependencies.php](https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-dependencies.php)
[class.wp-scripts.php](https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-scripts.php)
[functions.wp-scripts.php](https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/functions.wp-scripts.php) |
283,830 | <p>I want to loop my posts into a 2 column grid, but if there is an odd number of posts, there is an empty space on the even side of the grid. </p>
<p>How could I get an image to appear in this empty space <em>only</em> if there are an odd number of posts? So it would be:</p>
<pre><code>Post 1 | Post 2
Post 3 | img
</code></pre>
<p>I tried using <a href="https://wordpress.stackexchange.com/questions/90081/if-loop-has-odd-number-of-posts-on-last-page-custom-style-for-last-post-in-it">the code here</a>, but not sure how to apply the <code>Modulo</code> Operator because the image should appear after the loop, no?</p>
<p>If my code is super basic like:</p>
<pre><code><div class="small-12 large-6 columns end">
<?php if (have_posts()): while (have_posts()) : the_post(); ?>
Post title, thumbnail, excerpt, etc
<?php endwhile; endif; ?>
</div>
</code></pre>
| [
{
"answer_id": 284521,
"author": "Levi Dulstein",
"author_id": 101988,
"author_profile": "https://wordpress.stackexchange.com/users/101988",
"pm_score": 0,
"selected": false,
"text": "<p>The solution proposed by Alexander looks reasonable. You can keep all minified dependencies (libs.js in my example) in one file and your scripts in second file like so:</p>\n\n<pre><code>wp_enqueue_script( 'libs', get_template_directory_uri() . '/assets/js/libs.js', [], '1.0.0', true );\n\n// third parameter here will make sure that libs.js is loaded before jsbundle:\n\nwp_enqueue_script( 'jsbundle', get_template_directory_uri() . '/assets/js/jsbundle.min.js', [ 'libs' ], '1.0.0', true );\n</code></pre>\n\n<p>Even though bundling scripts is a well known practice for optimising page load speed and is a good idea most of the time, it might not always be the most performant solution. I would always consider some other options and decide what works best for particular use case.</p>\n\n<h2>CDN</h2>\n\n<p>You might wanna use one of available CDN's for your third party libraries to get all advantages that are listed <a href=\"https://stackoverflow.com/questions/2180391/why-should-i-use-googles-cdn-for-jquery\">in this answer</a>. </p>\n\n<p>E.g. If you use Google's or Facebook's CDN, there is a big chance, that your visitors already got popular scripts cached in their browsers and wouldn't need to download it again. </p>\n\n<p>In that case, bundling 3rd party scripts takes away this advantage, and the whole bundle needs to be downloaded, even if the user has part of it already saved in browser's cache.</p>\n\n<p>You can easily enqueue scripts from CDN with <code>wp_enqueue_script()</code>, just omit the <code>$ver</code> parameter, 'cause you don't want to refresh the cached script:</p>\n\n<pre><code>wp_enqueue_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', [], null, true );\n</code></pre>\n\n<h2>Conditional tags</h2>\n\n<p>The other thing I would consider is registering more scripts and calling them only on pages where they are actually used. This works well especially if you update your scripts often.</p>\n\n<p>If you keep all scripts in a bundle, applying one little changes requires busting cache for the whole script. Sometimes it might be better to keep parts of your scripts separated, so you can change version only for the chunk that you actually edited. </p>\n\n<p>Let's say I use <code>foo.js</code> script on my homepage and there's not much going on there so I don't plan to change it anytime soon, but at the same time I have a complicated <code>bar.js</code> script that I need to maintain and refresh often. In that case it might be better to register scripts separately.</p>\n\n<p>Also, some of your libraries might be used only on subpages that are not visited very often (let's say I use <code>masonry</code> on one less popular subpage), so preloading them on your home page might not be the way to go. In that case I'd do:\n // register masonry but don't enqueue it just yet\n wp_register_script( 'masonry', get_template_directory_uri() . '/assets/js/masonry.min.js', [], 1.0, true );</p>\n\n<pre><code>// foo.js is my implementation of masonry.js\nwp_register_script( 'foo.js', get_template_directory_uri() . '/assets/js/masonry.min.js', [ 'masonry' ], 1.0, true );\n\n// in bar.js I keep functions used all over my page so I enqueue it everywhere immediately\nwp_enqueue_script( 'bar.js', get_template_directory_uri() . '/assets/js/masonry.min.js', [], 1.0, true );\n\n// masonry.js and foo.js can wait until the user reaches my less popular subpage as it won't be needed most of the time\nif ( is_post_type_archive( 'unpopular-posts' ) ){\n wp_enqueue_script( 'foo.js' );\n}\n</code></pre>\n"
},
{
"answer_id": 284532,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 3,
"selected": true,
"text": "<p>To have the JavaScript Libraries not to load since you already created a bundle of them, do the following:</p>\n\n<p>Asumming the following, usual enqueue:</p>\n\n<pre><code>function the_js() {\n wp_enqueue_script('bundle_js', get_template_directory_uri() . '/js/bundle.js', array(), false, false);\n}\n\nadd_action('wp_enqueue_scripts', 'the_js');\n</code></pre>\n\n<p>and lets say you have in your bundle the following libraries (listing the handles):</p>\n\n<ol>\n<li><code>jquery</code></li>\n<li><code>backbone</code></li>\n<li><code>colorpicker</code> </li>\n<li><code>bootstrap_js</code></li>\n</ol>\n\n<p>1,2,3 are already in core, 4 is a third party, you bundled all 4 because you dont want the 4 to be loaded as separate resources.</p>\n\n<p>You have to deregister (if they are registered, core ones would be already) and register each one of them, each one of the libraries that are in your bundle:</p>\n\n<pre><code>function the_js() {\n wp_enqueue_script('bundle_js', get_template_directory_uri() . '/js/bundle.js', array(), false, false);\n\n //DEREGISTER the SCRIPTS THAT ARE IN YOUR BUNDLE\n wp_deregister_script('jquery'); //because its a Core-Registered Script\n wp_deregister_script('backbone'); //because its a Core-Registered Script\n wp_deregister_script('colorpicker'); //because its a Core-Registered Script\n\n //REGISTER THEM THIS TIME USING YOUR BUNDLE AS DEPENDENCY\n wp_register_script('jquery', FALSE, array('bundle_js'), '', FALSE);//THE KEY HERE IS THE SRC BEING FALSE\n wp_register_script('backbone', FALSE, array('bundle_js'), '', FALSE);\n wp_register_script('colorpicker', FALSE, array('bundle_js'), '', FALSE);\n\n}\n\nadd_action('wp_enqueue_scripts', 'the_js');\n</code></pre>\n\n<p>the key here is to set the <code>$src</code> as <code>FALSE</code> so the registered script will be an alias, check <a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-scripts.php#L327\" rel=\"nofollow noreferrer\">this line</a> in the core code:</p>\n\n<pre><code>// A single item may alias a set of items, by having dependencies, but no source.\nif ( ! $obj->src ) {\n return true;\n}\n</code></pre>\n\n<p>its what currently <code>jquery</code> does, when putting <code>jquery</code> as a dependency, it doesnt load <code>jquery</code> it loads <code>jquery-core</code> and <code>jquery-migrate</code>, this is the registered object for <code>jquery</code>:</p>\n\n<pre><code>object(_WP_Dependency)#329 (6) {\n [\"handle\"]=>\n string(6) \"jquery\"\n [\"src\"]=>\n bool(false)\n [\"deps\"]=>\n array(2) {\n [0]=>\n string(11) \"jquery-core\"\n [1]=>\n string(14) \"jquery-migrate\"\n }\n [\"ver\"]=>\n string(6) \"1.12.4\"\n [\"args\"]=>\n NULL\n [\"extra\"]=>\n array(0) {\n }\n}\n</code></pre>\n\n<p>so, <code>bundle_js</code> its going to be loaded when a script has as dependency of any of the libraries (<code>jquery</code>, <code>backbone</code>, <code>colorpicker</code>) and it will be loaded 1 time, since the logic in <code>WP_Dependencies</code> checks if its already in the <code>queue</code> array.</p>\n\n<p>If you want to check if a script is already registered use:</p>\n\n<pre><code>global $wp_scripts;\n$wp_scripts->query('jquery'); //jquery as example handle\n</code></pre>\n\n<p>it will return a <code>WP_dependency</code> object if its registered, <code>false</code> if its not.</p>\n\n<p>Some links for further understanding:<br>\n<a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-dependencies.php\" rel=\"nofollow noreferrer\">class.wp-dependencies.php</a><br>\n<a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-scripts.php\" rel=\"nofollow noreferrer\">class.wp-scripts.php</a><br>\n<a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/functions.wp-scripts.php\" rel=\"nofollow noreferrer\">functions.wp-scripts.php</a></p>\n"
},
{
"answer_id": 284550,
"author": "Levi Dulstein",
"author_id": 101988,
"author_profile": "https://wordpress.stackexchange.com/users/101988",
"pm_score": 0,
"selected": false,
"text": "<p>Quick exchange with @janh under my previous answer inspired me to think about different approach. I would still go with minifying all third party libraries to one separate bundle file (<code>bundlejs</code>), and then work with with global <code>$wp_scripts</code> variable (credit for that idea goes to <a href=\"https://stackoverflow.com/questions/20101896/proper-way-to-replace-enqueued-scripts-in-wordpress\">this thread</a>)</p>\n\n<p>It's never going to be fully automated - as Janh noticed, it's impossible to predict how other people would call the scripts in their plugins or themes. In my function I use an array of script names that my bundle file contains. To double the chances of hitting possible duplicates, I added also the support for script file names instead of handles only.</p>\n\n<p>Bear in mind that some admin scripts shouldn't be touched at all (see <a href=\"https://developer.wordpress.org/reference/functions/wp_deregister_script/\" rel=\"nofollow noreferrer\">codex</a>)</p>\n\n<p>Solution is pretty raw, I'm sure it can be perfected in many ways, definitely could use some refactoring and WP cache support. \nAlso I'm not sure how it affects performance in real life case. But it's here for you to get the general idea and maybe some inspiration:</p>\n\n<pre><code>function switch_dependencies_to_bundle(){\n global $wp_scripts;\n\n /**\n * array of scripts that our bundle file contains - can be either script name or handle name\n * it's never going to be bulletproof tho', as plugin authors can change file names, i.e.\n * include other version of script\n */\n $bundled = [\n 'jquery',\n 'masonry',\n 'masonry-js',\n 'masonry.js',\n 'masonry.min.js', //we can use file name too\n 'backbone',\n 'backbone.min.js'\n ];\n\n $deps_to_remove = [];\n\n // register our bundle script\n wp_register_script( 'bundlejs', get_template_directory_uri() . '/assets/js/bundle.min.js', [], '1.0.0', true );\n wp_enqueue_script( 'bundlejs' );\n\n // get registered scripts that our bundle file would duplicate\n foreach( $wp_scripts->registered as $handle => $script ){\n $file_name = substr( $script->src , strrpos( $script->src, \"/\" ) + 1 );\n if ( in_array( $handle, $bundled, true ) || in_array( $file_name, $bundled, true ) ){\n $deps_to_remove[] = $handle;\n }\n }\n\n //get rid of redundant scripts with deregister and dequeue.\n //NOTE: does not work for some admin scripts, see codex\n foreach( $deps_to_remove as $script ){\n wp_deregister_script( $script );\n wp_dequeue_script( $script );\n }\n\n // take care of remaining scripts' dependencies (they wouldn't load with deps missing)\n // add our bundle as dependency, as it contains the same scripts that we just removed\n foreach( $wp_scripts->registered as $script ){\n if ( ! empty( array_intersect( $deps_to_remove, $script->deps ) ) ) {\n $script->deps[] = 'bundlejs';\n $script->deps = array_diff( $script->deps, $deps_to_remove );\n }\n }\n}\n\n// load the function with high priority so it kickes in after other plugins registered their scripts\nadd_action('wp_enqueue_scripts', 'switch_dependencies_to_bundle', 9999);\n</code></pre>\n"
}
]
| 2017/10/24 | [
"https://wordpress.stackexchange.com/questions/283830",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54745/"
]
| I want to loop my posts into a 2 column grid, but if there is an odd number of posts, there is an empty space on the even side of the grid.
How could I get an image to appear in this empty space *only* if there are an odd number of posts? So it would be:
```
Post 1 | Post 2
Post 3 | img
```
I tried using [the code here](https://wordpress.stackexchange.com/questions/90081/if-loop-has-odd-number-of-posts-on-last-page-custom-style-for-last-post-in-it), but not sure how to apply the `Modulo` Operator because the image should appear after the loop, no?
If my code is super basic like:
```
<div class="small-12 large-6 columns end">
<?php if (have_posts()): while (have_posts()) : the_post(); ?>
Post title, thumbnail, excerpt, etc
<?php endwhile; endif; ?>
</div>
``` | To have the JavaScript Libraries not to load since you already created a bundle of them, do the following:
Asumming the following, usual enqueue:
```
function the_js() {
wp_enqueue_script('bundle_js', get_template_directory_uri() . '/js/bundle.js', array(), false, false);
}
add_action('wp_enqueue_scripts', 'the_js');
```
and lets say you have in your bundle the following libraries (listing the handles):
1. `jquery`
2. `backbone`
3. `colorpicker`
4. `bootstrap_js`
1,2,3 are already in core, 4 is a third party, you bundled all 4 because you dont want the 4 to be loaded as separate resources.
You have to deregister (if they are registered, core ones would be already) and register each one of them, each one of the libraries that are in your bundle:
```
function the_js() {
wp_enqueue_script('bundle_js', get_template_directory_uri() . '/js/bundle.js', array(), false, false);
//DEREGISTER the SCRIPTS THAT ARE IN YOUR BUNDLE
wp_deregister_script('jquery'); //because its a Core-Registered Script
wp_deregister_script('backbone'); //because its a Core-Registered Script
wp_deregister_script('colorpicker'); //because its a Core-Registered Script
//REGISTER THEM THIS TIME USING YOUR BUNDLE AS DEPENDENCY
wp_register_script('jquery', FALSE, array('bundle_js'), '', FALSE);//THE KEY HERE IS THE SRC BEING FALSE
wp_register_script('backbone', FALSE, array('bundle_js'), '', FALSE);
wp_register_script('colorpicker', FALSE, array('bundle_js'), '', FALSE);
}
add_action('wp_enqueue_scripts', 'the_js');
```
the key here is to set the `$src` as `FALSE` so the registered script will be an alias, check [this line](https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-scripts.php#L327) in the core code:
```
// A single item may alias a set of items, by having dependencies, but no source.
if ( ! $obj->src ) {
return true;
}
```
its what currently `jquery` does, when putting `jquery` as a dependency, it doesnt load `jquery` it loads `jquery-core` and `jquery-migrate`, this is the registered object for `jquery`:
```
object(_WP_Dependency)#329 (6) {
["handle"]=>
string(6) "jquery"
["src"]=>
bool(false)
["deps"]=>
array(2) {
[0]=>
string(11) "jquery-core"
[1]=>
string(14) "jquery-migrate"
}
["ver"]=>
string(6) "1.12.4"
["args"]=>
NULL
["extra"]=>
array(0) {
}
}
```
so, `bundle_js` its going to be loaded when a script has as dependency of any of the libraries (`jquery`, `backbone`, `colorpicker`) and it will be loaded 1 time, since the logic in `WP_Dependencies` checks if its already in the `queue` array.
If you want to check if a script is already registered use:
```
global $wp_scripts;
$wp_scripts->query('jquery'); //jquery as example handle
```
it will return a `WP_dependency` object if its registered, `false` if its not.
Some links for further understanding:
[class.wp-dependencies.php](https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-dependencies.php)
[class.wp-scripts.php](https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class.wp-scripts.php)
[functions.wp-scripts.php](https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/functions.wp-scripts.php) |
283,839 | <p>I have created a custom posttype labeled 'Richards' using a site-specific plugin with the following code.</p>
<pre><code>function add_richards_posttype() {
$labels = array(
'name' => _x( 'Richards', 'Post Type General Name' ),
'singular_name' => _x( 'Richard', 'Post Type Singular Name' ),
'menu_name' => __( 'Richard\'s Dagboek' ),
'parent_item_colon' => __( 'Parent Richard' ),
'all_items' => __( 'Alle Richards' ),
'view_item' => __( 'Bekijk Richards' ),
'add_new_item' => __( 'Nieuwe Richard' ),
'add_new' => __( 'Nieuwe Richard' ),
'edit_item' => __( 'Bewerk Richard' ),
'update_item' => __( 'Update Richard' ),
'search_items' => __( 'Zoek Richard' ),
'not_found' => __( 'Niet Gevonden' ),
'not_found_in_trash' => __( 'Niet Gevonden in Trash' ),
);
$args = array(
'label' => __( 'richards' ),
'description' => __( 'Richard\'s Dagboek' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'revisions' ),
// 'taxonomies' => array( 'kickstarters' ),
'hierarchical' => false,
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
);
register_post_type( 'richards', $args );
}
add_action( 'init', 'add_richards_posttype', 0 );
</code></pre>
<p>I have added data using <code>richards</code> as a posttype, which shows up with the correct posttype in the database. When I want to display either the archive page or single page for this custom post type (by visiting <code>site.com/richards/</code> or <code>site.com/richard/</code>), WordPress serves a 404 error page. </p>
<p>The reason I have public set to false is to block not-logged-in users from accessing this posttype. Logged-in users should be able to access site.com/richards/ while not-logged-in users should not. </p>
<p>I have searched for the solution for quite a while now and I have tried adjusting permalink settings and changing these back, adding and removing an archive-richards.php file (although I want the styling to fall back on regular posts styling), adding and removing a menu button with <code>?post_type=richards</code> behind it and some other methods I can't recall. </p>
<p>What else can I try? How would I go about finding the solution now?</p>
| [
{
"answer_id": 283840,
"author": "Tom",
"author_id": 3482,
"author_profile": "https://wordpress.stackexchange.com/users/3482",
"pm_score": 0,
"selected": false,
"text": "<p>Permalinks may need to be refreshed. Once you've saved your code, head to WP-Admin > Settings > Permalinks and click save without changing anything. Then try to visit an archive or single page. </p>\n"
},
{
"answer_id": 283842,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 1,
"selected": false,
"text": "<p>This seems like a <a href=\"https://wordpress.stackexchange.com/questions/243373/use-wordpress-page-instead-of-post-type-archive/243376#243376\">similar question</a>, but I'll also put it here.</p>\n\n<pre><code>'has_archive' => 'richards'\n</code></pre>\n\n<p>Then flush permalinks (Settings > Permalinks).</p>\n"
},
{
"answer_id": 283855,
"author": "hans3890",
"author_id": 130199,
"author_profile": "https://wordpress.stackexchange.com/users/130199",
"pm_score": 0,
"selected": false,
"text": "<p>Apparently, I misused the 'public' argument. I was trying to make the entire custom posttype private (which not only should hide all posts, but stop people from knowing about this posttype entirely).</p>\n\n<p>Although I did not yet figure out how to hide a posttype completely, I decided on setting the value back to public (which made everything show up) while setting every post of that custom post type to private. I used <a href=\"https://wordpress.stackexchange.com/a/118976/130199\">another script</a> which forces all publishes for this posttype to become private. I also set <code>'exclude_from_search' => true</code> to make posts from this custom posttype not show up in search results.</p>\n\n<p>This did create a problem in which the custom post type was used in the URL as a 'child' of the normal posts page (i.e. <code>site.com/news/richards/</code>) though this was fixed using a simple rewrite in the <code>$args</code>: </p>\n\n<pre><code>'rewrite' => array( 'with_front' => false )\n</code></pre>\n\n<p>Thanks for all answers!</p>\n"
}
]
| 2017/10/24 | [
"https://wordpress.stackexchange.com/questions/283839",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130199/"
]
| I have created a custom posttype labeled 'Richards' using a site-specific plugin with the following code.
```
function add_richards_posttype() {
$labels = array(
'name' => _x( 'Richards', 'Post Type General Name' ),
'singular_name' => _x( 'Richard', 'Post Type Singular Name' ),
'menu_name' => __( 'Richard\'s Dagboek' ),
'parent_item_colon' => __( 'Parent Richard' ),
'all_items' => __( 'Alle Richards' ),
'view_item' => __( 'Bekijk Richards' ),
'add_new_item' => __( 'Nieuwe Richard' ),
'add_new' => __( 'Nieuwe Richard' ),
'edit_item' => __( 'Bewerk Richard' ),
'update_item' => __( 'Update Richard' ),
'search_items' => __( 'Zoek Richard' ),
'not_found' => __( 'Niet Gevonden' ),
'not_found_in_trash' => __( 'Niet Gevonden in Trash' ),
);
$args = array(
'label' => __( 'richards' ),
'description' => __( 'Richard\'s Dagboek' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'revisions' ),
// 'taxonomies' => array( 'kickstarters' ),
'hierarchical' => false,
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
);
register_post_type( 'richards', $args );
}
add_action( 'init', 'add_richards_posttype', 0 );
```
I have added data using `richards` as a posttype, which shows up with the correct posttype in the database. When I want to display either the archive page or single page for this custom post type (by visiting `site.com/richards/` or `site.com/richard/`), WordPress serves a 404 error page.
The reason I have public set to false is to block not-logged-in users from accessing this posttype. Logged-in users should be able to access site.com/richards/ while not-logged-in users should not.
I have searched for the solution for quite a while now and I have tried adjusting permalink settings and changing these back, adding and removing an archive-richards.php file (although I want the styling to fall back on regular posts styling), adding and removing a menu button with `?post_type=richards` behind it and some other methods I can't recall.
What else can I try? How would I go about finding the solution now? | This seems like a [similar question](https://wordpress.stackexchange.com/questions/243373/use-wordpress-page-instead-of-post-type-archive/243376#243376), but I'll also put it here.
```
'has_archive' => 'richards'
```
Then flush permalinks (Settings > Permalinks). |
283,867 | <p>I want to compare two timestamps in a <code>meta_query</code> instead of <a href="https://wordpress.stackexchange.com/q/283851/25187">comparing two dates</a> in the "Y-m-d" format, each of them stored separately in custom fields, but no success. The first timestamp is an event start date/time, the second is the local date/time, also as a timestamp. When I use them in my code, posts are displayed in a not understandable order. What is wrong here? The comparison of dates in the "Y-m-d" format works correctly.</p>
<pre><code>function add_custom_post_type_to_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'post_type', array( 'facebook_events', 'event' ) );
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => 'start_ts', //this is from facebook_events post type
'value' => current_time( 'timestamp' ),
'compare' => '>=',
'type' => 'DATE',
),
array(
'key' => '_start_ts', //this is from event post type
'value' => current_time( 'timestamp' ),
'compare' => '>=',
'type' => 'DATE',
)
) );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'add_custom_post_type_to_query' );
</code></pre>
| [
{
"answer_id": 283872,
"author": "Iurie",
"author_id": 25187,
"author_profile": "https://wordpress.stackexchange.com/users/25187",
"pm_score": 3,
"selected": true,
"text": "<p>This is the magic: with timestamps, insteed of <code>'type' => 'DATE'</code> must be used <code>'type' => 'NUMERIC'</code>.</p>\n"
},
{
"answer_id": 355994,
"author": "Ryan",
"author_id": 144151,
"author_profile": "https://wordpress.stackexchange.com/users/144151",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks! We ran into the same issue and this question helped a lot!</p>\n\n<p><strong>Alternate Use Case</strong><br>\nWe're looping through a custom post type called <code>events</code> (<em>surprise, surprise, it stores events</em>). It stores a timestamp in the meta field <code>ev_start</code> (<em>event start time</em>). We actually were able to just use the orderby value <code>meta_value_num</code> (<em>as you can see meta_type is commented out</em>). We also query the posts to make sure the event didn't already happen. </p>\n\n<pre><code>$current_time = current_time('timestamp');\n\n$post_args = array(\n 'post_type' => 'events',\n 'posts_per_page' => 5, \n 'meta_key' => 'ev_start',\n //'meta_type' => 'NUMERIC',\n 'orderby' => 'meta_value_num', \n 'order' => 'ASC',\n 'meta_query' => array(\n array(\n 'key' => 'ev_start',\n 'value' => $current_time,\n 'compare' => '>='\n )\n )\n);\n\n$posts = new WP_Query( $post_args );\n</code></pre>\n\n<p><strong>Resources</strong><br>\n<a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\">WP_Query Code Reference</a></p>\n"
}
]
| 2017/10/24 | [
"https://wordpress.stackexchange.com/questions/283867",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25187/"
]
| I want to compare two timestamps in a `meta_query` instead of [comparing two dates](https://wordpress.stackexchange.com/q/283851/25187) in the "Y-m-d" format, each of them stored separately in custom fields, but no success. The first timestamp is an event start date/time, the second is the local date/time, also as a timestamp. When I use them in my code, posts are displayed in a not understandable order. What is wrong here? The comparison of dates in the "Y-m-d" format works correctly.
```
function add_custom_post_type_to_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'post_type', array( 'facebook_events', 'event' ) );
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => 'start_ts', //this is from facebook_events post type
'value' => current_time( 'timestamp' ),
'compare' => '>=',
'type' => 'DATE',
),
array(
'key' => '_start_ts', //this is from event post type
'value' => current_time( 'timestamp' ),
'compare' => '>=',
'type' => 'DATE',
)
) );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'add_custom_post_type_to_query' );
``` | This is the magic: with timestamps, insteed of `'type' => 'DATE'` must be used `'type' => 'NUMERIC'`. |
283,874 | <p>I want to authenticate against <em>both</em>:</p>
<ul>
<li>the WooCommerce consumer key, for system queries <em>and</em></li>
<li>JSON Web Tokens (JWT), for user queries</li>
</ul>
<p>I have installed <a href="https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/" rel="nofollow noreferrer">JWT Authentication for WP REST API</a>. But after activating the plugin, previously working queries (that use the WooCommerce consumer key for authentication) fail with:</p>
<pre><code>{'code': 'jwt_auth_bad_auth_header',
'data': {'status': 403},
'message': 'Authorization header malformed.'}
</code></pre>
<p>How can I configure Wordpress / the JWT plugin so that they succeed?</p>
| [
{
"answer_id": 283961,
"author": "lofidevops",
"author_id": 31388,
"author_profile": "https://wordpress.stackexchange.com/users/31388",
"pm_score": 4,
"selected": true,
"text": "<p>Yes this is possible by structuring your requests appropriately.</p>\n\n<p>For system requests use OAuth 1.0 (consumer key as before), but encode it to include the OAuth credentials <em>in the URL</em> not in the headers. Having the OAuth credentials in the <code>Authorisation</code> header triggers the JWT error.</p>\n\n<pre><code>GET https://DOMAIN/wp-json/wc/v1/subscriptions\n* Authorization: `OAuth 1.0`\n * Consumer key: FILLED IN\n * Consumer secret: FILLED IN\n * Other fields: blank\n* Headers: blank\n* Body: blank\n</code></pre>\n\n<p>To request a token (for a user-based query), you don't use authorization, you include the user credentials in the body:</p>\n\n<pre><code>POST https://DOMAIN/wp-json/jwt-auth/v1/token\n* Authorization: `No Auth`\n* Headers: blank\n* Body: `form-data`\n * key: username, value: test\n * key: password, value: test\n</code></pre>\n\n<p>Once you have the token, you can add it to the <code>Authentication</code> header per JWT requirements.</p>\n\n<p>To test these queries, it's easiest to use a dedicated tool like <a href=\"https://httpie.org\" rel=\"noreferrer\">httpie</a> or <a href=\"https://www.getpostman.com\" rel=\"noreferrer\">Postman</a>.</p>\n\n<p><strong>Reference:</strong> <a href=\"https://github.com/Tmeister/wp-api-jwt-auth/issues/87\" rel=\"noreferrer\">https://github.com/Tmeister/wp-api-jwt-auth/issues/87</a></p>\n"
},
{
"answer_id": 302458,
"author": "Joydeb Chouhdhury",
"author_id": 142854,
"author_profile": "https://wordpress.stackexchange.com/users/142854",
"pm_score": -1,
"selected": false,
"text": "<p>I have faced the same issue. Jwt Authentication for wp api and woocommerce api not working along with in <a href=\"http://jquerytraining.com\" rel=\"nofollow noreferrer\">ionic3</a> and woocommerce.\nI have figured out the issue and done the following </p>\n\n<p>Go to -> <code>plugins/jwt-authentication-for-wp-rest-api/includes/class-jwt-auth.php</code></p>\n\n<p>search for the function define_public_hooks() and comment last two lines</p>\n\n<pre><code>private function define_public_hooks()\n{\n $plugin_public = new Jwt_Auth_Public($this->get_plugin_name(), $this->get_version());\n $this->loader->add_action('rest_api_init', $plugin_public, 'add_api_routes');\n $this->loader->add_filter('rest_api_init', $plugin_public, 'add_cors_support');\n //$this->loader->add_filter('determine_current_user', $plugin_public, 'determine_current_user', 10);\n //$this->loader->add_filter( 'rest_pre_dispatch', $plugin_public, 'rest_pre_dispatch', 10, 2 );\n}\n</code></pre>\n\n<p>Thanks, enjoy.</p>\n"
}
]
| 2017/10/24 | [
"https://wordpress.stackexchange.com/questions/283874",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31388/"
]
| I want to authenticate against *both*:
* the WooCommerce consumer key, for system queries *and*
* JSON Web Tokens (JWT), for user queries
I have installed [JWT Authentication for WP REST API](https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/). But after activating the plugin, previously working queries (that use the WooCommerce consumer key for authentication) fail with:
```
{'code': 'jwt_auth_bad_auth_header',
'data': {'status': 403},
'message': 'Authorization header malformed.'}
```
How can I configure Wordpress / the JWT plugin so that they succeed? | Yes this is possible by structuring your requests appropriately.
For system requests use OAuth 1.0 (consumer key as before), but encode it to include the OAuth credentials *in the URL* not in the headers. Having the OAuth credentials in the `Authorisation` header triggers the JWT error.
```
GET https://DOMAIN/wp-json/wc/v1/subscriptions
* Authorization: `OAuth 1.0`
* Consumer key: FILLED IN
* Consumer secret: FILLED IN
* Other fields: blank
* Headers: blank
* Body: blank
```
To request a token (for a user-based query), you don't use authorization, you include the user credentials in the body:
```
POST https://DOMAIN/wp-json/jwt-auth/v1/token
* Authorization: `No Auth`
* Headers: blank
* Body: `form-data`
* key: username, value: test
* key: password, value: test
```
Once you have the token, you can add it to the `Authentication` header per JWT requirements.
To test these queries, it's easiest to use a dedicated tool like [httpie](https://httpie.org) or [Postman](https://www.getpostman.com).
**Reference:** <https://github.com/Tmeister/wp-api-jwt-auth/issues/87> |
283,890 | <p>I want to get all posts from my custom post type in groups by posts of each year.</p>
<ul>
<li>2017 (5) </li>
<li>2016 (9)</li>
<li>2015 (7)</li>
<li>2014 (19)</li>
<li>2013 (3)</li>
</ul>
| [
{
"answer_id": 284577,
"author": "James",
"author_id": 122472,
"author_profile": "https://wordpress.stackexchange.com/users/122472",
"pm_score": 0,
"selected": false,
"text": "<p>This should return an array of arrays, by year, with a count.</p>\n\n<pre><code>$args = [\n 'post_type' => 'cpt_post_type'\n];\n$query = new WP_Query($args);\n$posts_by_year = [];\n\nif ($query->have_posts()) {\n while ($query->have_posts()) {\n $query->the_post();\n $year = get_the_date('Y');\n $posts_by_year[$year][] = ['title' => get_the_title(), 'link' => get_the_permalink()];\n $posts_by_year[$year]['count'] = count($posts_by_year[$year]);\n }\n}\n</code></pre>\n\n<p>You could then foreach the $posts_by_year to iterate through them in the view. I would also wrap the above in to a function.</p>\n"
},
{
"answer_id": 284578,
"author": "megi",
"author_id": 122155,
"author_profile": "https://wordpress.stackexchange.com/users/122155",
"pm_score": 1,
"selected": false,
"text": "<p>You can get list with below code :</p>\n\n<pre><code><?php wp_get_archives('type=yearly&format=option&post_type=resources&show_post_count=true'); ?> \n</code></pre>\n"
}
]
| 2017/10/25 | [
"https://wordpress.stackexchange.com/questions/283890",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130230/"
]
| I want to get all posts from my custom post type in groups by posts of each year.
* 2017 (5)
* 2016 (9)
* 2015 (7)
* 2014 (19)
* 2013 (3) | You can get list with below code :
```
<?php wp_get_archives('type=yearly&format=option&post_type=resources&show_post_count=true'); ?>
``` |
283,893 | <p>I loaded some contents by ajax, When i try something like this:</p>
<pre><code>$resp = array(
'success' => true,
'data' => 'the content here'
);
</code></pre>
<p>it's working without any issues but if i used something like this:</p>
<pre><code>$resp = array(
'success' => true,
'data' => get_template_part( 'templates/update', 'profile' )
);
</code></pre>
<p>it gives me SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data.</p>
<pre><code>the content here{"success":true,"data":null}
</code></pre>
<p>What's the problem with get_template_part?</p>
| [
{
"answer_id": 283896,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<p><code>get_template_part()</code> includes the PHP file, which will break <code>$resp</code>. You need to use <a href=\"http://php.net/manual/en/book.outcontrol.php\" rel=\"noreferrer\">output buffering</a> to capture the output into a variable:</p>\n\n<pre><code>ob_start();\nget_template_part( 'templates/update', 'profile' );\n$data = ob_get_clean();\n\n$resp = array(\n 'success' => true,\n 'data' => $data\n);\n</code></pre>\n"
},
{
"answer_id": 352971,
"author": "I'm a TI calculator",
"author_id": 175313,
"author_profile": "https://wordpress.stackexchange.com/users/175313",
"pm_score": 1,
"selected": false,
"text": "<p>Since this had me scratching heads for a while too; here's the code i came up with if it can be useful to anyone.</p>\n\n<p>Register and localize the JS script, here's some good practical info for the basic <a href=\"https://www.damiencarbery.com/2018/11/ajax-script-generator/\" rel=\"nofollow noreferrer\">WP Ajax gen</a></p>\n\n<p>The wp_ajax function itself : </p>\n\n<pre><code> function fpost()\n{\n $post_type = sanitize_text_field($_POST['post_type']);\n $post_id = intval($_POST['post_id']);\n $args = array(\n 'post_type' => $post_type,\n 'post_status' => 'publish',\n 'p' => $post_id,\n );\n $p_query = new WP_Query($args);\n ob_start();\n if ($p_query->have_posts()) {\n while ($p_query->have_posts()) {\n $p_query->the_post();\n get_template_part('template-parts/content', $post_type);\n }\n wp_reset_postdata();\n wp_send_json_success(ob_get_clean());\n } else {\n wp_send_json_error();\n }\n die();\n}\nadd_action('wp_ajax_nopriv_fp', 'fpost');\nadd_action('wp_ajax_fp', 'fpost');\n</code></pre>\n\n<p>The JS sends post_type and post_id, and WP returns 2 objects; the templated content + \"success\" (which is much helpful..)</p>\n\n<p>hope that helps</p>\n"
},
{
"answer_id": 396713,
"author": "Carlos Bermudez Diaz",
"author_id": 177944,
"author_profile": "https://wordpress.stackexchange.com/users/177944",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me! don't forget to set the datatype to json in your JS ajax function</p>\n<p>so It'll be:</p>\n<pre><code>dataType: 'json',\n</code></pre>\n"
}
]
| 2017/10/25 | [
"https://wordpress.stackexchange.com/questions/283893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125375/"
]
| I loaded some contents by ajax, When i try something like this:
```
$resp = array(
'success' => true,
'data' => 'the content here'
);
```
it's working without any issues but if i used something like this:
```
$resp = array(
'success' => true,
'data' => get_template_part( 'templates/update', 'profile' )
);
```
it gives me SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data.
```
the content here{"success":true,"data":null}
```
What's the problem with get\_template\_part? | `get_template_part()` includes the PHP file, which will break `$resp`. You need to use [output buffering](http://php.net/manual/en/book.outcontrol.php) to capture the output into a variable:
```
ob_start();
get_template_part( 'templates/update', 'profile' );
$data = ob_get_clean();
$resp = array(
'success' => true,
'data' => $data
);
``` |
283,897 | <p>I am going to develop WordPress theme using <a href="https://underscores.me/" rel="nofollow noreferrer">Underscores</a> and Bootstrap.</p>
<p>So should I copy <a href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css" rel="nofollow noreferrer">all bootstrap codes</a> in to style.css or should I include it using <code>@import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css");</code> in style.css?</p>
| [
{
"answer_id": 283903,
"author": "Digvijayad",
"author_id": 118765,
"author_profile": "https://wordpress.stackexchange.com/users/118765",
"pm_score": 2,
"selected": true,
"text": "<p>Neither, \nIn wordpress styles and scripts should be properly en-queued through your functions.php file rather than hard-coding them in your html. </p>\n\n<p>The wordpress way of adding a new css file, be it <code>bootstrap.css</code> or any other is to use <code>wp_enqueue_scripts</code> hook. </p>\n\n<p>The following code should be in your theme's <code>functions.php</code></p>\n\n<pre><code>/**\n* Proper way to enqueue scripts and styles\n*/\nfunction wp_theme_name_scripts() {\n\n // enqueue your style.css\n wp_enqueue_style('style-name', get_stylesheet_uri() );\n\n // en-queue external style\n wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );\n\n // enqueue your script\n wp_enqueue_script( 'script-name', get_template_directory_uri() .'/js/theme_name.js', array(), '1.0.0', true );\n\n // Other styles and scripts\n}\nadd_action( 'wp_enqueue_scripts', 'wp_theme_name_scripts' );\n</code></pre>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/loading-css-into-wordpress-the-right-way--cms-20402\" rel=\"nofollow noreferrer\">This</a> is a great tutorial on how to load css the right way in wordpress.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">Check out</a> WordPress documentation for more info on enqueueing styles</p>\n\n<h2>Update:</h2>\n\n<p>Underscores Framework already has the function defined in the <code>functions.php</code>.\nOpen your themes <code>function.php</code> and find the function named <code>yourTheme_scripts()</code>, and add the following line to include the Bootstrap library.</p>\n\n<pre><code>wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );\n</code></pre>\n\n<p>Your function in the underscores's file should look like this:</p>\n\n<pre><code>/**\n* Enqueue scripts and styles.\n*/\nfunction yourTheme_scripts() {\n\n wp_enqueue_style( 'yourTheme-style', get_stylesheet_uri() );\n\n //Enqueue bootstrap css library\n wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );\n\n wp_enqueue_script( 'yourTheme-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );\n\n wp_enqueue_script( 'yourTheme-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );\n\n if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'yourTheme_scripts' );\n</code></pre>\n"
},
{
"answer_id": 283907,
"author": "Arun Basil Lal",
"author_id": 90061,
"author_profile": "https://wordpress.stackexchange.com/users/90061",
"pm_score": 0,
"selected": false,
"text": "<p>Please DO NOT copy external stylesheets into the style.css. That is very inefficient practice. </p>\n\n<p>Loading it via @import isn't recommended either. You should use <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> for CSS and <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a> for JS</p>\n\n<p>Here is the right way to do it. Add this function to the functions.php of your theme. </p>\n\n<pre><code>/**\n * Load CSS and JS the right way\n *\n * @refer http://millionclues.com/wordpress-tips/load-css-and-js-the-right-way/\n */\nfunction mcabl1226_load_css_and_js() {\n // Load Boostrap CSS\n wp_enqueue_style( 'bootstrap-css', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css' );\n\n // Load Theme's style.css\n wp_enqueue_style( 'style', get_stylesheet_uri() );\n\n // Load Boostrap JS\n //wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js', array('jquery'), '1.0', true);\n}\nadd_action( 'wp_enqueue_scripts', 'mcabl1226_load_css_and_js' );\n</code></pre>\n\n<p>You would most likely need Bootstrap JS as well. Un-comment the appropriate line in the above function for that. </p>\n\n<p>On a side note, if you want a very minimal starter theme to develop with Bootstrap, you can checkout my <a href=\"https://github.com/arunbasillal/MillionClues-Starter-Theme\" rel=\"nofollow noreferrer\">Bootstrap starter theme</a>. </p>\n"
}
]
| 2017/10/25 | [
"https://wordpress.stackexchange.com/questions/283897",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123092/"
]
| I am going to develop WordPress theme using [Underscores](https://underscores.me/) and Bootstrap.
So should I copy [all bootstrap codes](https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css) in to style.css or should I include it using `@import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css");` in style.css? | Neither,
In wordpress styles and scripts should be properly en-queued through your functions.php file rather than hard-coding them in your html.
The wordpress way of adding a new css file, be it `bootstrap.css` or any other is to use `wp_enqueue_scripts` hook.
The following code should be in your theme's `functions.php`
```
/**
* Proper way to enqueue scripts and styles
*/
function wp_theme_name_scripts() {
// enqueue your style.css
wp_enqueue_style('style-name', get_stylesheet_uri() );
// en-queue external style
wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );
// enqueue your script
wp_enqueue_script( 'script-name', get_template_directory_uri() .'/js/theme_name.js', array(), '1.0.0', true );
// Other styles and scripts
}
add_action( 'wp_enqueue_scripts', 'wp_theme_name_scripts' );
```
[This](https://code.tutsplus.com/tutorials/loading-css-into-wordpress-the-right-way--cms-20402) is a great tutorial on how to load css the right way in wordpress.
[Check out](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) WordPress documentation for more info on enqueueing styles
Update:
-------
Underscores Framework already has the function defined in the `functions.php`.
Open your themes `function.php` and find the function named `yourTheme_scripts()`, and add the following line to include the Bootstrap library.
```
wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );
```
Your function in the underscores's file should look like this:
```
/**
* Enqueue scripts and styles.
*/
function yourTheme_scripts() {
wp_enqueue_style( 'yourTheme-style', get_stylesheet_uri() );
//Enqueue bootstrap css library
wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );
wp_enqueue_script( 'yourTheme-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );
wp_enqueue_script( 'yourTheme-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', 'yourTheme_scripts' );
``` |
283,928 | <p>I am developing a custom code in wordpress and in order to debug that I need to know if I can add custom text in wpdebug log Please help me if i can do it</p>
| [
{
"answer_id": 283903,
"author": "Digvijayad",
"author_id": 118765,
"author_profile": "https://wordpress.stackexchange.com/users/118765",
"pm_score": 2,
"selected": true,
"text": "<p>Neither, \nIn wordpress styles and scripts should be properly en-queued through your functions.php file rather than hard-coding them in your html. </p>\n\n<p>The wordpress way of adding a new css file, be it <code>bootstrap.css</code> or any other is to use <code>wp_enqueue_scripts</code> hook. </p>\n\n<p>The following code should be in your theme's <code>functions.php</code></p>\n\n<pre><code>/**\n* Proper way to enqueue scripts and styles\n*/\nfunction wp_theme_name_scripts() {\n\n // enqueue your style.css\n wp_enqueue_style('style-name', get_stylesheet_uri() );\n\n // en-queue external style\n wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );\n\n // enqueue your script\n wp_enqueue_script( 'script-name', get_template_directory_uri() .'/js/theme_name.js', array(), '1.0.0', true );\n\n // Other styles and scripts\n}\nadd_action( 'wp_enqueue_scripts', 'wp_theme_name_scripts' );\n</code></pre>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/loading-css-into-wordpress-the-right-way--cms-20402\" rel=\"nofollow noreferrer\">This</a> is a great tutorial on how to load css the right way in wordpress.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">Check out</a> WordPress documentation for more info on enqueueing styles</p>\n\n<h2>Update:</h2>\n\n<p>Underscores Framework already has the function defined in the <code>functions.php</code>.\nOpen your themes <code>function.php</code> and find the function named <code>yourTheme_scripts()</code>, and add the following line to include the Bootstrap library.</p>\n\n<pre><code>wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );\n</code></pre>\n\n<p>Your function in the underscores's file should look like this:</p>\n\n<pre><code>/**\n* Enqueue scripts and styles.\n*/\nfunction yourTheme_scripts() {\n\n wp_enqueue_style( 'yourTheme-style', get_stylesheet_uri() );\n\n //Enqueue bootstrap css library\n wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );\n\n wp_enqueue_script( 'yourTheme-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );\n\n wp_enqueue_script( 'yourTheme-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );\n\n if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'yourTheme_scripts' );\n</code></pre>\n"
},
{
"answer_id": 283907,
"author": "Arun Basil Lal",
"author_id": 90061,
"author_profile": "https://wordpress.stackexchange.com/users/90061",
"pm_score": 0,
"selected": false,
"text": "<p>Please DO NOT copy external stylesheets into the style.css. That is very inefficient practice. </p>\n\n<p>Loading it via @import isn't recommended either. You should use <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> for CSS and <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a> for JS</p>\n\n<p>Here is the right way to do it. Add this function to the functions.php of your theme. </p>\n\n<pre><code>/**\n * Load CSS and JS the right way\n *\n * @refer http://millionclues.com/wordpress-tips/load-css-and-js-the-right-way/\n */\nfunction mcabl1226_load_css_and_js() {\n // Load Boostrap CSS\n wp_enqueue_style( 'bootstrap-css', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css' );\n\n // Load Theme's style.css\n wp_enqueue_style( 'style', get_stylesheet_uri() );\n\n // Load Boostrap JS\n //wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js', array('jquery'), '1.0', true);\n}\nadd_action( 'wp_enqueue_scripts', 'mcabl1226_load_css_and_js' );\n</code></pre>\n\n<p>You would most likely need Bootstrap JS as well. Un-comment the appropriate line in the above function for that. </p>\n\n<p>On a side note, if you want a very minimal starter theme to develop with Bootstrap, you can checkout my <a href=\"https://github.com/arunbasillal/MillionClues-Starter-Theme\" rel=\"nofollow noreferrer\">Bootstrap starter theme</a>. </p>\n"
}
]
| 2017/10/25 | [
"https://wordpress.stackexchange.com/questions/283928",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| I am developing a custom code in wordpress and in order to debug that I need to know if I can add custom text in wpdebug log Please help me if i can do it | Neither,
In wordpress styles and scripts should be properly en-queued through your functions.php file rather than hard-coding them in your html.
The wordpress way of adding a new css file, be it `bootstrap.css` or any other is to use `wp_enqueue_scripts` hook.
The following code should be in your theme's `functions.php`
```
/**
* Proper way to enqueue scripts and styles
*/
function wp_theme_name_scripts() {
// enqueue your style.css
wp_enqueue_style('style-name', get_stylesheet_uri() );
// en-queue external style
wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );
// enqueue your script
wp_enqueue_script( 'script-name', get_template_directory_uri() .'/js/theme_name.js', array(), '1.0.0', true );
// Other styles and scripts
}
add_action( 'wp_enqueue_scripts', 'wp_theme_name_scripts' );
```
[This](https://code.tutsplus.com/tutorials/loading-css-into-wordpress-the-right-way--cms-20402) is a great tutorial on how to load css the right way in wordpress.
[Check out](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) WordPress documentation for more info on enqueueing styles
Update:
-------
Underscores Framework already has the function defined in the `functions.php`.
Open your themes `function.php` and find the function named `yourTheme_scripts()`, and add the following line to include the Bootstrap library.
```
wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );
```
Your function in the underscores's file should look like this:
```
/**
* Enqueue scripts and styles.
*/
function yourTheme_scripts() {
wp_enqueue_style( 'yourTheme-style', get_stylesheet_uri() );
//Enqueue bootstrap css library
wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.css' );
wp_enqueue_script( 'yourTheme-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );
wp_enqueue_script( 'yourTheme-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', 'yourTheme_scripts' );
``` |
283,965 | <p>I have a custom HTML form with input types and checkboxes. When I submit this form I want to send a mail will all the form details from the same php. How do I send the email from WordPress? I am pretty new and would thank for ur help.</p>
| [
{
"answer_id": 283968,
"author": "Tom",
"author_id": 3482,
"author_profile": "https://wordpress.stackexchange.com/users/3482",
"pm_score": 4,
"selected": true,
"text": "<p><code>wp_mail</code> is the function you are looking for. </p>\n\n<p>You can take the posted form data (<code>$_POST['email']</code>, for example) and then use it to build and execute the <code>wp_mail</code> function. The example below was taken from <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/#user-contributed-notes\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/wp_mail/#user-contributed-notes</a></p>\n\n<pre><code>$to = $_POST['email']; //[email protected]\n$subject = 'The subject';\n$body = 'The email body content';\n$headers = array('Content-Type: text/html; charset=UTF-8');\n\nwp_mail( $to, $subject, $body, $headers );\n</code></pre>\n\n<p>Also the above script would need to check for malicious attacks or bad input from the user but the <code>wp_mail</code> function will allow you to send email.</p>\n\n<p>Source: \n<a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/wp_mail/</a></p>\n"
},
{
"answer_id": 284011,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to write your own code (and the mail form), consider a 'contact form' plugin. I use (and recommend) the Contact Form 7 plugin. It allows you to create any form, customize the look/feel/fields, and the mail that is sent out. Very powerful and popular plugin. Lots of other plugins available to add additional fields.</p>\n\n<p>The only minor issue is sparse and sometimes hard-to-find (and sometimes older) technical documentation (like available filters). But I've worked around that.</p>\n"
},
{
"answer_id": 317544,
"author": "user10526239",
"author_id": 152933,
"author_profile": "https://wordpress.stackexchange.com/users/152933",
"pm_score": 1,
"selected": false,
"text": "<p>One simple way to post a form is to use a form backend service like <a href=\"https://www.formkeep.com\" rel=\"nofollow noreferrer\">https://www.formkeep.com</a></p>\n\n<p>All you have to do is modify the action tag in your form and backend service will store the data and provide ways to integrate data with the other systems.</p>\n\n<p>Here's a sample for how to modify the form html. You would just replace \"example token\" with a key provided by the formkeep service</p>\n\n<pre><code><form accept-charset=\"UTF-8\" action=\"https://formkeep.com/f/exampletoken\" method=\"POST\">\n</code></pre>\n"
}
]
| 2017/10/25 | [
"https://wordpress.stackexchange.com/questions/283965",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130289/"
]
| I have a custom HTML form with input types and checkboxes. When I submit this form I want to send a mail will all the form details from the same php. How do I send the email from WordPress? I am pretty new and would thank for ur help. | `wp_mail` is the function you are looking for.
You can take the posted form data (`$_POST['email']`, for example) and then use it to build and execute the `wp_mail` function. The example below was taken from <https://developer.wordpress.org/reference/functions/wp_mail/#user-contributed-notes>
```
$to = $_POST['email']; //[email protected]
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
```
Also the above script would need to check for malicious attacks or bad input from the user but the `wp_mail` function will allow you to send email.
Source:
<https://developer.wordpress.org/reference/functions/wp_mail/> |
283,971 | <p>I am facing an issue when i use get_the_content() function. It displays the post content but the image in beginning of the content has some extra text around. My code is:</p>
<pre><code><div class="thecontent" itemprop="articleBody">
<?php echo get_the_content(); ?>
</div>
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/rn87L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rn87L.png" alt="enter image description here"></a></p>
<p>I also tried</p>
<pre><code><div class="thecontent" itemprop="articleBody">
<?php $content= get_the_content();
echo apply_filters('the_content', $content);
?>
</div>
</code></pre>
<p>But in this case picture isn't showing at all.</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/9kbSC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9kbSC.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 283972,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": true,
"text": "<p>To make sure the shortcode executes, save the content to a variable, then run <code>do_shortcode</code> on the saved variable.</p>\n\n<pre><code><div class=\"thecontent\" itemprop=\"articleBody\">\n <?php $content = get_the_content();\n echo do_shortcode($content); ?>\n</div>\n</code></pre>\n\n<p>The difference is, echoing just literally echoes whatever has been grabbed. PHP's built-in functions don't have any special way to process shortcodes so they just output as they've been told. By using a WP-specific function, WordPress parses whatever the content is and displays it. This works even if you have no shortcodes in the content.</p>\n"
},
{
"answer_id": 283980,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>What you had originally, <code>echo get_the_content();</code> doesn't work because the <code>do_shortcode</code> callback isn't applied when calling <a href=\"https://developer.wordpress.org/reference/functions/get_the_content/\" rel=\"nofollow noreferrer\"><code>get_the_content()</code></a>, but it is when calling <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"nofollow noreferrer\"><code>the_content()</code></a>. That's why the caption shortcode isn't being converted into its corresponding HTML.</p>\n\n<p>There is almost never a reason to <code>echo get_the_content()</code> because that's basically what <code>the_content()</code> does.</p>\n\n<pre><code><div class=\"thecontent\" itemprop=\"articleBody\">\n <?php the_content(); ?>\n</div>\n</code></pre>\n\n<p>If, for whatever reason, your use can necessitates using <code>get_the_content()</code> instead of <code>the_content()</code>, you need to make sure that the <code>do_shortcode</code> callback is applied before printing the HTML. So there are a couple ways to fix that. One (that should work) is by applying the <code>the_content</code> filter to the <code>get_the_content()</code> function. </p>\n\n<pre><code>//* In your index.php (or wherever template file)\nprintf( \n '<div class=\"thecontent\" itemprop=\"articleBody\">%1$s</div>',\n apply_filters( 'the_content', $content )\n);\n</code></pre>\n\n<p>This is basically what you tried in your question. I write it like this because it's clearer, to me, what this code does. To be clear, this should work. Since it's not, there is a filter hooked to <code>the_content</code> that's messing it up added by your theme or a plugin. Make sure to disable all plugins and disable any other part of your theme that filters <code>the_content</code>.</p>\n\n<p>Another way to do this is to force the shortcodes to do their thing. This is what WebElaine says in her answer. I'd do it slightly differently, but again, the same concept.</p>\n\n<pre><code>//* Again, in a template file\nprintf(\n <div class=\"thecontent\" itemprop=\"articleBody\">%1$s</div>,\n do_shortcode( get_the_content() )\n);\n</code></pre>\n\n<p>There's also a way to do this in your functions.php, or another file included from your functions.php, or even a plugin. What you can do is hook into <code>the_content</code> and add the wrapper there.</p>\n\n<pre><code>//* In your functions.php\nadd_filter( 'the_content', 'wpse_283971_the_content', 1000 );\nfunction wpse_283971_the_content( $content ) {\n return sprintf( '<div class=\"thecontent\" itemprop=\"articleBody\">%1$s</div>', $content );\n}\n\n//* In your template file\nthe_content();\n</code></pre>\n\n<p>I'm guessing that you're trying to <code>echo get_the_content()</code> instead of just using <code>the_content()</code> is because <code>the_content()</code> wasn't working. You need to find the filter that's causing the problem with <code>the_content</code>. From the looks of it, one of the filters is forgetting to return its result.</p>\n"
}
]
| 2017/10/25 | [
"https://wordpress.stackexchange.com/questions/283971",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119633/"
]
| I am facing an issue when i use get\_the\_content() function. It displays the post content but the image in beginning of the content has some extra text around. My code is:
```
<div class="thecontent" itemprop="articleBody">
<?php echo get_the_content(); ?>
</div>
```
Output:
[](https://i.stack.imgur.com/rn87L.png)
I also tried
```
<div class="thecontent" itemprop="articleBody">
<?php $content= get_the_content();
echo apply_filters('the_content', $content);
?>
</div>
```
But in this case picture isn't showing at all.
Output:
[](https://i.stack.imgur.com/9kbSC.png) | To make sure the shortcode executes, save the content to a variable, then run `do_shortcode` on the saved variable.
```
<div class="thecontent" itemprop="articleBody">
<?php $content = get_the_content();
echo do_shortcode($content); ?>
</div>
```
The difference is, echoing just literally echoes whatever has been grabbed. PHP's built-in functions don't have any special way to process shortcodes so they just output as they've been told. By using a WP-specific function, WordPress parses whatever the content is and displays it. This works even if you have no shortcodes in the content. |
283,988 | <p>I am building a website for a public school district. All of our school buildings have common pages with the same name (i.e. Library, Nurse, Attendance, etc) that are nested under their parent building's page. While trying to update our site navigation, I've noticed that for some reason the Menus -> Pages -> View All area is not nesting the building pages under their building and is instead listing them alphabetically.</p>
<p><a href="https://i.stack.imgur.com/WxasR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxasR.jpg" alt="Pages not nesting"></a> </p>
<p>The odd thing is, I have nested pages set up in other areas of the site and they <em>do</em> nest themselves on the list.<br>
<a href="https://i.stack.imgur.com/hzA6j.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hzA6j.jpg" alt="Pages that are nesting"></a></p>
<p>Am I missing something? I can't find anything different about the way I nested the pages that do display properly vs those that don't. I double checked the nested pages and they have their building listed as their parent. </p>
<p>I find this extremely frustrating. Unless I go in and edit all of the pages under a specific building to force them into the recent list I have no idea which page is which.</p>
<ul>
<li>I do NOT want to add the building name to each page title.</li>
<li>These pages are nested 3 levels deep (Schools -> Building Name -> Page Name)</li>
</ul>
<p>If there isn't a way to fix the way the list displays, is there maybe a way to add the parent page's name to the page name? Or another way to build the menus?</p>
| [
{
"answer_id": 285005,
"author": "jaswrks",
"author_id": 81760,
"author_profile": "https://wordpress.stackexchange.com/users/81760",
"pm_score": -1,
"selected": false,
"text": "<p>The function you're looking for is <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/\" rel=\"nofollow noreferrer\"><code>wp_list_pages()</code></a>.</p>\n\n<p>Pay particular attention to these two arguments documented on that page.</p>\n\n<ul>\n<li><p><code>depth</code> being the most relevant to your question.</p>\n\n<blockquote>\n <p>'depth' (int) Number of levels in the hierarchy of pages to include in\n the generated list. Accepts -1 (any depth), 0 (all pages), 1\n (top-level pages only), and n (pages to the given n depth). Default 0.</p>\n</blockquote></li>\n<li><p>There's also <code>child_of</code>, giving you the option to list only those that are children of a specific parent page that you have; i.e., a specific building's child pages.</p>\n\n<blockquote>\n <p>'child_of' (int) Display only the sub-pages of a single page by ID.\n Default 0 (all pages).</p>\n</blockquote></li>\n</ul>\n\n<hr>\n\n<p><strong>Tip:</strong> One more option is to use a combination of <a href=\"https://developer.wordpress.org/reference/functions/get_pages/\" rel=\"nofollow noreferrer\"><code>get_pages()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/#comment-391\" rel=\"nofollow noreferrer\"><code>wp_list_pages()</code></a> as shown by <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/#comment-391\" rel=\"nofollow noreferrer\">example here</a>. Between the two, you should be able to display the hierarchy as desired.</p>\n"
},
{
"answer_id": 293649,
"author": "LoganGoesPlaces",
"author_id": 43563,
"author_profile": "https://wordpress.stackexchange.com/users/43563",
"pm_score": 1,
"selected": true,
"text": "<p>For those who run into this in the future, the issue was due to pagination and the parent appearing on a different page than the children. Removing pagination from the View All menu fixed the nesting.</p>\n\n<p>There is a <a href=\"https://core.trac.wordpress.org/ticket/18282\" rel=\"nofollow noreferrer\">ticket</a> opened 7 years ago reporting this bug and it has yet to be resolved. In the comments user danburzo suggests adding the following filter, which corrected the issue for me.</p>\n\n<pre><code><?php\n add_filter( 'nav_menu_meta_box_object', array( $this, 'disable_pagination_in_menu_meta_box' ) );\n\n function disable_pagination_in_menu_meta_box($obj) {\n $obj->_default_query = array(\n 'posts_per_page' => -1\n );\n return $obj;\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 323703,
"author": "Isma'el",
"author_id": 157407,
"author_profile": "https://wordpress.stackexchange.com/users/157407",
"pm_score": 0,
"selected": false,
"text": "<p>Yes this is annoying, I found that this happens only if the [Main Navigation] option is checked ,go to menus on theme customization; uncheck this and you will be fine.</p>\n"
}
]
| 2017/10/25 | [
"https://wordpress.stackexchange.com/questions/283988",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43563/"
]
| I am building a website for a public school district. All of our school buildings have common pages with the same name (i.e. Library, Nurse, Attendance, etc) that are nested under their parent building's page. While trying to update our site navigation, I've noticed that for some reason the Menus -> Pages -> View All area is not nesting the building pages under their building and is instead listing them alphabetically.
[](https://i.stack.imgur.com/WxasR.jpg)
The odd thing is, I have nested pages set up in other areas of the site and they *do* nest themselves on the list.
[](https://i.stack.imgur.com/hzA6j.jpg)
Am I missing something? I can't find anything different about the way I nested the pages that do display properly vs those that don't. I double checked the nested pages and they have their building listed as their parent.
I find this extremely frustrating. Unless I go in and edit all of the pages under a specific building to force them into the recent list I have no idea which page is which.
* I do NOT want to add the building name to each page title.
* These pages are nested 3 levels deep (Schools -> Building Name -> Page Name)
If there isn't a way to fix the way the list displays, is there maybe a way to add the parent page's name to the page name? Or another way to build the menus? | For those who run into this in the future, the issue was due to pagination and the parent appearing on a different page than the children. Removing pagination from the View All menu fixed the nesting.
There is a [ticket](https://core.trac.wordpress.org/ticket/18282) opened 7 years ago reporting this bug and it has yet to be resolved. In the comments user danburzo suggests adding the following filter, which corrected the issue for me.
```
<?php
add_filter( 'nav_menu_meta_box_object', array( $this, 'disable_pagination_in_menu_meta_box' ) );
function disable_pagination_in_menu_meta_box($obj) {
$obj->_default_query = array(
'posts_per_page' => -1
);
return $obj;
}
?>
``` |
284,083 | <p>a friend received a notification from her host about infected files and asked me to look at it. I don't know wordpress or php so I'm a little lost in what I am looking for. The is the websitescan.txt. I don't know what I am looking at, hoping someone could give me some direction as to what this report is saying and what I can do to fix the problems. thanks</p>
<pre><code>Scan started at - Fri Oct 13 13:42:53 EDT 2017
/htdocs/wp-admin/edit-comments_ver1.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/css/colors/midnight/colors-rtl_new.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/css/colors/ectoplasm/colors_indesit.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/css/colors/sunrise/colors.min_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/css/colors/ocean/colors-rtl.min_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/network/site-settings_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/maint/repair_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/includes/taxonomy_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/js/inline-edit-tax_infoold.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/user/admin_bck_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-content/themes/fiore/functions.php:
LONGDEF.PHP.Spam-Links-009N.UNOFFICIAL FOUND
/htdocs/wp-content/themes/fiore/images/thicklines-2x_noversion.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-content/themes/fiore/js/customizer_new.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/SimplePie/HTTP/Parser_bck_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/SimplePie/Content/6f26e1e6_bck_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/Text/Diff_ver1.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/utils/mctabs_bck_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/langs/wp-langs-en_infoold.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/skins/lightgray/img/trans_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/plugins/07ab1454_indesit.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/plugins/hr/plugin.min_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/plugins/wpgallery/plugin.min_indesit.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/plugins/media/plugin_infoold.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
----------- SCAN SUMMARY -----------
Infected files: 23
Time: 238.961 sec (3 m 58 s)
Scan ended at - Fri Oct 13 13:46:52 EDT 2017
</code></pre>
| [
{
"answer_id": 284086,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": -1,
"selected": false,
"text": "<p>Just Using FTP or File manager Delete these infected files.. Then login to wp admin and add WordFence Security WordPress plugin. Then monitor the site health in regular basis</p>\n"
},
{
"answer_id": 284087,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 1,
"selected": true,
"text": "<p>If you have a good full backup of your website, restore your site from it (recommended). Install and set up <code>WordFence</code> plugin (as in case of no backup).</p>\n\n<p>If you don't have good backup:</p>\n\n<p>Immediately delete all files from this list. Get a clean copy of your version of WordPress, and clean copy of your theme. Copy over entire theme. Copy over clean <code>/wp-admin/</code>, and <code>/wp-includes/</code>. Start your website. Install <code>WordFence</code> security plugin, activate it, and set up its firewall. Do regular scans to see, if the problem persists, and follow plugin's instructions.</p>\n\n<p>Third option: if you don't feel comfortable, performing above steps yourself, ask security pros for help. </p>\n"
}
]
| 2017/10/26 | [
"https://wordpress.stackexchange.com/questions/284083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130359/"
]
| a friend received a notification from her host about infected files and asked me to look at it. I don't know wordpress or php so I'm a little lost in what I am looking for. The is the websitescan.txt. I don't know what I am looking at, hoping someone could give me some direction as to what this report is saying and what I can do to fix the problems. thanks
```
Scan started at - Fri Oct 13 13:42:53 EDT 2017
/htdocs/wp-admin/edit-comments_ver1.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/css/colors/midnight/colors-rtl_new.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/css/colors/ectoplasm/colors_indesit.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/css/colors/sunrise/colors.min_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/css/colors/ocean/colors-rtl.min_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/network/site-settings_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/maint/repair_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/includes/taxonomy_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/js/inline-edit-tax_infoold.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-admin/user/admin_bck_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-content/themes/fiore/functions.php:
LONGDEF.PHP.Spam-Links-009N.UNOFFICIAL FOUND
/htdocs/wp-content/themes/fiore/images/thicklines-2x_noversion.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-content/themes/fiore/js/customizer_new.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/SimplePie/HTTP/Parser_bck_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/SimplePie/Content/6f26e1e6_bck_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/Text/Diff_ver1.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/utils/mctabs_bck_old.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/langs/wp-langs-en_infoold.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/skins/lightgray/img/trans_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/plugins/07ab1454_indesit.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/plugins/hr/plugin.min_backup.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/plugins/wpgallery/plugin.min_indesit.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
/htdocs/wp-includes/js/tinymce/plugins/media/plugin_infoold.php:
JCDEF.Obfus.CreateFunc.BackDoorEval-26.UNOFFICIAL FOUND
----------- SCAN SUMMARY -----------
Infected files: 23
Time: 238.961 sec (3 m 58 s)
Scan ended at - Fri Oct 13 13:46:52 EDT 2017
``` | If you have a good full backup of your website, restore your site from it (recommended). Install and set up `WordFence` plugin (as in case of no backup).
If you don't have good backup:
Immediately delete all files from this list. Get a clean copy of your version of WordPress, and clean copy of your theme. Copy over entire theme. Copy over clean `/wp-admin/`, and `/wp-includes/`. Start your website. Install `WordFence` security plugin, activate it, and set up its firewall. Do regular scans to see, if the problem persists, and follow plugin's instructions.
Third option: if you don't feel comfortable, performing above steps yourself, ask security pros for help. |
284,112 | <p>I noticed that my edit post WP editor expands automatically when writing.
However my WP editor instances I use for my other Custom post types don't.</p>
<p>I investigated a bit I and I see that the iframe including the textarea in the built-in edit post has a body which has a "wp-autoresize" class.
The ones of my custom posts don't.
I thought that adding that class would be all I need to allow the autoresize feature. At least, it was worth the try.</p>
<p>So, I try to add this class to the iframe bodies of my CPT plugins like this:</p>
<pre><code>add_filter( 'tiny_mce_before_init', 'wpse_235194_tiny_mce_classes' );
function wpse_235194_tiny_mce_classes( $init_array ){
global $post;
$init_array['body_class'] .= ' ' . join( ' ', 'wp-autoresize' );
return $init_array;
}
</code></pre>
<p>But the class doesn't appear there.</p>
<p>I tried this too (willing then to target each CP iframe id specifically):</p>
<pre><code>$("iframe#_xxx_textarea").contents().find("body").addClass("wp-autoresize");
</code></pre>
<p>No success neither.</p>
<p>Whatever I tried to add a class to an iframe body was just a failure.</p>
<p>So I tried to just bypass this body class approach to add the auto-resize feature for TinyCME in another way:</p>
<pre><code>function init_tinymce_autoresize($initArray){
$initArray['plugins'] = "autoresize";
return $initArray;
}
add_filter('tiny_mce_before_init', 'init_tinymce_autoresize');
</code></pre>
<p>Nope.</p>
<p>And then tried to add a more sophisticated handmade plugin as described here:</p>
<p><a href="https://wordpress.stackexchange.com/questions/72626/tinymce-autoresize">TinyMCE Autoresize</a></p>
<p>But nothing happens neither.</p>
<p>And by nothing, I mean that when my text grows big as I type, the textarea keeps its original height and I have to scroll to see the whole content.</p>
<p>Some I'm stuck as I believe I tried all the standard solutions I found in the previous 3 hours. Now I keep finding the same solutions I tried already.</p>
<p>So how can I achieve an autoresize on custom TinyMCE editors applied to Custom posts?</p>
<p>Thanks.</p>
<p><strong>EDIT:</strong> I've been asked to show the way I registered the CPT:</p>
<pre><code> function xxx_custom_type_init()
{
register_post_type('xxx', array(
'labels' => array(
'name' => 'xxx',
'singular_label' => 'xxx',
'add_new' => 'Ajouter',
'add_new_item' => 'Ajouter un élément',
'new_item' => 'Nouvel élément',
'view_item' => 'Afficher l\'élément',
'edit_item' => 'xxx',
'not_found' => 'Auncun élément trouvé',
'not_found_in_trash' => 'Auncun élément dans la corbeille'),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'supports' => array('')
));
register_taxonomy_for_object_type( 'category', 'xxx' );
}
add_action('init', 'xxx_custom_type_init');
function xxx_custom_type_messages( $messages )
{
global $post, $post_ID;
$messages['xxx'] = array(
1 => sprintf(__('xxx updated. <a href="%s">See xxx</a>','your_text_domain'),esc_url(get_permalink($post_ID))),
4 => __('xxx updated.', 'your_text_domain'),
6 => sprintf(__('xxx published. <a href="%s">See xxx</a>','your_text_domain'),esc_url(get_permalink($post_ID))),
7 => __('xxx saved.','your_text_domain'),
9 => sprintf(__('Elément prévu pour: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Prévisualiser l\'élément</a>','your_text_domain'),
date_i18n(__('M j, Y @ G:i'),strtotime($post->post_date)),esc_url(get_permalink($post_ID))),
10 => sprintf(__('Brouillon mis à jour. <a target="_blank" href="%s">Prévisualiser l\'élément</a>','your_text_domain'),esc_url(add_query_arg('preview','true',get_permalink($post_ID)))),
);
return $messages;
}
add_filter( 'post_updated_messages', 'xxx_custom_type_messages' );
</code></pre>
<p>And here how I added an editor to my CP admin page:</p>
<pre><code><?php
add_action( 'add_meta_boxes', 'xxx_textarea_add_fields_metabox');
function xxx_textarea_add_fields_metabox()
{
add_meta_box(
'xxx_textarea_metabox',
'Intro',
'xxx_textarea_show_fields_metabox',
'xxx',
'side',
'default'
);
}
function xxx_textarea_show_fields_metabox()
{
global $post;
$content = get_post_meta($post->ID, '_xxx_textarea', true);
?>
<style>
iframe#_xxx_textarea_ifr
{width:100%;height:auto !important;display:block;}
iframe#_xxx_textarea_ifr html
{overflow:hidden;display: block;}
iframe#_xxx_textarea_ifr body
{overflow:hidden;display: block;}
#_xxx_textarea
{height:auto;overflow-y: hidden;min-height: 35px;overflow-x: hidden;overflow-y: auto;}
</style>
<?php
$args = array(
'description_name' => '_xxx_textarea',
'teeny' => true,
'quicktags' => false,
'media_buttons' => false,
'tinymce' => array(
'toolbar1'=> 'bold,italic,underline,link,unlink,forecolor',
'toolbar2' => '',
'toolbar3' => ''
)
);
wp_editor( $content, '_xxx_textarea', $args );
wp_nonce_field(plugin_basename(__FILE__), 'xxx_textarea_noncename');
};
add_action('save_post', 'xxx_textarea_save_fields_metabox', 1, 2);
function xxx_textarea_save_fields_metabox($post_id, $post)
{
global $post_id;
if ( !wp_verify_nonce( $_POST['xxx_textarea_noncename'], plugin_basename(__FILE__) )){return $post->ID;}
if ( !current_user_can( 'edit_post', $post->ID )) {return $post->ID;}
if( $post->post_type == 'revision' ) {return;$post->ID;}
if($_POST['_xxx_textarea']) {$xxx_content = $_POST['_xxx_textarea'];}
else{$xxx_content = '';};
if(get_post_meta($post_id, '_xxx_textarea', FALSE)){update_post_meta($post_id, '_xxx_textarea', $xxx_content);}
else{ add_post_meta($post_id, '_xxx_textarea', $xxx_content);};
}
</code></pre>
<p>I hope it helps.</p>
<p>Just FYI, I styled the iframe and body of my CPT exactly the same than the ones I found for the standard edit post.</p>
<p>I added the "!important" flag to the height of the iframe because it seems that, somewhere in a WP file, it's set to 400px. So, this way, it's clearly overridden.</p>
<p>So, I should not expect anything blocking on the CSS part but I can't be absolutely positive about this.</p>
| [
{
"answer_id": 284465,
"author": "Kumar",
"author_id": 32466,
"author_profile": "https://wordpress.stackexchange.com/users/32466",
"pm_score": 3,
"selected": true,
"text": "<p>Finally I got around this.</p>\n\n<p>You need to modify tinymce args passed to wp_editor function. WordPress have a argument <code>wp_autoresize_on</code> to allow the editor to be resized automatically.</p>\n\n<p>So instead of these:</p>\n\n<pre><code>'tinymce' => array(\n 'toolbar1'=> 'bold,italic,underline,link,unlink,forecolor',\n 'toolbar2' => '',\n 'toolbar3' => ''\n )\n</code></pre>\n\n<p>you need to use this:</p>\n\n<pre><code>'tinymce' => array(\n 'autoresize_min_height' => 100,\n 'wp_autoresize_on' => true,\n 'plugins' => 'wpautoresize',\n 'toolbar1' => 'bold,italic,underline,link,unlink,forecolor',\n 'toolbar2' => '',\n ),\n</code></pre>\n\n<p>There are two additional args in here, <code>autoresize_min_height</code>, you can set it to desired height, and second one is <code>'wp_autoresize_on' => true,</code>.\nApart from that you need to pass additional parameter to load the tinymce plugin for auto resizing and i.e <code>'plugins' => 'wpautoresize'</code> and the auto resizing works flawlessly.</p>\n\n<p>With these changes, I'd suggest you add some other checks in your code. Like for the function:</p>\n\n<pre><code>function xxx_textarea_save_fields_metabox($post_id, $post) {\n global $post_id;\n\n if ( !wp_verify_nonce( $_POST['xxx_textarea_noncename'], plugin_basename(__FILE__) )){return $post->ID;} \n if ( !current_user_can( 'edit_post', $post->ID )) {return $post->ID;} \n if( $post->post_type == 'revision' ) {return;$post->ID;}\n\n if($_POST['_xxx_textarea']) {$xxx_content = $_POST['_xxx_textarea'];}\n else{$xxx_content = '';};\n\n if(get_post_meta($post_id, '_xxx_textarea', FALSE))\n {update_post_meta($post_id, '_xxx_textarea', $xxx_content);} \n else{ add_post_meta($post_id, '_xxx_textarea', $xxx_content);}; \n\n }\n</code></pre>\n\n<p>Make sure to add a check for empty $_POST, otherwise you'll get notices on post edit screen.\nI've made the changes and formatted the code ( You should be doing that ), here is the whole code for adding metabox.</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'xxx_textarea_add_fields_metabox' );\nfunction xxx_textarea_add_fields_metabox() {\n add_meta_box(\n 'xxx_textarea_metabox',\n 'Intro',\n 'xxx_textarea_show_fields_metabox',\n 'new_xxx',\n 'side',\n 'default'\n );\n}\n\nfunction xxx_textarea_show_fields_metabox() {\n global $post;\n $content = get_post_meta( $post->ID, '_xxx_textarea', true );\n //Loads the editor to allow adding fresh content if there is no content already\n $content = empty( $content ) ? '' : $content;\n\n $args = array(\n 'description_name' => 'xxx_textarea',\n 'teeny' => true,\n 'quicktags' => false,\n 'media_buttons' => false,\n 'tinymce' => array(\n 'autoresize_min_height' => 100,\n 'wp_autoresize_on' => true,\n 'plugins' => 'wpautoresize',\n 'toolbar1' => 'bold,italic,underline,link,unlink,forecolor',\n 'toolbar2' => '',\n ),\n );\n wp_editor( $content, '_xxx_textarea', $args );\n wp_nonce_field( plugin_basename( __FILE__ ), 'xxx_textarea_noncename' );\n}\n\nadd_action( 'save_post', 'xxx_textarea_save_fields_metabox', 1, 2 );\nfunction xxx_textarea_save_fields_metabox( $post_id, $post ) {\n global $post_id;\n\n //Avoids notice and warnings\n if( empty( $_POST ) ) {\n return $post->ID;\n }\n if ( !empty( $_POST['xxx_textarea_noncename'] ) && ! wp_verify_nonce( $_POST['xxx_textarea_noncename'], plugin_basename( __FILE__ ) ) ) {\n return $post->ID;\n }\n if ( ! current_user_can( 'edit_post', $post->ID ) ) {\n return $post->ID;\n }\n if ( $post->post_type == 'revision' ) {\n return;\n $post->ID;\n }\n\n if ( $_POST['_xxx_textarea'] ) {\n $xxx_content = $_POST['_xxx_textarea'];\n } else {\n $xxx_content = '';\n };\n\n if ( get_post_meta( $post_id, '_xxx_textarea', false ) ) {\n update_post_meta( $post_id, '_xxx_textarea', $xxx_content );\n } else {\n add_post_meta( $post_id, '_xxx_textarea', $xxx_content );\n };\n}\n</code></pre>\n\n<p>That should do it.\nCorresponding Post: <a href=\"http://codechutney.com/auto-resize-wp-editor-custom-instance/\" rel=\"nofollow noreferrer\">http://codechutney.com/auto-resize-wp-editor-custom-instance/</a></p>\n"
},
{
"answer_id": 372938,
"author": "FroboZ",
"author_id": 193068,
"author_profile": "https://wordpress.stackexchange.com/users/193068",
"pm_score": 0,
"selected": false,
"text": "<p>I realise this is several years later and I don't know if this functionality was available at the time but now its as easy as passing wp_autoresize_on as true to the setup config</p>\n<p><strong>In javascript</strong></p>\n<pre><code>wp.editor.initialize('case-'+caseid+'-post_content', {'tinymce': {\n 'wp_autoresize_on' : true\n }, 'quicktags': true, 'mediaButtons': true});\n</code></pre>\n"
}
]
| 2017/10/26 | [
"https://wordpress.stackexchange.com/questions/284112",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23404/"
]
| I noticed that my edit post WP editor expands automatically when writing.
However my WP editor instances I use for my other Custom post types don't.
I investigated a bit I and I see that the iframe including the textarea in the built-in edit post has a body which has a "wp-autoresize" class.
The ones of my custom posts don't.
I thought that adding that class would be all I need to allow the autoresize feature. At least, it was worth the try.
So, I try to add this class to the iframe bodies of my CPT plugins like this:
```
add_filter( 'tiny_mce_before_init', 'wpse_235194_tiny_mce_classes' );
function wpse_235194_tiny_mce_classes( $init_array ){
global $post;
$init_array['body_class'] .= ' ' . join( ' ', 'wp-autoresize' );
return $init_array;
}
```
But the class doesn't appear there.
I tried this too (willing then to target each CP iframe id specifically):
```
$("iframe#_xxx_textarea").contents().find("body").addClass("wp-autoresize");
```
No success neither.
Whatever I tried to add a class to an iframe body was just a failure.
So I tried to just bypass this body class approach to add the auto-resize feature for TinyCME in another way:
```
function init_tinymce_autoresize($initArray){
$initArray['plugins'] = "autoresize";
return $initArray;
}
add_filter('tiny_mce_before_init', 'init_tinymce_autoresize');
```
Nope.
And then tried to add a more sophisticated handmade plugin as described here:
[TinyMCE Autoresize](https://wordpress.stackexchange.com/questions/72626/tinymce-autoresize)
But nothing happens neither.
And by nothing, I mean that when my text grows big as I type, the textarea keeps its original height and I have to scroll to see the whole content.
Some I'm stuck as I believe I tried all the standard solutions I found in the previous 3 hours. Now I keep finding the same solutions I tried already.
So how can I achieve an autoresize on custom TinyMCE editors applied to Custom posts?
Thanks.
**EDIT:** I've been asked to show the way I registered the CPT:
```
function xxx_custom_type_init()
{
register_post_type('xxx', array(
'labels' => array(
'name' => 'xxx',
'singular_label' => 'xxx',
'add_new' => 'Ajouter',
'add_new_item' => 'Ajouter un élément',
'new_item' => 'Nouvel élément',
'view_item' => 'Afficher l\'élément',
'edit_item' => 'xxx',
'not_found' => 'Auncun élément trouvé',
'not_found_in_trash' => 'Auncun élément dans la corbeille'),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'supports' => array('')
));
register_taxonomy_for_object_type( 'category', 'xxx' );
}
add_action('init', 'xxx_custom_type_init');
function xxx_custom_type_messages( $messages )
{
global $post, $post_ID;
$messages['xxx'] = array(
1 => sprintf(__('xxx updated. <a href="%s">See xxx</a>','your_text_domain'),esc_url(get_permalink($post_ID))),
4 => __('xxx updated.', 'your_text_domain'),
6 => sprintf(__('xxx published. <a href="%s">See xxx</a>','your_text_domain'),esc_url(get_permalink($post_ID))),
7 => __('xxx saved.','your_text_domain'),
9 => sprintf(__('Elément prévu pour: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Prévisualiser l\'élément</a>','your_text_domain'),
date_i18n(__('M j, Y @ G:i'),strtotime($post->post_date)),esc_url(get_permalink($post_ID))),
10 => sprintf(__('Brouillon mis à jour. <a target="_blank" href="%s">Prévisualiser l\'élément</a>','your_text_domain'),esc_url(add_query_arg('preview','true',get_permalink($post_ID)))),
);
return $messages;
}
add_filter( 'post_updated_messages', 'xxx_custom_type_messages' );
```
And here how I added an editor to my CP admin page:
```
<?php
add_action( 'add_meta_boxes', 'xxx_textarea_add_fields_metabox');
function xxx_textarea_add_fields_metabox()
{
add_meta_box(
'xxx_textarea_metabox',
'Intro',
'xxx_textarea_show_fields_metabox',
'xxx',
'side',
'default'
);
}
function xxx_textarea_show_fields_metabox()
{
global $post;
$content = get_post_meta($post->ID, '_xxx_textarea', true);
?>
<style>
iframe#_xxx_textarea_ifr
{width:100%;height:auto !important;display:block;}
iframe#_xxx_textarea_ifr html
{overflow:hidden;display: block;}
iframe#_xxx_textarea_ifr body
{overflow:hidden;display: block;}
#_xxx_textarea
{height:auto;overflow-y: hidden;min-height: 35px;overflow-x: hidden;overflow-y: auto;}
</style>
<?php
$args = array(
'description_name' => '_xxx_textarea',
'teeny' => true,
'quicktags' => false,
'media_buttons' => false,
'tinymce' => array(
'toolbar1'=> 'bold,italic,underline,link,unlink,forecolor',
'toolbar2' => '',
'toolbar3' => ''
)
);
wp_editor( $content, '_xxx_textarea', $args );
wp_nonce_field(plugin_basename(__FILE__), 'xxx_textarea_noncename');
};
add_action('save_post', 'xxx_textarea_save_fields_metabox', 1, 2);
function xxx_textarea_save_fields_metabox($post_id, $post)
{
global $post_id;
if ( !wp_verify_nonce( $_POST['xxx_textarea_noncename'], plugin_basename(__FILE__) )){return $post->ID;}
if ( !current_user_can( 'edit_post', $post->ID )) {return $post->ID;}
if( $post->post_type == 'revision' ) {return;$post->ID;}
if($_POST['_xxx_textarea']) {$xxx_content = $_POST['_xxx_textarea'];}
else{$xxx_content = '';};
if(get_post_meta($post_id, '_xxx_textarea', FALSE)){update_post_meta($post_id, '_xxx_textarea', $xxx_content);}
else{ add_post_meta($post_id, '_xxx_textarea', $xxx_content);};
}
```
I hope it helps.
Just FYI, I styled the iframe and body of my CPT exactly the same than the ones I found for the standard edit post.
I added the "!important" flag to the height of the iframe because it seems that, somewhere in a WP file, it's set to 400px. So, this way, it's clearly overridden.
So, I should not expect anything blocking on the CSS part but I can't be absolutely positive about this. | Finally I got around this.
You need to modify tinymce args passed to wp\_editor function. WordPress have a argument `wp_autoresize_on` to allow the editor to be resized automatically.
So instead of these:
```
'tinymce' => array(
'toolbar1'=> 'bold,italic,underline,link,unlink,forecolor',
'toolbar2' => '',
'toolbar3' => ''
)
```
you need to use this:
```
'tinymce' => array(
'autoresize_min_height' => 100,
'wp_autoresize_on' => true,
'plugins' => 'wpautoresize',
'toolbar1' => 'bold,italic,underline,link,unlink,forecolor',
'toolbar2' => '',
),
```
There are two additional args in here, `autoresize_min_height`, you can set it to desired height, and second one is `'wp_autoresize_on' => true,`.
Apart from that you need to pass additional parameter to load the tinymce plugin for auto resizing and i.e `'plugins' => 'wpautoresize'` and the auto resizing works flawlessly.
With these changes, I'd suggest you add some other checks in your code. Like for the function:
```
function xxx_textarea_save_fields_metabox($post_id, $post) {
global $post_id;
if ( !wp_verify_nonce( $_POST['xxx_textarea_noncename'], plugin_basename(__FILE__) )){return $post->ID;}
if ( !current_user_can( 'edit_post', $post->ID )) {return $post->ID;}
if( $post->post_type == 'revision' ) {return;$post->ID;}
if($_POST['_xxx_textarea']) {$xxx_content = $_POST['_xxx_textarea'];}
else{$xxx_content = '';};
if(get_post_meta($post_id, '_xxx_textarea', FALSE))
{update_post_meta($post_id, '_xxx_textarea', $xxx_content);}
else{ add_post_meta($post_id, '_xxx_textarea', $xxx_content);};
}
```
Make sure to add a check for empty $\_POST, otherwise you'll get notices on post edit screen.
I've made the changes and formatted the code ( You should be doing that ), here is the whole code for adding metabox.
```
add_action( 'add_meta_boxes', 'xxx_textarea_add_fields_metabox' );
function xxx_textarea_add_fields_metabox() {
add_meta_box(
'xxx_textarea_metabox',
'Intro',
'xxx_textarea_show_fields_metabox',
'new_xxx',
'side',
'default'
);
}
function xxx_textarea_show_fields_metabox() {
global $post;
$content = get_post_meta( $post->ID, '_xxx_textarea', true );
//Loads the editor to allow adding fresh content if there is no content already
$content = empty( $content ) ? '' : $content;
$args = array(
'description_name' => 'xxx_textarea',
'teeny' => true,
'quicktags' => false,
'media_buttons' => false,
'tinymce' => array(
'autoresize_min_height' => 100,
'wp_autoresize_on' => true,
'plugins' => 'wpautoresize',
'toolbar1' => 'bold,italic,underline,link,unlink,forecolor',
'toolbar2' => '',
),
);
wp_editor( $content, '_xxx_textarea', $args );
wp_nonce_field( plugin_basename( __FILE__ ), 'xxx_textarea_noncename' );
}
add_action( 'save_post', 'xxx_textarea_save_fields_metabox', 1, 2 );
function xxx_textarea_save_fields_metabox( $post_id, $post ) {
global $post_id;
//Avoids notice and warnings
if( empty( $_POST ) ) {
return $post->ID;
}
if ( !empty( $_POST['xxx_textarea_noncename'] ) && ! wp_verify_nonce( $_POST['xxx_textarea_noncename'], plugin_basename( __FILE__ ) ) ) {
return $post->ID;
}
if ( ! current_user_can( 'edit_post', $post->ID ) ) {
return $post->ID;
}
if ( $post->post_type == 'revision' ) {
return;
$post->ID;
}
if ( $_POST['_xxx_textarea'] ) {
$xxx_content = $_POST['_xxx_textarea'];
} else {
$xxx_content = '';
};
if ( get_post_meta( $post_id, '_xxx_textarea', false ) ) {
update_post_meta( $post_id, '_xxx_textarea', $xxx_content );
} else {
add_post_meta( $post_id, '_xxx_textarea', $xxx_content );
};
}
```
That should do it.
Corresponding Post: <http://codechutney.com/auto-resize-wp-editor-custom-instance/> |
284,122 | <p>I'd like to develop pagination into my theme, FluX, as well as some other things, which I'll outline soon on GitHub. But pagination for my articles template is really high on the list. Can anyone tell me the best way to go about this? It needs to be number-based with buttons for previous and next, and work with the current loop I use (a foreach loop instead of "the loop")</p>
| [
{
"answer_id": 284165,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>Most of pagination logic in core naturally deals with native data structures, such as post loops, comments, and so on.</p>\n\n<p>There is a low level <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\"><code>paginate_links()</code></a> functions, which allows you to construct arbitrary pagination logic. However you will be on your own with a lot of remaining stuff, such as query variables, rewrite, and so on.</p>\n"
},
{
"answer_id": 284169,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>Paginations mostly rely on the global <code>$wp_query</code> variable to generate the data. Using <code>get_posts()</code> will not generate that, because it returns an array of posts, not an instance of the <code>WP_Query()</code> class itself. As a result, you don't have access to class's methods, such as <code>$query->max_num_pages</code>.</p>\n\n<p>You can use a plugin to add pagination (such as <a href=\"https://wordpress.org/plugins/wp-pagenavi/\" rel=\"nofollow noreferrer\">WP-PageNavi</a> by Lester Chan) which supports custom queries, or you can write your own.</p>\n\n<p>Here is a piece of code that will create a simple pagination for your queries. But notice, you have to use <code>WP_Query()</code>, not <code>get_posts()</code>:</p>\n\n<pre><code>function get_pagination( $query = null ) {\n if( is_singular() )\n return;\n // Check if any custom query is passed to the function\n if ($query == null ) {\n global $wp_query;\n } else {\n $wp_query = $query;\n }\n /** Stop execution if there's only 1 page */\n if( $wp_query->max_num_pages <= 1 )\n return;\n $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;\n $max = intval( $wp_query->max_num_pages );\n /** Add current page to the array */\n if ( $paged >= 1 )\n $links[] = $paged;\n /** Add the pages around the current page to the array */\n if ( $paged >= 3 ) {\n $links[] = $paged - 1;\n $links[] = $paged - 2;\n }\n if ( ( $paged + 2 ) <= $max ) {\n $links[] = $paged + 2;\n $links[] = $paged + 1;\n }\n echo '<div class=\"photogram-navigation\">' . \"\\n\";\n /** Previous Post Link */\n if ( get_previous_posts_link() )\n printf( '<li>%s</li>' . \"\\n\", get_previous_posts_link() );\n /** Link to first page, plus ellipses if necessary */\n if ( ! in_array( 1, $links ) ) {\n $class = 1 == $paged ? ' class=\"active\"' : '';\n printf( '<li%s><a href=\"%s\">%s</a></li>' . \"\\n\", $class, esc_url( get_pagenum_link( 1 ) ), '1' );\n if ( ! in_array( 2, $links ) )\n echo '<li>...</li>';\n }\n /** Link to current page, plus 2 pages in either direction if necessary */\n sort( $links );\n foreach ( (array) $links as $link ) {\n $class = $paged == $link ? ' class=\"active\"' : '';\n printf( '<li%s><a href=\"%s\">%s</a></li>' . \"\\n\", $class, esc_url( get_pagenum_link( $link ) ), $link );\n }\n /** Link to last page, plus ellipses if necessary */\n if ( ! in_array( $max, $links ) ) {\n if ( ! in_array( $max - 1, $links ) )\n echo '<li>...</li>' . \"\\n\";\n $class = $paged == $max ? ' class=\"active\"' : '';\n printf( '<li%s><a href=\"%s\">%s</a></li>' . \"\\n\", $class, esc_url( get_pagenum_link( $max ) ), $max );\n }\n /** Next Post Link */\n if ( get_next_posts_link() )\n printf( '<li>%s</li>' . \"\\n\", get_next_posts_link() );\n echo '</ul></div>' . \"\\n\";\n}\n</code></pre>\n\n<p>Now you can output your pagination by using <code>get_pagination()</code> in your archives, or by using <code>get_pagination( $my_query )</code> and using it anywhere you wish ( <code>$my_query</code> is your custom query).</p>\n"
}
]
| 2017/10/27 | [
"https://wordpress.stackexchange.com/questions/284122",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130378/"
]
| I'd like to develop pagination into my theme, FluX, as well as some other things, which I'll outline soon on GitHub. But pagination for my articles template is really high on the list. Can anyone tell me the best way to go about this? It needs to be number-based with buttons for previous and next, and work with the current loop I use (a foreach loop instead of "the loop") | Paginations mostly rely on the global `$wp_query` variable to generate the data. Using `get_posts()` will not generate that, because it returns an array of posts, not an instance of the `WP_Query()` class itself. As a result, you don't have access to class's methods, such as `$query->max_num_pages`.
You can use a plugin to add pagination (such as [WP-PageNavi](https://wordpress.org/plugins/wp-pagenavi/) by Lester Chan) which supports custom queries, or you can write your own.
Here is a piece of code that will create a simple pagination for your queries. But notice, you have to use `WP_Query()`, not `get_posts()`:
```
function get_pagination( $query = null ) {
if( is_singular() )
return;
// Check if any custom query is passed to the function
if ($query == null ) {
global $wp_query;
} else {
$wp_query = $query;
}
/** Stop execution if there's only 1 page */
if( $wp_query->max_num_pages <= 1 )
return;
$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
$max = intval( $wp_query->max_num_pages );
/** Add current page to the array */
if ( $paged >= 1 )
$links[] = $paged;
/** Add the pages around the current page to the array */
if ( $paged >= 3 ) {
$links[] = $paged - 1;
$links[] = $paged - 2;
}
if ( ( $paged + 2 ) <= $max ) {
$links[] = $paged + 2;
$links[] = $paged + 1;
}
echo '<div class="photogram-navigation">' . "\n";
/** Previous Post Link */
if ( get_previous_posts_link() )
printf( '<li>%s</li>' . "\n", get_previous_posts_link() );
/** Link to first page, plus ellipses if necessary */
if ( ! in_array( 1, $links ) ) {
$class = 1 == $paged ? ' class="active"' : '';
printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );
if ( ! in_array( 2, $links ) )
echo '<li>...</li>';
}
/** Link to current page, plus 2 pages in either direction if necessary */
sort( $links );
foreach ( (array) $links as $link ) {
$class = $paged == $link ? ' class="active"' : '';
printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
}
/** Link to last page, plus ellipses if necessary */
if ( ! in_array( $max, $links ) ) {
if ( ! in_array( $max - 1, $links ) )
echo '<li>...</li>' . "\n";
$class = $paged == $max ? ' class="active"' : '';
printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
}
/** Next Post Link */
if ( get_next_posts_link() )
printf( '<li>%s</li>' . "\n", get_next_posts_link() );
echo '</ul></div>' . "\n";
}
```
Now you can output your pagination by using `get_pagination()` in your archives, or by using `get_pagination( $my_query )` and using it anywhere you wish ( `$my_query` is your custom query). |
284,146 | <p>Our website is being flooded with thousands of page requests. The access logs looks like this:</p>
<pre><code>**.**.250.*9 - - [24/Oct/2017:09:16:32 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:32 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:33 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:33 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:33 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:34 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:34 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:34 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
</code></pre>
<p>Other than blocking the IPs manually what can we do to stop these attacks?</p>
| [
{
"answer_id": 284148,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 2,
"selected": false,
"text": "<p>First of all, report whoever is doing it.</p>\n\n<p>You obviously could block anything with a query-string that contains <code>screw-you</code>, but that'll only help in this case.</p>\n\n<p>Maybe Drop any requests with HTTP/1.0 (browser don't use it, and \"good\" bots like google don't either, but if you need to provide access to special tools, you might not want to do this), but you should keep a close watch over what requests get dropped by this to make sure that you don't lose any legitimate traffic.</p>\n\n<p>And of course, there are technical solutions that try to automatically discover this kind of traffic and block it. Have a look at CloudFlare, Incapsula, StackPath etc. </p>\n"
},
{
"answer_id": 284167,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>From WordPress point of view the most vulnerable part is resource–intensive loading of WordPress core and page generation.</p>\n\n<p>So for a primitive attack your priority is to <em>never let these reach WP core</em>. That would mean intercepting them at some stage before at web server, reverse proxy, or firewall level. Depends on server stack and configuration options available to you.</p>\n\n<p>If you use managed hosting contacting them is a good idea both for awareness and to hear their recommendations.</p>\n"
},
{
"answer_id": 284192,
"author": "CᴴᵁᴮᴮʸNᴵᴺᴶᴬ",
"author_id": 28557,
"author_profile": "https://wordpress.stackexchange.com/users/28557",
"pm_score": 2,
"selected": false,
"text": "<p>If you have access to the server you have some options like using mod_evasive (if using apache2) - this will throttle the requests.</p>\n\n<p>It's also worth putting your website on some cache, like WP Super Cache, force preloading of caching and let it serve static files, it will reduce the chances of you bottlenecking.</p>\n"
}
]
| 2017/10/27 | [
"https://wordpress.stackexchange.com/questions/284146",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130404/"
]
| Our website is being flooded with thousands of page requests. The access logs looks like this:
```
**.**.250.*9 - - [24/Oct/2017:09:16:32 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:32 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:33 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:33 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:33 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:34 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:34 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
**.**.250.*9 - - [24/Oct/2017:09:16:34 -0400] "GET /about-our-company/?screw-you HTTP/1.0" 200 14959 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
```
Other than blocking the IPs manually what can we do to stop these attacks? | First of all, report whoever is doing it.
You obviously could block anything with a query-string that contains `screw-you`, but that'll only help in this case.
Maybe Drop any requests with HTTP/1.0 (browser don't use it, and "good" bots like google don't either, but if you need to provide access to special tools, you might not want to do this), but you should keep a close watch over what requests get dropped by this to make sure that you don't lose any legitimate traffic.
And of course, there are technical solutions that try to automatically discover this kind of traffic and block it. Have a look at CloudFlare, Incapsula, StackPath etc. |
284,164 | <p>The shop page of WooCommerce is based on the <code>archive-product.php</code> file. In this file, a loop is called: </p>
<pre><code> <?php woocommerce_product_loop_start(); ?>
<?php woocommerce_product_subcategories(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/**
* woocommerce_shop_loop hook.
*
* @hooked WC_Structured_Data::generate_product_data() - 10
*/
do_action( 'woocommerce_shop_loop' );
?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
</code></pre>
<p>In this loop, product data is generated: </p>
<pre><code>public function generate_product_data( $product = null ) {
if ( ! is_object( $product ) ) {
global $product;
}
if ( ! is_a( $product, 'WC_Product' ) ) {
return;
}
$shop_name = get_bloginfo( 'name' );
$shop_url = home_url();
$currency = get_woocommerce_currency();
$markup = array();
$markup['@type'] = 'Product';
$markup['@id'] = get_permalink( $product->get_id() );
$markup['url'] = $markup['@id'];
$markup['name'] = $product->get_name();
if ( apply_filters( 'woocommerce_structured_data_product_limit', is_product_taxonomy() || is_shop() ) ) {
$this->set_data( apply_filters( 'woocommerce_structured_data_product_limited', $markup, $product ) );
return;
}
if ( '' !== $product->get_price() ) {
$markup_offer = array(
'@type' => 'Offer',
'priceCurrency' => $currency,
'availability' => 'https://schema.org/' . $stock = ( $product->is_in_stock() ? 'InStock' : 'OutOfStock' ),
'sku' => $product->get_sku(),
'image' => wp_get_attachment_url( $product->get_image_id() ),
'description' => $product->get_description(),
'seller' => array(
'@type' => 'Organization',
'name' => $shop_name,
'url' => $shop_url,
),
);
...
</code></pre>
<p>There is a line in the <code>generate_product_data function</code> calling for the product description.</p>
<p>I'd like to adapt my template or add a function in my <code>functions.php</code> file so the description is no longer added to my product archive page. However, it should be added to my single product page. Product archive page & single product page use the same <code>woocommerce_shop_loop</code> however.</p>
<p>How should I adapt the template or add code to my functions file to remove this product description? I have long descriptions for my products & don't want these to be added to the product archive pages. </p>
| [
{
"answer_id": 284171,
"author": "BarrieO",
"author_id": 129008,
"author_profile": "https://wordpress.stackexchange.com/users/129008",
"pm_score": 2,
"selected": true,
"text": "<p>The solution was for the following for <strong>the7 template</strong>:\n<a href=\"https://i.stack.imgur.com/up3GK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/up3GK.png\" alt=\"Solution\"></a></p>\n\n<p>If anybody knows how to implement this in the <code>functions.php</code> file so I don't have to update this when my theme updates, shoot!</p>\n"
},
{
"answer_id": 306301,
"author": "Akshat",
"author_id": 114978,
"author_profile": "https://wordpress.stackexchange.com/users/114978",
"pm_score": 0,
"selected": false,
"text": "<p>For this specific theme you can add</p>\n\n<pre><code>remove_action('woocommerce_shop_loop_item_desc','dt_woocommerce_template_loop_product_short_desc', 15);\n</code></pre>\n\n<p>in functions.php of the child theme to remove the action, <code>dt_woocommerce_template_loop_product_short_desc</code> this function is added to <code>woocommerce_shop_loop_item_desc</code>, by using remove_action it'll be removed.</p>\n\n<p>Update: It seems like you are removing action before init, child theme's function is executed before parent theme, kindly try</p>\n\n<pre><code>function remove_parent_action() { \n remove_action('woocommerce_shop_loop_item_desc','dt_woocommerce_template_loop_product_short_desc', 15);\n}\nadd_filter('init', 'remove_parent_action');\n</code></pre>\n"
},
{
"answer_id": 393834,
"author": "Shawn W",
"author_id": 63357,
"author_profile": "https://wordpress.stackexchange.com/users/63357",
"pm_score": 0,
"selected": false,
"text": "<p>2021 working solution. In your child theme, add this to functions.php</p>\n<pre><code>/**\n * Products Shop Archive Short Description\n *\n * @param string $string\n * @return string\n */\n\nfunction woo_archive_desc( $string ) {\n global $post;\n\n// Don't display the description on search results page. \n\nif ( is_search() ) {\n return;\n}\n\n// Only run function if on Woo Shop Page\n\nif ( is_post_type_archive( 'product' ) ) {\n\n $shop_page = get_post( wc_get_page_id( 'shop' ) && in_array( absint( get_query_var( 'paged' ) ), array( 0, 1 ), true ) );\n if ( $shop_page ) {\n $des = $post->post_excerpt;\n\n// do something like empty above var, then echo\n \n echo '<div class="woocommerce-product-details__short-description"><p>' . $des . '</p></div>';\n\n }\n}\n}\nadd_action( 'woocommerce_after_shop_loop_item_title', 'woo_archive_desc', 4, 1 );\n</code></pre>\n<p>Lastly move...</p>\n<p><code>plugins/woocommerce/single-product/short-description.php</code> to <code>themes/{yourthemehere}/woocommerce/single-product/short-description.php</code></p>\n<p>Change this code block adding <code>! is_product()</code> to condition.</p>\n<pre><code>global $post;\n\n$short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt );\n\nif ( ! $short_description || ! is_product() ) {\n return;\n}\n</code></pre>\n"
}
]
| 2017/10/27 | [
"https://wordpress.stackexchange.com/questions/284164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129008/"
]
| The shop page of WooCommerce is based on the `archive-product.php` file. In this file, a loop is called:
```
<?php woocommerce_product_loop_start(); ?>
<?php woocommerce_product_subcategories(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/**
* woocommerce_shop_loop hook.
*
* @hooked WC_Structured_Data::generate_product_data() - 10
*/
do_action( 'woocommerce_shop_loop' );
?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
```
In this loop, product data is generated:
```
public function generate_product_data( $product = null ) {
if ( ! is_object( $product ) ) {
global $product;
}
if ( ! is_a( $product, 'WC_Product' ) ) {
return;
}
$shop_name = get_bloginfo( 'name' );
$shop_url = home_url();
$currency = get_woocommerce_currency();
$markup = array();
$markup['@type'] = 'Product';
$markup['@id'] = get_permalink( $product->get_id() );
$markup['url'] = $markup['@id'];
$markup['name'] = $product->get_name();
if ( apply_filters( 'woocommerce_structured_data_product_limit', is_product_taxonomy() || is_shop() ) ) {
$this->set_data( apply_filters( 'woocommerce_structured_data_product_limited', $markup, $product ) );
return;
}
if ( '' !== $product->get_price() ) {
$markup_offer = array(
'@type' => 'Offer',
'priceCurrency' => $currency,
'availability' => 'https://schema.org/' . $stock = ( $product->is_in_stock() ? 'InStock' : 'OutOfStock' ),
'sku' => $product->get_sku(),
'image' => wp_get_attachment_url( $product->get_image_id() ),
'description' => $product->get_description(),
'seller' => array(
'@type' => 'Organization',
'name' => $shop_name,
'url' => $shop_url,
),
);
...
```
There is a line in the `generate_product_data function` calling for the product description.
I'd like to adapt my template or add a function in my `functions.php` file so the description is no longer added to my product archive page. However, it should be added to my single product page. Product archive page & single product page use the same `woocommerce_shop_loop` however.
How should I adapt the template or add code to my functions file to remove this product description? I have long descriptions for my products & don't want these to be added to the product archive pages. | The solution was for the following for **the7 template**:
[](https://i.stack.imgur.com/up3GK.png)
If anybody knows how to implement this in the `functions.php` file so I don't have to update this when my theme updates, shoot! |
284,177 | <p>Any reason why wp_cache_set not to work? I have spun my wheels trying to figure out why these are not working. Any suggestions? These functions are supposed to help me cache the results to a key/object and then leverage the key/object to display the info. However, they are not storing key/object </p>
<pre><code>$related_post_ids = wp_cache_get( 'related_post_ids' );
if ( false === $related_post_ids ) {
//seting args and run query
$the_query = new WP_Query( $args );
wp_cache_set('related_post_ids', $the_query, '', 300 );
}
</code></pre>
| [
{
"answer_id": 284188,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": false,
"text": "<p>The <code>wp_cache_*()</code> functions are non-persistent caches which means that they only last during the current page request. This would be beneficial if you're requesting the same information multiple times during page load. For example, if you're showing recent posts in the header, content section, and sidebar ( calling the same code 3 times to retrieve recent posts ) then caching the results would be beneficial. Check out The Codex on <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache\" rel=\"noreferrer\">WP Object Cache</a> for more information.</p>\n\n<p>If you want to save these through multiple page page loads but also expire them eventually, you may want to save them as a <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"noreferrer\">transient</a>. They work the same way as the WP Object Cache but they are saved to the database for a set amount of time. If requested and that time has passed, the transient becomes expired and returns false.</p>\n\n<pre><code>$related_post_ids = get_transient( 'theme_related_post_ids' );\n\nif( false === $related_post_ids ) {\n\n $args = array(\n 'fields' => 'ids', // If we only need IDs, just return IDs\n );\n $the_query = get_posts( $args );\n\n if( ! empty( $the_query ) ) {\n set_transient( 'theme_related_post_ids', $the_query, 300 );\n }\n\n}\n</code></pre>\n\n<p>Depending on how many recent posts you're planning to get, this is probably fruitless. 300 miliseconds is not a very long time and it would probably be faster just calling the query itself during load than attempting to store and retrieve them via cache, but I don't know your entire use-case. </p>\n"
},
{
"answer_id": 356452,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": 0,
"selected": false,
"text": "<p>I guess you are thinking that this function should set a <code>json object</code> in browser <code>local storage</code> or <code>cache storage</code>. But this is not the case. This function still cache but in a non-persistent way. Following example may help you understand it better.</p>\n\n<p><strong>I have 5 posts displaying on my homepage.</strong></p>\n\n<p>When page is refreshed 5 posts are loaded which loads template part <code>'template-parts/content/content.php'</code>.</p>\n\n<p>Now I have created my own function to load the template for the first time and cache it for rest of 4 times.</p>\n\n<pre><code>$cache_key = 'home-template-parts';\n$template = wp_cache_get($cache_key, 'template_cache_group');\nif (!$template) {\n $template = locate_template(\n array(\n template_path() . \"{$slug}-{$name}.php\",\n template_path() . \"{$slug}.php\",\n ),\n false,\n false\n );\n wp_cache_set($cache_key, $template, 'template_cache_group');\n}\nload_template($template, false);\n</code></pre>\n\n<p>Similarly WordPress <code>loop</code>, <code>database queries</code> or anything that is loading multiple times can be cached.</p>\n\n<p><strong>wp_transient API</strong></p>\n\n<p>On other hand if you do not use wp_transient api carefully your database <code>wp_options</code> table will grow slowly over the time. And if table size is large your wp_transient api will be slow.</p>\n"
}
]
| 2017/10/27 | [
"https://wordpress.stackexchange.com/questions/284177",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130304/"
]
| Any reason why wp\_cache\_set not to work? I have spun my wheels trying to figure out why these are not working. Any suggestions? These functions are supposed to help me cache the results to a key/object and then leverage the key/object to display the info. However, they are not storing key/object
```
$related_post_ids = wp_cache_get( 'related_post_ids' );
if ( false === $related_post_ids ) {
//seting args and run query
$the_query = new WP_Query( $args );
wp_cache_set('related_post_ids', $the_query, '', 300 );
}
``` | The `wp_cache_*()` functions are non-persistent caches which means that they only last during the current page request. This would be beneficial if you're requesting the same information multiple times during page load. For example, if you're showing recent posts in the header, content section, and sidebar ( calling the same code 3 times to retrieve recent posts ) then caching the results would be beneficial. Check out The Codex on [WP Object Cache](https://codex.wordpress.org/Class_Reference/WP_Object_Cache) for more information.
If you want to save these through multiple page page loads but also expire them eventually, you may want to save them as a [transient](https://codex.wordpress.org/Transients_API). They work the same way as the WP Object Cache but they are saved to the database for a set amount of time. If requested and that time has passed, the transient becomes expired and returns false.
```
$related_post_ids = get_transient( 'theme_related_post_ids' );
if( false === $related_post_ids ) {
$args = array(
'fields' => 'ids', // If we only need IDs, just return IDs
);
$the_query = get_posts( $args );
if( ! empty( $the_query ) ) {
set_transient( 'theme_related_post_ids', $the_query, 300 );
}
}
```
Depending on how many recent posts you're planning to get, this is probably fruitless. 300 miliseconds is not a very long time and it would probably be faster just calling the query itself during load than attempting to store and retrieve them via cache, but I don't know your entire use-case. |
284,182 | <p>Looking for possible solutions, because I'm pretty much lost as to why it happens.</p>
<p>In WP Admin, all my pages, when I want to modify them, are OK. But one throws a 500 error.</p>
<p>What could be the problem? The same code is loaded in all pages, AFAIK.</p>
<p>So how can one 500, when the others are ok?</p>
<p>Plugins are:</p>
<ul>
<li>ACF</li>
<li>Contact Form 7</li>
<li>oAuth Twitter feed for developers</li>
<li>Regenerate Thumbnails</li>
<li>Transient Manager</li>
<li>WP Mail Logging</li>
<li>WPML</li>
<li>Yoast</li>
</ul>
| [
{
"answer_id": 284184,
"author": "Tex0gen",
"author_id": 97070,
"author_profile": "https://wordpress.stackexchange.com/users/97070",
"pm_score": 2,
"selected": false,
"text": "<p>It means you have a PHP syntax error. You need to consult the logs or turn on debug mode. In wp-config.php in your root wordpress directory, find the line as follows:</p>\n\n<pre><code>define( 'WP_DEBUG', false );\n</code></pre>\n\n<p>and change it to: </p>\n\n<pre><code>define( 'WP_DEBUG', true );\n</code></pre>\n\n<p>Refresh your page that appears blank to find the error. If it still does not show up, it means you may need to change your php.ini settings to display errors.</p>\n"
},
{
"answer_id": 284197,
"author": "Fredy31",
"author_id": 8895,
"author_profile": "https://wordpress.stackexchange.com/users/8895",
"pm_score": 1,
"selected": false,
"text": "<p>Found out what it was:</p>\n\n<p>My ACF was writing a novel every time the page was saved, and because of the excess of heavy revisions it crashed.</p>\n\n<p>I installed the WP-Sweep plugins, and swept the revisions.</p>\n"
}
]
| 2017/10/27 | [
"https://wordpress.stackexchange.com/questions/284182",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8895/"
]
| Looking for possible solutions, because I'm pretty much lost as to why it happens.
In WP Admin, all my pages, when I want to modify them, are OK. But one throws a 500 error.
What could be the problem? The same code is loaded in all pages, AFAIK.
So how can one 500, when the others are ok?
Plugins are:
* ACF
* Contact Form 7
* oAuth Twitter feed for developers
* Regenerate Thumbnails
* Transient Manager
* WP Mail Logging
* WPML
* Yoast | It means you have a PHP syntax error. You need to consult the logs or turn on debug mode. In wp-config.php in your root wordpress directory, find the line as follows:
```
define( 'WP_DEBUG', false );
```
and change it to:
```
define( 'WP_DEBUG', true );
```
Refresh your page that appears blank to find the error. If it still does not show up, it means you may need to change your php.ini settings to display errors. |
284,234 | <p><code>the_author_link()</code> displays author name with hyperlink. I only want authors link to display and not authors name with hyperlink. how i suppose to do that?.
thanks</p>
| [
{
"answer_id": 284236,
"author": "Temani Afif",
"author_id": 128913,
"author_profile": "https://wordpress.stackexchange.com/users/128913",
"pm_score": 3,
"selected": true,
"text": "<p>You may consider using this function :</p>\n\n<pre><code>get_the_author_meta('url')\n</code></pre>\n\n<p>You can see <a href=\"https://developer.wordpress.org/reference/functions/get_the_author_link/\" rel=\"nofollow noreferrer\">here</a> the implementation of the function <code>get_the_author_link()</code> and you will see how they construct the link with name.</p>\n"
},
{
"answer_id": 284237,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to print the URL of author, you can try this.</p>\n\n<pre><code>$authorLink = get_author_link(); \necho $authorLink;\n</code></pre>\n\n<p>Hope this will help.</p>\n\n<p>Thanks.</p>\n\n<p><strong>Updated</strong> on 1st Nov,2017.</p>\n\n<p>In my above solution, get_author_link() is deprecated for latest version of Wordpress.</p>\n\n<p>You can get the any details of users by get_the_author_meta() method. \nIn this function you need to pass the meta_key which you want to get.</p>\n"
}
]
| 2017/10/28 | [
"https://wordpress.stackexchange.com/questions/284234",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125227/"
]
| `the_author_link()` displays author name with hyperlink. I only want authors link to display and not authors name with hyperlink. how i suppose to do that?.
thanks | You may consider using this function :
```
get_the_author_meta('url')
```
You can see [here](https://developer.wordpress.org/reference/functions/get_the_author_link/) the implementation of the function `get_the_author_link()` and you will see how they construct the link with name. |
284,269 | <p>I want to register a new css document that I'm storing inside a PHP file (so that I can create variable css rules). I tried doing this:</p>
<pre><code>function tps_admin_scripts() {
$plugin_url = plugin_dir_url( __FILE__ );
wp_register_script('admin-variable-style', $plugin_url.'css/style-variable.php');
wp_enqueue_script('admin-variable-style');
}
add_action('admin_enqueue_scripts', 'tps_admin_scripts');
</code></pre>
<p>And I've also tried wp_enqueue_style with no luck.</p>
<p>Additionally, I tried </p>
<pre><code>require_once (plugin_dir_path(__FILE__).'css/style-variable.php');
</code></pre>
<p>But that simply rendered the raw style/html onto the page.</p>
<p>Inside the .php file, I have something like this:</p>
<pre><code><?php header("Content-type: text/css"); ?>
<?php
//Calendar Color Pickers
$tpsSettings = get_option( 'tps_rental_settings' );
?>
.colorAvailable {
background-color: <?php echo $tpsSettings['tps_calendar_color_available']; ?>
}
</code></pre>
<p>Is this possible to do with WP? If not, any other solutions to including a php file to run as an additional css file?</p>
| [
{
"answer_id": 284270,
"author": "Eckstein",
"author_id": 23492,
"author_profile": "https://wordpress.stackexchange.com/users/23492",
"pm_score": 0,
"selected": false,
"text": "<p>That answer was to put this in my php file:</p>\n\n<pre><code>require_once('../../../../wp-load.php');\n</code></pre>\n"
},
{
"answer_id": 284271,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>You could also look to create a special CSS file that you setup an htaccess rewrite rule for. For example</p>\n\n<p><code>wp-content/yourtheme/custom.css</code></p>\n\n<p>And then add a rule in your htaccess:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule ^/wp-content/yourtheme/custom.css$ /wp-content/yourtheme/styles.php [L]\n</code></pre>\n\n<p>You can then call wp-load inside this <code>styles.php</code> file, do any sort of logic required, before outputting your custom css rules:</p>\n\n<pre><code><?php header(\"Content-type: text/css; charset: UTF-8\"); ?>\np {\n color: black;\n}\n</code></pre>\n"
}
]
| 2017/10/28 | [
"https://wordpress.stackexchange.com/questions/284269",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23492/"
]
| I want to register a new css document that I'm storing inside a PHP file (so that I can create variable css rules). I tried doing this:
```
function tps_admin_scripts() {
$plugin_url = plugin_dir_url( __FILE__ );
wp_register_script('admin-variable-style', $plugin_url.'css/style-variable.php');
wp_enqueue_script('admin-variable-style');
}
add_action('admin_enqueue_scripts', 'tps_admin_scripts');
```
And I've also tried wp\_enqueue\_style with no luck.
Additionally, I tried
```
require_once (plugin_dir_path(__FILE__).'css/style-variable.php');
```
But that simply rendered the raw style/html onto the page.
Inside the .php file, I have something like this:
```
<?php header("Content-type: text/css"); ?>
<?php
//Calendar Color Pickers
$tpsSettings = get_option( 'tps_rental_settings' );
?>
.colorAvailable {
background-color: <?php echo $tpsSettings['tps_calendar_color_available']; ?>
}
```
Is this possible to do with WP? If not, any other solutions to including a php file to run as an additional css file? | You could also look to create a special CSS file that you setup an htaccess rewrite rule for. For example
`wp-content/yourtheme/custom.css`
And then add a rule in your htaccess:
```
RewriteEngine On
RewriteRule ^/wp-content/yourtheme/custom.css$ /wp-content/yourtheme/styles.php [L]
```
You can then call wp-load inside this `styles.php` file, do any sort of logic required, before outputting your custom css rules:
```
<?php header("Content-type: text/css; charset: UTF-8"); ?>
p {
color: black;
}
``` |
284,283 | <p>Is there any function to change the image Author(Uploaded By) in WordPress library?</p>
<p><a href="https://i.stack.imgur.com/Ol1u8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ol1u8.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 284290,
"author": "shamim khan",
"author_id": 98304,
"author_profile": "https://wordpress.stackexchange.com/users/98304",
"pm_score": 1,
"selected": true,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_post\" rel=\"nofollow noreferrer\">wp_update_post()</a></p>\n\n<pre><code>$my_post = array(\n'ID' => $post_id,\n'post_author' => $user_id,\n);\nwp_update_post( $my_post );\n</code></pre>\n\n<p>Or change image's author via a function using GravityForms uploader</p>\n\n<pre><code>add_action(\"gform_user_registered\", \"image_author\", 10, 4);\nfunction image_author($user_id, $config, $entry, $user_pass) \n{\n$post_id = $entry[\"post_id\"];\n\n$args = array(\n'post_parent' => $post_id,\n'post_type' => 'attachment',\n'post_mime_type' => 'image'\n);\n\n$attachments = get_posts($args);\nif($attachments) :\n foreach ($attachments as $attachment) : setup_postdata($attachment);\n $the_post = array();\n $the_post['ID'] = $attachment->ID;\n $the_post['post_author'] = $user_id;\n\n wp_update_post( $the_post );\n\n endforeach;\nendif; \n\n}\n</code></pre>\n"
},
{
"answer_id": 284291,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>In the screenshot you provided, click on the <code>Edit more detail</code>. this will redirect you to attachment's page.</p>\n\n<p>Then, click on the <code>Screen's options</code> on the top of screen, and check the <code>Author</code> box. A new box will be added to your page.</p>\n\n<p><a href=\"https://i.stack.imgur.com/AqUxJ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AqUxJ.jpg\" alt=\"Screen's option box in edit attachment page\"></a></p>\n\n<p>You can there choose an author for your attachment, and save the page.</p>\n\n<p>If you want to do this programmatically on upload or edit, you can use the <code>add_attachment</code> or <code>edit_attachment</code> filter as shown in <a href=\"https://wordpress.stackexchange.com/a/56233/94498\">this</a> answer.</p>\n\n<p>Otherwise, to change it manually, you can use the <a href=\"https://developer.wordpress.org/reference/functions/wp_update_post/\" rel=\"nofollow noreferrer\"><code>wp_update_post()</code></a> function. A photo is an attachment, therefore a post type, so you can change its author by passing an author to <code>post_author</code> argument of this function.</p>\n"
}
]
| 2017/10/29 | [
"https://wordpress.stackexchange.com/questions/284283",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129715/"
]
| Is there any function to change the image Author(Uploaded By) in WordPress library?
[](https://i.stack.imgur.com/Ol1u8.jpg) | You can use [wp\_update\_post()](https://codex.wordpress.org/Function_Reference/wp_update_post)
```
$my_post = array(
'ID' => $post_id,
'post_author' => $user_id,
);
wp_update_post( $my_post );
```
Or change image's author via a function using GravityForms uploader
```
add_action("gform_user_registered", "image_author", 10, 4);
function image_author($user_id, $config, $entry, $user_pass)
{
$post_id = $entry["post_id"];
$args = array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_mime_type' => 'image'
);
$attachments = get_posts($args);
if($attachments) :
foreach ($attachments as $attachment) : setup_postdata($attachment);
$the_post = array();
$the_post['ID'] = $attachment->ID;
$the_post['post_author'] = $user_id;
wp_update_post( $the_post );
endforeach;
endif;
}
``` |
284,284 | <p>I created a CPT with slug <code>plist</code> via cutom plugin I made.</p>
<p>In my local host the archive work but in live server it return blank page.</p>
<p>Here is the 'include' archive page code</p>
<pre><code>/**
* Add Price List archive template
* @since 1.0.0
*/
add_filter( 'archive_template', 'get_plist_archive_template' ) ;
function get_plist_archive_template( $archive_template ) {
global $post;
if ( is_post_type_archive ( 'plist' ) ) {
$archive_template = dirname( __FILE__ ) . '\partials\archive-plist.php';
}
return $archive_template;
}
</code></pre>
<p>Link: <a href="http://cratetimer.com/plist/" rel="nofollow noreferrer">http://cratetimer.com/plist/</a></p>
<p>Also this may help:</p>
<pre><code>/**
* Register Custom Post Type Price List
* @since 1.0.0
*/
if ( ! function_exists('price_item_post_type') ) {
add_action( 'init', 'price_item_post_type', 0 );
// Register Custom Post Type
function price_item_post_type() {
$labels = array(
'name' => _x( 'Price Lists', 'Post Type General Name', 'plist' ),
'singular_name' => _x( 'Price List', 'Post Type Singular Name', 'plist' ),
'menu_name' => __( 'Price List', 'plist' ),
'name_admin_bar' => __( 'Price List', 'plist' ),
'archives' => __( 'Price List Archives', 'plist' ),
'attributes' => __( 'Price List Attributes', 'plist' ),
'parent_item_colon' => __( 'Parent Price List:', 'plist' ),
'all_items' => __( 'All Price Lists', 'plist' ),
'add_new_item' => __( 'Add New Price List', 'plist' ),
'add_new' => __( 'Add New', 'plist' ),
'new_item' => __( 'New Price List', 'plist' ),
'edit_item' => __( 'Edit Price List', 'plist' ),
'update_item' => __( 'Update Price List', 'plist' ),
'view_item' => __( 'View Price List', 'plist' ),
'view_items' => __( 'View Price Lists', 'plist' ),
'search_items' => __( 'Search Price List', 'plist' ),
'not_found' => __( 'Not found', 'plist' ),
'not_found_in_trash' => __( 'Not found in Trash', 'plist' ),
'featured_image' => __( 'Featured Image', 'plist' ),
'set_featured_image' => __( 'Set featured image', 'plist' ),
'remove_featured_image' => __( 'Remove featured image', 'plist' ),
'use_featured_image' => __( 'Use as featured image', 'plist' ),
'insert_into_item' => __( 'Insert into Price List', 'plist' ),
'uploaded_to_this_item' => __( 'Uploaded to this Price List', 'plist' ),
'items_list' => __( 'Price Lists', 'plist' ),
'items_list_navigation' => __( 'Price Lists navigation', 'plist' ),
'filter_items_list' => __( 'Filter Price Lists', 'plist' ),
);
$args = array(
'label' => __( 'Price List', 'plist' ),
'description' => __( 'Price list item for market', 'plist' ),
'labels' => $labels,
'supports' => array( ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 20,
'menu_icon' => 'dashicons-tag',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'plist', $args );
}
}
</code></pre>
<p>I tried flush_rewrite_rules() and it didn't work.</p>
| [
{
"answer_id": 284290,
"author": "shamim khan",
"author_id": 98304,
"author_profile": "https://wordpress.stackexchange.com/users/98304",
"pm_score": 1,
"selected": true,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_post\" rel=\"nofollow noreferrer\">wp_update_post()</a></p>\n\n<pre><code>$my_post = array(\n'ID' => $post_id,\n'post_author' => $user_id,\n);\nwp_update_post( $my_post );\n</code></pre>\n\n<p>Or change image's author via a function using GravityForms uploader</p>\n\n<pre><code>add_action(\"gform_user_registered\", \"image_author\", 10, 4);\nfunction image_author($user_id, $config, $entry, $user_pass) \n{\n$post_id = $entry[\"post_id\"];\n\n$args = array(\n'post_parent' => $post_id,\n'post_type' => 'attachment',\n'post_mime_type' => 'image'\n);\n\n$attachments = get_posts($args);\nif($attachments) :\n foreach ($attachments as $attachment) : setup_postdata($attachment);\n $the_post = array();\n $the_post['ID'] = $attachment->ID;\n $the_post['post_author'] = $user_id;\n\n wp_update_post( $the_post );\n\n endforeach;\nendif; \n\n}\n</code></pre>\n"
},
{
"answer_id": 284291,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>In the screenshot you provided, click on the <code>Edit more detail</code>. this will redirect you to attachment's page.</p>\n\n<p>Then, click on the <code>Screen's options</code> on the top of screen, and check the <code>Author</code> box. A new box will be added to your page.</p>\n\n<p><a href=\"https://i.stack.imgur.com/AqUxJ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AqUxJ.jpg\" alt=\"Screen's option box in edit attachment page\"></a></p>\n\n<p>You can there choose an author for your attachment, and save the page.</p>\n\n<p>If you want to do this programmatically on upload or edit, you can use the <code>add_attachment</code> or <code>edit_attachment</code> filter as shown in <a href=\"https://wordpress.stackexchange.com/a/56233/94498\">this</a> answer.</p>\n\n<p>Otherwise, to change it manually, you can use the <a href=\"https://developer.wordpress.org/reference/functions/wp_update_post/\" rel=\"nofollow noreferrer\"><code>wp_update_post()</code></a> function. A photo is an attachment, therefore a post type, so you can change its author by passing an author to <code>post_author</code> argument of this function.</p>\n"
}
]
| 2017/10/29 | [
"https://wordpress.stackexchange.com/questions/284284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68492/"
]
| I created a CPT with slug `plist` via cutom plugin I made.
In my local host the archive work but in live server it return blank page.
Here is the 'include' archive page code
```
/**
* Add Price List archive template
* @since 1.0.0
*/
add_filter( 'archive_template', 'get_plist_archive_template' ) ;
function get_plist_archive_template( $archive_template ) {
global $post;
if ( is_post_type_archive ( 'plist' ) ) {
$archive_template = dirname( __FILE__ ) . '\partials\archive-plist.php';
}
return $archive_template;
}
```
Link: <http://cratetimer.com/plist/>
Also this may help:
```
/**
* Register Custom Post Type Price List
* @since 1.0.0
*/
if ( ! function_exists('price_item_post_type') ) {
add_action( 'init', 'price_item_post_type', 0 );
// Register Custom Post Type
function price_item_post_type() {
$labels = array(
'name' => _x( 'Price Lists', 'Post Type General Name', 'plist' ),
'singular_name' => _x( 'Price List', 'Post Type Singular Name', 'plist' ),
'menu_name' => __( 'Price List', 'plist' ),
'name_admin_bar' => __( 'Price List', 'plist' ),
'archives' => __( 'Price List Archives', 'plist' ),
'attributes' => __( 'Price List Attributes', 'plist' ),
'parent_item_colon' => __( 'Parent Price List:', 'plist' ),
'all_items' => __( 'All Price Lists', 'plist' ),
'add_new_item' => __( 'Add New Price List', 'plist' ),
'add_new' => __( 'Add New', 'plist' ),
'new_item' => __( 'New Price List', 'plist' ),
'edit_item' => __( 'Edit Price List', 'plist' ),
'update_item' => __( 'Update Price List', 'plist' ),
'view_item' => __( 'View Price List', 'plist' ),
'view_items' => __( 'View Price Lists', 'plist' ),
'search_items' => __( 'Search Price List', 'plist' ),
'not_found' => __( 'Not found', 'plist' ),
'not_found_in_trash' => __( 'Not found in Trash', 'plist' ),
'featured_image' => __( 'Featured Image', 'plist' ),
'set_featured_image' => __( 'Set featured image', 'plist' ),
'remove_featured_image' => __( 'Remove featured image', 'plist' ),
'use_featured_image' => __( 'Use as featured image', 'plist' ),
'insert_into_item' => __( 'Insert into Price List', 'plist' ),
'uploaded_to_this_item' => __( 'Uploaded to this Price List', 'plist' ),
'items_list' => __( 'Price Lists', 'plist' ),
'items_list_navigation' => __( 'Price Lists navigation', 'plist' ),
'filter_items_list' => __( 'Filter Price Lists', 'plist' ),
);
$args = array(
'label' => __( 'Price List', 'plist' ),
'description' => __( 'Price list item for market', 'plist' ),
'labels' => $labels,
'supports' => array( ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 20,
'menu_icon' => 'dashicons-tag',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'plist', $args );
}
}
```
I tried flush\_rewrite\_rules() and it didn't work. | You can use [wp\_update\_post()](https://codex.wordpress.org/Function_Reference/wp_update_post)
```
$my_post = array(
'ID' => $post_id,
'post_author' => $user_id,
);
wp_update_post( $my_post );
```
Or change image's author via a function using GravityForms uploader
```
add_action("gform_user_registered", "image_author", 10, 4);
function image_author($user_id, $config, $entry, $user_pass)
{
$post_id = $entry["post_id"];
$args = array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_mime_type' => 'image'
);
$attachments = get_posts($args);
if($attachments) :
foreach ($attachments as $attachment) : setup_postdata($attachment);
$the_post = array();
$the_post['ID'] = $attachment->ID;
$the_post['post_author'] = $user_id;
wp_update_post( $the_post );
endforeach;
endif;
}
``` |
284,325 | <p>I have the following domains/subdomains. They are all related to each other, yet they must be on different domains/subdomains</p>
<pre><code>example.com
www.example.com (redirects to example.com)
sub1.example.com
sub2.example.com
example.net
www.example.net (redirects to example.net)
sub1.example.net
sub2.example.net
</code></pre>
<p>I would like to have a single WordPress installation for all the above (i.e., end up with a single DB). I do understand that I can setup a multisite installation if I have a single domain with subdomains. But for the above, this would mean I end up with TWO multisite installations (one for <code>example.com</code>, and another for <code>example.net</code>). </p>
<p>Is it possible to setup a single multisite installation with a single database allowing more than one main domain as shown above? If so, how?</p>
<p>Thanks.</p>
| [
{
"answer_id": 284324,
"author": "Jlil",
"author_id": 83204,
"author_profile": "https://wordpress.stackexchange.com/users/83204",
"pm_score": 2,
"selected": true,
"text": "<p>You can do that using <a href=\"https://wordpress.org/plugins/custom-permalinks/\" rel=\"nofollow noreferrer\">Custom Permalinks</a> Plugin, you need to add a full slug manually <code>[shows/2017/any]</code>.</p>\n\n<p>It also allow you customize your permalink: <code>[anyname/another/2017/example/slug]</code>.</p>\n\n<p>You should still using this plugin, if you deactivate it, all permalinks will return to <em>default</em> <code>[shows/2017/%postname%]</code></p>\n"
},
{
"answer_id": 284339,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 0,
"selected": false,
"text": "<p>It is easy to manipulate post's slug, before writing it to database. If concerts and festivals occur once a year, you can still use %postname% tag for a permalink. Your URL will look like, for example, <code>http://yoursite.com/2016-concert-name/</code>. Add this code to functions.php:</p>\n\n<pre><code>function wpse_filter_handler($data, $postarr) {\n if(!is_numeric(substr($data['post_name'], 0, 4))) {\n $catids = $postarr['post_category'];\n if(count($catids) > 1) {\n $catobj = get_category($catids[1]);\n $data['post_name'] = $catobj->slug . '-' . $data['post_name'];\n }\n }\n return $data;\n}\nadd_filter( 'wp_insert_post_data', 'wpse_filter_handler', 10, 2 );\n</code></pre>\n\n<p>This example uses categories, but for custom taxonomies the logic is exactly the same. Of course, additional checks should be included, in code above, depending on your actual settings.</p>\n"
}
]
| 2017/10/29 | [
"https://wordpress.stackexchange.com/questions/284325",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
]
| I have the following domains/subdomains. They are all related to each other, yet they must be on different domains/subdomains
```
example.com
www.example.com (redirects to example.com)
sub1.example.com
sub2.example.com
example.net
www.example.net (redirects to example.net)
sub1.example.net
sub2.example.net
```
I would like to have a single WordPress installation for all the above (i.e., end up with a single DB). I do understand that I can setup a multisite installation if I have a single domain with subdomains. But for the above, this would mean I end up with TWO multisite installations (one for `example.com`, and another for `example.net`).
Is it possible to setup a single multisite installation with a single database allowing more than one main domain as shown above? If so, how?
Thanks. | You can do that using [Custom Permalinks](https://wordpress.org/plugins/custom-permalinks/) Plugin, you need to add a full slug manually `[shows/2017/any]`.
It also allow you customize your permalink: `[anyname/another/2017/example/slug]`.
You should still using this plugin, if you deactivate it, all permalinks will return to *default* `[shows/2017/%postname%]` |
284,352 | <p>My current theme comments are displayed using following code.</p>
<pre><code> <ol class="comment-list">
<?php
wp_list_comments( array(
'style' => 'ol',
'short_ping' => true,
) );
?>
</ol>
</code></pre>
<p>I need to remove "a href" part.I mean their should not be linked to the comment author website.</p>
<p>I check <a href="https://codex.wordpress.org/Function_Reference/wp_list_comments" rel="nofollow noreferrer"><code>wp_list_comments()</code></a> from codex, but I could not find how to remove <code><a href</code> part.</p>
| [
{
"answer_id": 284353,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>You could create your own walker and customize its structure. Note that using a filter will affect <em>\"all\"</em> instances of <code>wp_list_comments()</code>, so you are advised to customize your comments by using a walker. Here's a basic example:</p>\n\n<pre><code>function my_comment( $comment, $args, $depth ) {\n $GLOBALS['comment'] = $comment; ?>\n <li <?php comment_class(); ?> id=\"li-comment-<?php comment_ID(); ?>\">\n <div id=\"comment-<?php comment_ID(); ?>\" class=\"comment-wrap\">\n <div class=\"comment-head comment-author vcard\"><?php\n echo get_avatar( $comment, 60 );\n if ( comments_open() ){\n comment_reply_link( \n array_merge( \n $args, \n array( \n 'depth' => $depth,\n 'max_depth' => $args['max_depth'], \n 'reply_text' => __( 'Reply' ) \n ) \n ) \n );\n }?>\n <div class=\"comment-meta commentmetadata\">\n <div class=\"comment-date\"><?php\n /* translators: 1: date, 2: time */\n printf( __( '%1$s at %2$s' ),\n get_comment_date(),\n get_comment_time()\n ); ?>\n </div><?php\n edit_comment_link( __( 'Edit' ), '', '' );?>\n </div>\n </div>\n <div class=\"comment-content comment-text\"><?php\n if ( $comment->comment_approved == '0' ) { ?>\n <em><?php _e( 'Your comment is awaiting moderation.'); ?></em><br /><?php\n }\n comment_text(); ?>\n </div>\n </div>\n <?php\n}\n</code></pre>\n\n<p>Now you can define the callback in <code>wp_list_comments()</code>:</p>\n\n<pre><code>wp_list_comments( \n array( \n 'callback' => 'my_comment' ,\n 'style' => 'ol'\n ) \n);\n</code></pre>\n\n<p>This will render the comments without a link to them. You can fully customize the output comments. Further information and complex examples are provided in the <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_comments\" rel=\"nofollow noreferrer\">codex</a> page.</p>\n"
},
{
"answer_id": 284354,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Deep down the function uses <a href=\"https://developer.wordpress.org/reference/functions/get_comment_author_link/\" rel=\"nofollow noreferrer\"><code>get_comment_author_link()</code></a> to output the author name. That function is filterable. Inside the function it checks if the author has a URL and wraps the name in a link to it if it exists. We can use the <code>get_comment_author_link</code> filter to just output the name, and ignore the URL. This is pretty simple, since the callback for this filter gets the author name as one of its arguments, so we just need to pass it through untouched:</p>\n\n<pre><code>function wpse_284352_author_link( $author_link, $author ) {\n return $author;\n}\nadd_filter( 'get_comment_author_link', 'wpse_284352_author_link', 10, 2 );\n</code></pre>\n\n<p><strong>EDIT:</strong> It's actually even simpler, the URL has its own filter, which means that can be filtered with one of WordPress' built in functions in one line:</p>\n\n<pre><code>add_filter( 'get_comment_author_url', '__return_empty_string' );\n</code></pre>\n"
}
]
| 2017/10/30 | [
"https://wordpress.stackexchange.com/questions/284352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123092/"
]
| My current theme comments are displayed using following code.
```
<ol class="comment-list">
<?php
wp_list_comments( array(
'style' => 'ol',
'short_ping' => true,
) );
?>
</ol>
```
I need to remove "a href" part.I mean their should not be linked to the comment author website.
I check [`wp_list_comments()`](https://codex.wordpress.org/Function_Reference/wp_list_comments) from codex, but I could not find how to remove `<a href` part. | Deep down the function uses [`get_comment_author_link()`](https://developer.wordpress.org/reference/functions/get_comment_author_link/) to output the author name. That function is filterable. Inside the function it checks if the author has a URL and wraps the name in a link to it if it exists. We can use the `get_comment_author_link` filter to just output the name, and ignore the URL. This is pretty simple, since the callback for this filter gets the author name as one of its arguments, so we just need to pass it through untouched:
```
function wpse_284352_author_link( $author_link, $author ) {
return $author;
}
add_filter( 'get_comment_author_link', 'wpse_284352_author_link', 10, 2 );
```
**EDIT:** It's actually even simpler, the URL has its own filter, which means that can be filtered with one of WordPress' built in functions in one line:
```
add_filter( 'get_comment_author_url', '__return_empty_string' );
``` |
284,360 | <p>Please assist. I have followed a tutorial to create a custom template with a sidebar. The sidebar has been implemented successfully and the page template is called "Custom page Template Wizard". The issue I am having is getting the sidebar to appear left and content on the right. The theme I am using is Ultra7</p>
<p>The issue I am having lies within this test page:
<a href="https://devtest2017.aquatiere.co.uk/product-filter-wizard/" rel="nofollow noreferrer">https://devtest2017.aquatiere.co.uk/product-filter-wizard/</a></p>
<p>The desired layout is not showing up. Does this require css? </p>
<p>Also, main page content is not displaying. How do I resolve this?</p>
<p>This is custom_page.php coding: </p>
<pre><code><?php
/*
* Template Name: Custom Page Template Wizard
*/
?>
<?php get_header(); ?>
<?php if ( is_active_sidebar( 'wizard-sidebar' ) ) : ?>
<?php dynamic_sidebar( 'wizard-sidebar' ); ?>
<?php endif; ?>
<?php get_footer(); ?>
</code></pre>
<p>This is my custom sidebar template coding (sidebar-wizard.php):</p>
<pre><code><div id="sidebar">
<ul>
<?php
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('wizard-sidebar') ) :
endif; ?>
</ul>
</div>
</code></pre>
<p>AND I have added this code to my themes functions.php file: </p>
<pre><code>if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'name' => 'Wizard Layout Page',
'id' => 'wizard-sidebar',
'description' => 'Appears as the sidebar on the custom wizard page',
'before_widget' => '<div style="height: 280px"></div><li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>',
));
}
</code></pre>
<p>This is what the page looks like at present:</p>
<p><a href="https://i.stack.imgur.com/CXO9H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXO9H.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/FADXY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FADXY.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/5jsFG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5jsFG.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 284353,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>You could create your own walker and customize its structure. Note that using a filter will affect <em>\"all\"</em> instances of <code>wp_list_comments()</code>, so you are advised to customize your comments by using a walker. Here's a basic example:</p>\n\n<pre><code>function my_comment( $comment, $args, $depth ) {\n $GLOBALS['comment'] = $comment; ?>\n <li <?php comment_class(); ?> id=\"li-comment-<?php comment_ID(); ?>\">\n <div id=\"comment-<?php comment_ID(); ?>\" class=\"comment-wrap\">\n <div class=\"comment-head comment-author vcard\"><?php\n echo get_avatar( $comment, 60 );\n if ( comments_open() ){\n comment_reply_link( \n array_merge( \n $args, \n array( \n 'depth' => $depth,\n 'max_depth' => $args['max_depth'], \n 'reply_text' => __( 'Reply' ) \n ) \n ) \n );\n }?>\n <div class=\"comment-meta commentmetadata\">\n <div class=\"comment-date\"><?php\n /* translators: 1: date, 2: time */\n printf( __( '%1$s at %2$s' ),\n get_comment_date(),\n get_comment_time()\n ); ?>\n </div><?php\n edit_comment_link( __( 'Edit' ), '', '' );?>\n </div>\n </div>\n <div class=\"comment-content comment-text\"><?php\n if ( $comment->comment_approved == '0' ) { ?>\n <em><?php _e( 'Your comment is awaiting moderation.'); ?></em><br /><?php\n }\n comment_text(); ?>\n </div>\n </div>\n <?php\n}\n</code></pre>\n\n<p>Now you can define the callback in <code>wp_list_comments()</code>:</p>\n\n<pre><code>wp_list_comments( \n array( \n 'callback' => 'my_comment' ,\n 'style' => 'ol'\n ) \n);\n</code></pre>\n\n<p>This will render the comments without a link to them. You can fully customize the output comments. Further information and complex examples are provided in the <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_comments\" rel=\"nofollow noreferrer\">codex</a> page.</p>\n"
},
{
"answer_id": 284354,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Deep down the function uses <a href=\"https://developer.wordpress.org/reference/functions/get_comment_author_link/\" rel=\"nofollow noreferrer\"><code>get_comment_author_link()</code></a> to output the author name. That function is filterable. Inside the function it checks if the author has a URL and wraps the name in a link to it if it exists. We can use the <code>get_comment_author_link</code> filter to just output the name, and ignore the URL. This is pretty simple, since the callback for this filter gets the author name as one of its arguments, so we just need to pass it through untouched:</p>\n\n<pre><code>function wpse_284352_author_link( $author_link, $author ) {\n return $author;\n}\nadd_filter( 'get_comment_author_link', 'wpse_284352_author_link', 10, 2 );\n</code></pre>\n\n<p><strong>EDIT:</strong> It's actually even simpler, the URL has its own filter, which means that can be filtered with one of WordPress' built in functions in one line:</p>\n\n<pre><code>add_filter( 'get_comment_author_url', '__return_empty_string' );\n</code></pre>\n"
}
]
| 2017/10/30 | [
"https://wordpress.stackexchange.com/questions/284360",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129843/"
]
| Please assist. I have followed a tutorial to create a custom template with a sidebar. The sidebar has been implemented successfully and the page template is called "Custom page Template Wizard". The issue I am having is getting the sidebar to appear left and content on the right. The theme I am using is Ultra7
The issue I am having lies within this test page:
<https://devtest2017.aquatiere.co.uk/product-filter-wizard/>
The desired layout is not showing up. Does this require css?
Also, main page content is not displaying. How do I resolve this?
This is custom\_page.php coding:
```
<?php
/*
* Template Name: Custom Page Template Wizard
*/
?>
<?php get_header(); ?>
<?php if ( is_active_sidebar( 'wizard-sidebar' ) ) : ?>
<?php dynamic_sidebar( 'wizard-sidebar' ); ?>
<?php endif; ?>
<?php get_footer(); ?>
```
This is my custom sidebar template coding (sidebar-wizard.php):
```
<div id="sidebar">
<ul>
<?php
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('wizard-sidebar') ) :
endif; ?>
</ul>
</div>
```
AND I have added this code to my themes functions.php file:
```
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'name' => 'Wizard Layout Page',
'id' => 'wizard-sidebar',
'description' => 'Appears as the sidebar on the custom wizard page',
'before_widget' => '<div style="height: 280px"></div><li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>',
));
}
```
This is what the page looks like at present:
[](https://i.stack.imgur.com/CXO9H.png)
[](https://i.stack.imgur.com/FADXY.png)
[](https://i.stack.imgur.com/5jsFG.png) | Deep down the function uses [`get_comment_author_link()`](https://developer.wordpress.org/reference/functions/get_comment_author_link/) to output the author name. That function is filterable. Inside the function it checks if the author has a URL and wraps the name in a link to it if it exists. We can use the `get_comment_author_link` filter to just output the name, and ignore the URL. This is pretty simple, since the callback for this filter gets the author name as one of its arguments, so we just need to pass it through untouched:
```
function wpse_284352_author_link( $author_link, $author ) {
return $author;
}
add_filter( 'get_comment_author_link', 'wpse_284352_author_link', 10, 2 );
```
**EDIT:** It's actually even simpler, the URL has its own filter, which means that can be filtered with one of WordPress' built in functions in one line:
```
add_filter( 'get_comment_author_url', '__return_empty_string' );
``` |
284,364 | <p>I have been working with WordPress since last 5 years almost. But so far I didn't get a standard solution to secure a WordPress site.</p>
<p>I have a clients hosting account which has 11 WordPress websites that keeps getting hacked every year almost. Even Finally I had to leave the Hostgator or they suspended that account because of this. Now I bought a new hosting and I don't want it to be happen again and again.</p>
<p>So far what I did to secure my site is I have used "Wordfence" Plugins and set it up correctly. Tried to hide my wordpress installation using "Hide My Wp" Plugin. Has set the login attempt to 5 in Wordfence settings that could help it to protect from Ddos attack. Always using updated version of plugins and themes and WordPress core. By following these steps still I have been hacked 6 times in Hosgator hosting.</p>
<p>Now my question is that as I have moved to new host and off course I am using all fresh new installation in my new hosting for these existing sites; How I can I make all these site secure or what is the best standard methods to secure a WordPress site ?</p>
<p>Thanks to you all in Advance. </p>
| [
{
"answer_id": 284353,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>You could create your own walker and customize its structure. Note that using a filter will affect <em>\"all\"</em> instances of <code>wp_list_comments()</code>, so you are advised to customize your comments by using a walker. Here's a basic example:</p>\n\n<pre><code>function my_comment( $comment, $args, $depth ) {\n $GLOBALS['comment'] = $comment; ?>\n <li <?php comment_class(); ?> id=\"li-comment-<?php comment_ID(); ?>\">\n <div id=\"comment-<?php comment_ID(); ?>\" class=\"comment-wrap\">\n <div class=\"comment-head comment-author vcard\"><?php\n echo get_avatar( $comment, 60 );\n if ( comments_open() ){\n comment_reply_link( \n array_merge( \n $args, \n array( \n 'depth' => $depth,\n 'max_depth' => $args['max_depth'], \n 'reply_text' => __( 'Reply' ) \n ) \n ) \n );\n }?>\n <div class=\"comment-meta commentmetadata\">\n <div class=\"comment-date\"><?php\n /* translators: 1: date, 2: time */\n printf( __( '%1$s at %2$s' ),\n get_comment_date(),\n get_comment_time()\n ); ?>\n </div><?php\n edit_comment_link( __( 'Edit' ), '', '' );?>\n </div>\n </div>\n <div class=\"comment-content comment-text\"><?php\n if ( $comment->comment_approved == '0' ) { ?>\n <em><?php _e( 'Your comment is awaiting moderation.'); ?></em><br /><?php\n }\n comment_text(); ?>\n </div>\n </div>\n <?php\n}\n</code></pre>\n\n<p>Now you can define the callback in <code>wp_list_comments()</code>:</p>\n\n<pre><code>wp_list_comments( \n array( \n 'callback' => 'my_comment' ,\n 'style' => 'ol'\n ) \n);\n</code></pre>\n\n<p>This will render the comments without a link to them. You can fully customize the output comments. Further information and complex examples are provided in the <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_comments\" rel=\"nofollow noreferrer\">codex</a> page.</p>\n"
},
{
"answer_id": 284354,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Deep down the function uses <a href=\"https://developer.wordpress.org/reference/functions/get_comment_author_link/\" rel=\"nofollow noreferrer\"><code>get_comment_author_link()</code></a> to output the author name. That function is filterable. Inside the function it checks if the author has a URL and wraps the name in a link to it if it exists. We can use the <code>get_comment_author_link</code> filter to just output the name, and ignore the URL. This is pretty simple, since the callback for this filter gets the author name as one of its arguments, so we just need to pass it through untouched:</p>\n\n<pre><code>function wpse_284352_author_link( $author_link, $author ) {\n return $author;\n}\nadd_filter( 'get_comment_author_link', 'wpse_284352_author_link', 10, 2 );\n</code></pre>\n\n<p><strong>EDIT:</strong> It's actually even simpler, the URL has its own filter, which means that can be filtered with one of WordPress' built in functions in one line:</p>\n\n<pre><code>add_filter( 'get_comment_author_url', '__return_empty_string' );\n</code></pre>\n"
}
]
| 2017/10/30 | [
"https://wordpress.stackexchange.com/questions/284364",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109213/"
]
| I have been working with WordPress since last 5 years almost. But so far I didn't get a standard solution to secure a WordPress site.
I have a clients hosting account which has 11 WordPress websites that keeps getting hacked every year almost. Even Finally I had to leave the Hostgator or they suspended that account because of this. Now I bought a new hosting and I don't want it to be happen again and again.
So far what I did to secure my site is I have used "Wordfence" Plugins and set it up correctly. Tried to hide my wordpress installation using "Hide My Wp" Plugin. Has set the login attempt to 5 in Wordfence settings that could help it to protect from Ddos attack. Always using updated version of plugins and themes and WordPress core. By following these steps still I have been hacked 6 times in Hosgator hosting.
Now my question is that as I have moved to new host and off course I am using all fresh new installation in my new hosting for these existing sites; How I can I make all these site secure or what is the best standard methods to secure a WordPress site ?
Thanks to you all in Advance. | Deep down the function uses [`get_comment_author_link()`](https://developer.wordpress.org/reference/functions/get_comment_author_link/) to output the author name. That function is filterable. Inside the function it checks if the author has a URL and wraps the name in a link to it if it exists. We can use the `get_comment_author_link` filter to just output the name, and ignore the URL. This is pretty simple, since the callback for this filter gets the author name as one of its arguments, so we just need to pass it through untouched:
```
function wpse_284352_author_link( $author_link, $author ) {
return $author;
}
add_filter( 'get_comment_author_link', 'wpse_284352_author_link', 10, 2 );
```
**EDIT:** It's actually even simpler, the URL has its own filter, which means that can be filtered with one of WordPress' built in functions in one line:
```
add_filter( 'get_comment_author_url', '__return_empty_string' );
``` |
284,381 | <p>Is there any way to force to show the price of the Product Variation I set as defaul in product page settings, instead of lower and higher prices?</p>
<p>I've got this code to show just one price, but the shown price is not the price of the default variation:</p>
<pre><code>/*******************************
SHOW ONLY ONE PRICE FOR VARIATIONS
*********************************/
add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);
function custom_variation_price( $price, $product ) {
$price = '';
$price .= woocommerce_price($product->get_price());
return $price;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/l9ROZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l9ROZ.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 284739,
"author": "Alexander Z.",
"author_id": 123792,
"author_profile": "https://wordpress.stackexchange.com/users/123792",
"pm_score": 2,
"selected": false,
"text": "<p>This is solution for the minimal price as default for the variable products:</p>\n\n<pre><code>add_filter('woocommerce_variable_price_html','shop_variable_product_price', 10, 2 );\n\nfunction shop_variable_product_price( $price, $product ){\n $variation_min_reg_price = $product->get_variation_regular_price('min', true);\n\n if(!empty($variation_min_reg_price)) {\n $price = woocommerce_price( $variation_min_reg_price );\n }\n else {\n $price = woocommerce_price( $product->regular_price );\n }\n\n return $price;\n}\n</code></pre>\n"
},
{
"answer_id": 284850,
"author": "Vivek Athalye",
"author_id": 119672,
"author_profile": "https://wordpress.stackexchange.com/users/119672",
"pm_score": 4,
"selected": true,
"text": "<p>Try this code:</p>\n\n<pre><code>add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);\nfunction custom_variation_price( $price, $product ) {\n $available_variations = $product->get_available_variations();\n $selectedPrice = '';\n $dump = '';\n\n foreach ( $available_variations as $variation )\n {\n // $dump = $dump . '<pre>' . var_export($variation['attributes'], true) . '</pre>';\n\n $isDefVariation=false;\n foreach($product->get_default_attributes() as $key=>$val){\n // $dump = $dump . '<pre>' . var_export($key, true) . '</pre>';\n // $dump = $dump . '<pre>' . var_export($val, true) . '</pre>';\n if($variation['attributes']['attribute_'.$key]==$val){\n $isDefVariation=true;\n } \n }\n if($isDefVariation){\n $price = $variation['display_price']; \n }\n }\n $selectedPrice = wc_price($price);\n\n// $dump = $dump . '<pre>' . var_export($available_variations, true) . '</pre>';\n\n return $selectedPrice . $dump;\n}\n</code></pre>\n"
},
{
"answer_id": 334952,
"author": "SHEESHRAM",
"author_id": 141392,
"author_profile": "https://wordpress.stackexchange.com/users/141392",
"pm_score": 0,
"selected": false,
"text": "<p>Show single variable price</p>\n\n<pre><code>add_filter( 'woocommerce_show_variation_price', '__return_true' );\n</code></pre>\n"
},
{
"answer_id": 344088,
"author": "Abhinav bhardwaj",
"author_id": 172790,
"author_profile": "https://wordpress.stackexchange.com/users/172790",
"pm_score": 0,
"selected": false,
"text": "<p>upgrading @vivek's code as its code is only working for a single variation </p>\n\n<pre><code> add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);\nfunction custom_variation_price($price, $product) {\n $available_variations = $product->get_available_variations();\n $selectedPrice = '';\n $dump = '';\n $defaultArray = array();\n foreach ($available_variations as $variation) {\n // $dump = $dump . '<pre>' . var_export($variation['attributes'], true) . '</pre>';\n $isDefVariation = false;\n foreach ($product->get_default_attributes() as $key => $val) {\n // $dump = $dump . '<pre>' . var_export($key, true) . '</pre>';\n // $dump = $dump . '<pre>' . var_export($val, true) . '</pre>';\n $defaultArray['attribute_' . $key] = $val;\n }\n **$result = array_diff($defaultArray, $variation['attributes']);**\n **if (empty($result)) {\n $isDefVariation = true;\n $price = $variation['display_price'];\n }**\n }\n\n $selectedPrice = wc_price($price);\n// $dump = $dump . '<pre>' . var_export($available_variations, true) . '</pre>';\n return $selectedPrice . $dump;\n}\n</code></pre>\n\n<p>This will work for multiple variation key</p>\n"
},
{
"answer_id": 386398,
"author": "Stijn Sillen",
"author_id": 204664,
"author_profile": "https://wordpress.stackexchange.com/users/204664",
"pm_score": 0,
"selected": false,
"text": "<p>Upgrading @ Abhinav's code to show minimum price in case there is no default set:</p>\n<pre><code>/**\n * Show default variation price\n * If no default variation, shows min price\n */\n\nadd_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);\nfunction custom_variation_price($price, $product) {\n $available_variations = $product->get_available_variations();\n $selectedPrice = '';\n $dump = '';\n $defaultArray = array();\n foreach ($product->get_default_attributes() as $key => $val) {\n // $dump = $dump . '<pre>' . var_export($key, true) . '</pre>';\n // $dump = $dump . '<pre>' . var_export($val, true) . '</pre>';\n $defaultArray['attribute_' . $key] = $val;\n }\n // $dump = $dump . '<pre>' . var_export($defaultArray, true) . '</pre>';\n if (empty($defaultArray)) {\n $price = $product->get_variation_price( 'min', true ); // no default variation, show min price\n } else {\n foreach ($available_variations as $variation) {\n // $dump = $dump . '<pre>' . var_export($variation['attributes'], true) . '</pre>';\n $isDefVariation = false;\n \n $result = array_diff($defaultArray, $variation['attributes']);\n if (empty($result)) {\n $isDefVariation = true;\n $price = $variation['display_price'];\n break;\n }\n }\n }\n\n $selectedPrice = wc_price($price);\n // $dump = $dump . '<pre>' . var_export($available_variations, true) . '</pre>';\n return $selectedPrice . $dump;\n}\n</code></pre>\n"
}
]
| 2017/10/30 | [
"https://wordpress.stackexchange.com/questions/284381",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107273/"
]
| Is there any way to force to show the price of the Product Variation I set as defaul in product page settings, instead of lower and higher prices?
I've got this code to show just one price, but the shown price is not the price of the default variation:
```
/*******************************
SHOW ONLY ONE PRICE FOR VARIATIONS
*********************************/
add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);
function custom_variation_price( $price, $product ) {
$price = '';
$price .= woocommerce_price($product->get_price());
return $price;
}
```
[](https://i.stack.imgur.com/l9ROZ.jpg) | Try this code:
```
add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);
function custom_variation_price( $price, $product ) {
$available_variations = $product->get_available_variations();
$selectedPrice = '';
$dump = '';
foreach ( $available_variations as $variation )
{
// $dump = $dump . '<pre>' . var_export($variation['attributes'], true) . '</pre>';
$isDefVariation=false;
foreach($product->get_default_attributes() as $key=>$val){
// $dump = $dump . '<pre>' . var_export($key, true) . '</pre>';
// $dump = $dump . '<pre>' . var_export($val, true) . '</pre>';
if($variation['attributes']['attribute_'.$key]==$val){
$isDefVariation=true;
}
}
if($isDefVariation){
$price = $variation['display_price'];
}
}
$selectedPrice = wc_price($price);
// $dump = $dump . '<pre>' . var_export($available_variations, true) . '</pre>';
return $selectedPrice . $dump;
}
``` |
284,428 | <p>I'm not sure if this is specific to my site or not, but if anyone knows how to override this behavior, that would be most appreciated! I have WordPress installed in the root directory of my server. There is also an unrelated sub-directory we'll call 'restricted-dir'. I have added an .htaccess file inside that directory with the following code:</p>
<pre><code>Deny from all
</code></pre>
<p>Without that command, if a user visits www.my-domain.com/restricted-dir/ it would list all contents. I would like the user to receive the server's typical 403 Forbidden message, but instead WordPress kicks in and directs the user to my 404 page on my website. </p>
<p>Is there anything I can do to make the 403 page show up instead of the 404 page along with my entire WordPress install?</p>
| [
{
"answer_id": 284739,
"author": "Alexander Z.",
"author_id": 123792,
"author_profile": "https://wordpress.stackexchange.com/users/123792",
"pm_score": 2,
"selected": false,
"text": "<p>This is solution for the minimal price as default for the variable products:</p>\n\n<pre><code>add_filter('woocommerce_variable_price_html','shop_variable_product_price', 10, 2 );\n\nfunction shop_variable_product_price( $price, $product ){\n $variation_min_reg_price = $product->get_variation_regular_price('min', true);\n\n if(!empty($variation_min_reg_price)) {\n $price = woocommerce_price( $variation_min_reg_price );\n }\n else {\n $price = woocommerce_price( $product->regular_price );\n }\n\n return $price;\n}\n</code></pre>\n"
},
{
"answer_id": 284850,
"author": "Vivek Athalye",
"author_id": 119672,
"author_profile": "https://wordpress.stackexchange.com/users/119672",
"pm_score": 4,
"selected": true,
"text": "<p>Try this code:</p>\n\n<pre><code>add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);\nfunction custom_variation_price( $price, $product ) {\n $available_variations = $product->get_available_variations();\n $selectedPrice = '';\n $dump = '';\n\n foreach ( $available_variations as $variation )\n {\n // $dump = $dump . '<pre>' . var_export($variation['attributes'], true) . '</pre>';\n\n $isDefVariation=false;\n foreach($product->get_default_attributes() as $key=>$val){\n // $dump = $dump . '<pre>' . var_export($key, true) . '</pre>';\n // $dump = $dump . '<pre>' . var_export($val, true) . '</pre>';\n if($variation['attributes']['attribute_'.$key]==$val){\n $isDefVariation=true;\n } \n }\n if($isDefVariation){\n $price = $variation['display_price']; \n }\n }\n $selectedPrice = wc_price($price);\n\n// $dump = $dump . '<pre>' . var_export($available_variations, true) . '</pre>';\n\n return $selectedPrice . $dump;\n}\n</code></pre>\n"
},
{
"answer_id": 334952,
"author": "SHEESHRAM",
"author_id": 141392,
"author_profile": "https://wordpress.stackexchange.com/users/141392",
"pm_score": 0,
"selected": false,
"text": "<p>Show single variable price</p>\n\n<pre><code>add_filter( 'woocommerce_show_variation_price', '__return_true' );\n</code></pre>\n"
},
{
"answer_id": 344088,
"author": "Abhinav bhardwaj",
"author_id": 172790,
"author_profile": "https://wordpress.stackexchange.com/users/172790",
"pm_score": 0,
"selected": false,
"text": "<p>upgrading @vivek's code as its code is only working for a single variation </p>\n\n<pre><code> add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);\nfunction custom_variation_price($price, $product) {\n $available_variations = $product->get_available_variations();\n $selectedPrice = '';\n $dump = '';\n $defaultArray = array();\n foreach ($available_variations as $variation) {\n // $dump = $dump . '<pre>' . var_export($variation['attributes'], true) . '</pre>';\n $isDefVariation = false;\n foreach ($product->get_default_attributes() as $key => $val) {\n // $dump = $dump . '<pre>' . var_export($key, true) . '</pre>';\n // $dump = $dump . '<pre>' . var_export($val, true) . '</pre>';\n $defaultArray['attribute_' . $key] = $val;\n }\n **$result = array_diff($defaultArray, $variation['attributes']);**\n **if (empty($result)) {\n $isDefVariation = true;\n $price = $variation['display_price'];\n }**\n }\n\n $selectedPrice = wc_price($price);\n// $dump = $dump . '<pre>' . var_export($available_variations, true) . '</pre>';\n return $selectedPrice . $dump;\n}\n</code></pre>\n\n<p>This will work for multiple variation key</p>\n"
},
{
"answer_id": 386398,
"author": "Stijn Sillen",
"author_id": 204664,
"author_profile": "https://wordpress.stackexchange.com/users/204664",
"pm_score": 0,
"selected": false,
"text": "<p>Upgrading @ Abhinav's code to show minimum price in case there is no default set:</p>\n<pre><code>/**\n * Show default variation price\n * If no default variation, shows min price\n */\n\nadd_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);\nfunction custom_variation_price($price, $product) {\n $available_variations = $product->get_available_variations();\n $selectedPrice = '';\n $dump = '';\n $defaultArray = array();\n foreach ($product->get_default_attributes() as $key => $val) {\n // $dump = $dump . '<pre>' . var_export($key, true) . '</pre>';\n // $dump = $dump . '<pre>' . var_export($val, true) . '</pre>';\n $defaultArray['attribute_' . $key] = $val;\n }\n // $dump = $dump . '<pre>' . var_export($defaultArray, true) . '</pre>';\n if (empty($defaultArray)) {\n $price = $product->get_variation_price( 'min', true ); // no default variation, show min price\n } else {\n foreach ($available_variations as $variation) {\n // $dump = $dump . '<pre>' . var_export($variation['attributes'], true) . '</pre>';\n $isDefVariation = false;\n \n $result = array_diff($defaultArray, $variation['attributes']);\n if (empty($result)) {\n $isDefVariation = true;\n $price = $variation['display_price'];\n break;\n }\n }\n }\n\n $selectedPrice = wc_price($price);\n // $dump = $dump . '<pre>' . var_export($available_variations, true) . '</pre>';\n return $selectedPrice . $dump;\n}\n</code></pre>\n"
}
]
| 2017/10/30 | [
"https://wordpress.stackexchange.com/questions/284428",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31889/"
]
| I'm not sure if this is specific to my site or not, but if anyone knows how to override this behavior, that would be most appreciated! I have WordPress installed in the root directory of my server. There is also an unrelated sub-directory we'll call 'restricted-dir'. I have added an .htaccess file inside that directory with the following code:
```
Deny from all
```
Without that command, if a user visits www.my-domain.com/restricted-dir/ it would list all contents. I would like the user to receive the server's typical 403 Forbidden message, but instead WordPress kicks in and directs the user to my 404 page on my website.
Is there anything I can do to make the 403 page show up instead of the 404 page along with my entire WordPress install? | Try this code:
```
add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);
function custom_variation_price( $price, $product ) {
$available_variations = $product->get_available_variations();
$selectedPrice = '';
$dump = '';
foreach ( $available_variations as $variation )
{
// $dump = $dump . '<pre>' . var_export($variation['attributes'], true) . '</pre>';
$isDefVariation=false;
foreach($product->get_default_attributes() as $key=>$val){
// $dump = $dump . '<pre>' . var_export($key, true) . '</pre>';
// $dump = $dump . '<pre>' . var_export($val, true) . '</pre>';
if($variation['attributes']['attribute_'.$key]==$val){
$isDefVariation=true;
}
}
if($isDefVariation){
$price = $variation['display_price'];
}
}
$selectedPrice = wc_price($price);
// $dump = $dump . '<pre>' . var_export($available_variations, true) . '</pre>';
return $selectedPrice . $dump;
}
``` |
284,431 | <p>I'm currently using Sage 8.5.1 theme and have some password protected pages. The client would like to have the word "Protected" removed but not the title. I've used this code snippet </p>
<pre><code>add_filter( 'protected_title_format', 'remove_protected_text' );
function remove_protected_text() {
return __('%s');
}
</code></pre>
<p>But it removes the title also. I've looked and everywhere seems to use basically the same snippet of code. I've posed this question on Roots Discourse and they said it's not theme specific and to post my question here. Thanks</p>
| [
{
"answer_id": 284433,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 1,
"selected": false,
"text": "<p>You don't want to translate the title, so there's no need to use __() here and you won't translate '%s', because that's a placeholder.</p>\n\n<pre><code>add_filter( 'protected_title_format', 'remove_protected_text' );\nfunction remove_protected_text() {\n return '%s';\n}\n</code></pre>\n\n<p>should work.</p>\n"
},
{
"answer_id": 284439,
"author": "Swati",
"author_id": 123547,
"author_profile": "https://wordpress.stackexchange.com/users/123547",
"pm_score": 0,
"selected": false,
"text": "<p>use a filter function:\nCopy and paste whichever you prefer into your theme functions.php</p>\n\n<pre><code><?php\nfunction the_title_trim($title){\n$pattern[0] = '/Protected:/';\n$replacement[0] = ''; // Enter some text to put in place of Protected:\nreturn preg_replace($pattern, $replacement, $title);\n}\nadd_filter('the_title', 'the_title_trim');\n?>\n</code></pre>\n"
}
]
| 2017/10/30 | [
"https://wordpress.stackexchange.com/questions/284431",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127349/"
]
| I'm currently using Sage 8.5.1 theme and have some password protected pages. The client would like to have the word "Protected" removed but not the title. I've used this code snippet
```
add_filter( 'protected_title_format', 'remove_protected_text' );
function remove_protected_text() {
return __('%s');
}
```
But it removes the title also. I've looked and everywhere seems to use basically the same snippet of code. I've posed this question on Roots Discourse and they said it's not theme specific and to post my question here. Thanks | You don't want to translate the title, so there's no need to use \_\_() here and you won't translate '%s', because that's a placeholder.
```
add_filter( 'protected_title_format', 'remove_protected_text' );
function remove_protected_text() {
return '%s';
}
```
should work. |
284,445 | <p>The following code generates a label for a facet (<a href="https://electricgates.staging.wpengine.com/product-category/home-automation/?fwp_category=home-automation" rel="nofollow noreferrer">see sidebar</a>).</p>
<p>I would like to add a conditional statement that prevents the label generation is the facet if empty.</p>
<pre><code>$(document).on('facetwp-loaded', function() {
$('.facetwp-facet').each(function() {
var facet_name = $(this).attr('data-name');
var facet_label = FWP.settings.labels[facet_name];
if ($('.facet-label[data-for="' + facet_name + '"]').length < 1) {
$(this).before('<h3 class="facet-label" data-for="' + facet_name + '">' + facet_label + '</h3>');
}
});
});
</code></pre>
<p>Edit: <a href="https://facetwp.com/add-labels-above-each-facet/" rel="nofollow noreferrer">Source of code</a></p>
| [
{
"answer_id": 284536,
"author": "Tony M",
"author_id": 71192,
"author_profile": "https://wordpress.stackexchange.com/users/71192",
"pm_score": 1,
"selected": false,
"text": "<p>Your code seems identical to FacetWP's. The only variable I can think of is code placement. You might not be placing the code where it belongs (functions.php or a plugin). A quick fix would be adding their code to your theme's functions.php:</p>\n\n<pre><code> function fwp_add_facet_labels() {\n ?>\n <script>\n (function($) {\n $(document).on('facetwp-loaded', function() {\n $('.facetwp-facet').each(function() {\n var facet_name = $(this).attr('data-name');\n var facet_label = FWP.settings.labels[facet_name];\n if ($('.facet-label[data-for=\"' + facet_name + '\"]').length < 1) {\n $(this).before('<h3 class=\"facet-label\" data-for=\"' + facet_name + '\">' + facet_label + '</h3>');\n }\n });\n });\n })(jQuery);\n </script>\n <?php\n }\n add_action( 'wp_head', 'fwp_add_facet_labels', 100 );\n</code></pre>\n\n<p>Or alternatively follow their instructions: <a href=\"https://facetwp.com/how-to-use-hooks/\" rel=\"nofollow noreferrer\">Here</a></p>\n"
},
{
"answer_id": 330070,
"author": "Alvic",
"author_id": 162118,
"author_profile": "https://wordpress.stackexchange.com/users/162118",
"pm_score": 1,
"selected": false,
"text": "<p>You can this line for it to hide when empty.</p>\n\n<pre><code>&& $(this).children().length > 0)\n</code></pre>\n\n<p>So here is the all the code to add to your function.php file to show the h3 facet name and to hide the facets when empty.</p>\n\n<pre><code>function fwp_add_facet_labels() {\n ?>\n<script>\n(function($) {\n $(document).on('facetwp-loaded', function() {\n $('.facetwp-facet').each(function() {\n var facet_name = $(this).attr('data-name');\n var facet_label = FWP.settings.labels[facet_name];\n if ($('.facet-label[data-for=\"' + facet_name + '\"]').length < 1 && $(this).children()\n .length > 0) {\n $(this).before('<h3 class=\"facet-label\" data-for=\"' + facet_name + '\">' +\n facet_label + '</h3>');\n }\n });\n });\n})(jQuery);\n</script>\n<?php\n }\n add_action( 'wp_head', 'fwp_add_facet_labels', 100 );\n</code></pre>\n"
},
{
"answer_id": 381953,
"author": "nydame",
"author_id": 86502,
"author_profile": "https://wordpress.stackexchange.com/users/86502",
"pm_score": 0,
"selected": false,
"text": "<p>The answers given above aren't wrong, but they both lean on jQuery. That is not a good idea because jQuery is slowly being escorted out of the building by the powers that be at Automattic.</p>\n<p>More importantly, when you actually look at the FacetWP documentation on <a href=\"https://facetwp.com/how-to-use-hooks/\" rel=\"nofollow noreferrer\">How to Use FacetWP Hooks</a>, the instructions clearly tell you to put the code somewhere else. Specifically, you are instructed to download their custom hooks plugin and to paste your code in <strong>custom-hooks.php</strong>. Cheers!</p>\n"
}
]
| 2017/10/30 | [
"https://wordpress.stackexchange.com/questions/284445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57057/"
]
| The following code generates a label for a facet ([see sidebar](https://electricgates.staging.wpengine.com/product-category/home-automation/?fwp_category=home-automation)).
I would like to add a conditional statement that prevents the label generation is the facet if empty.
```
$(document).on('facetwp-loaded', function() {
$('.facetwp-facet').each(function() {
var facet_name = $(this).attr('data-name');
var facet_label = FWP.settings.labels[facet_name];
if ($('.facet-label[data-for="' + facet_name + '"]').length < 1) {
$(this).before('<h3 class="facet-label" data-for="' + facet_name + '">' + facet_label + '</h3>');
}
});
});
```
Edit: [Source of code](https://facetwp.com/add-labels-above-each-facet/) | Your code seems identical to FacetWP's. The only variable I can think of is code placement. You might not be placing the code where it belongs (functions.php or a plugin). A quick fix would be adding their code to your theme's functions.php:
```
function fwp_add_facet_labels() {
?>
<script>
(function($) {
$(document).on('facetwp-loaded', function() {
$('.facetwp-facet').each(function() {
var facet_name = $(this).attr('data-name');
var facet_label = FWP.settings.labels[facet_name];
if ($('.facet-label[data-for="' + facet_name + '"]').length < 1) {
$(this).before('<h3 class="facet-label" data-for="' + facet_name + '">' + facet_label + '</h3>');
}
});
});
})(jQuery);
</script>
<?php
}
add_action( 'wp_head', 'fwp_add_facet_labels', 100 );
```
Or alternatively follow their instructions: [Here](https://facetwp.com/how-to-use-hooks/) |
284,508 | <p>I am currently developing a website which needs user input on posts. An admin will feed the data and regular visitors can notify the errors/additions to specific post. I am using a hidden login form which contains a contributor username and password to let the public login to the admin and make necessary changes. Its all working fine.</p>
<p>What I am looking for is, I don’t want the ‘Update’ button for the Contributor user when revising a post. Always keep it like ‘Submit for review’.</p>
<p>Any ideas? Thanks in advance!</p>
| [
{
"answer_id": 284536,
"author": "Tony M",
"author_id": 71192,
"author_profile": "https://wordpress.stackexchange.com/users/71192",
"pm_score": 1,
"selected": false,
"text": "<p>Your code seems identical to FacetWP's. The only variable I can think of is code placement. You might not be placing the code where it belongs (functions.php or a plugin). A quick fix would be adding their code to your theme's functions.php:</p>\n\n<pre><code> function fwp_add_facet_labels() {\n ?>\n <script>\n (function($) {\n $(document).on('facetwp-loaded', function() {\n $('.facetwp-facet').each(function() {\n var facet_name = $(this).attr('data-name');\n var facet_label = FWP.settings.labels[facet_name];\n if ($('.facet-label[data-for=\"' + facet_name + '\"]').length < 1) {\n $(this).before('<h3 class=\"facet-label\" data-for=\"' + facet_name + '\">' + facet_label + '</h3>');\n }\n });\n });\n })(jQuery);\n </script>\n <?php\n }\n add_action( 'wp_head', 'fwp_add_facet_labels', 100 );\n</code></pre>\n\n<p>Or alternatively follow their instructions: <a href=\"https://facetwp.com/how-to-use-hooks/\" rel=\"nofollow noreferrer\">Here</a></p>\n"
},
{
"answer_id": 330070,
"author": "Alvic",
"author_id": 162118,
"author_profile": "https://wordpress.stackexchange.com/users/162118",
"pm_score": 1,
"selected": false,
"text": "<p>You can this line for it to hide when empty.</p>\n\n<pre><code>&& $(this).children().length > 0)\n</code></pre>\n\n<p>So here is the all the code to add to your function.php file to show the h3 facet name and to hide the facets when empty.</p>\n\n<pre><code>function fwp_add_facet_labels() {\n ?>\n<script>\n(function($) {\n $(document).on('facetwp-loaded', function() {\n $('.facetwp-facet').each(function() {\n var facet_name = $(this).attr('data-name');\n var facet_label = FWP.settings.labels[facet_name];\n if ($('.facet-label[data-for=\"' + facet_name + '\"]').length < 1 && $(this).children()\n .length > 0) {\n $(this).before('<h3 class=\"facet-label\" data-for=\"' + facet_name + '\">' +\n facet_label + '</h3>');\n }\n });\n });\n})(jQuery);\n</script>\n<?php\n }\n add_action( 'wp_head', 'fwp_add_facet_labels', 100 );\n</code></pre>\n"
},
{
"answer_id": 381953,
"author": "nydame",
"author_id": 86502,
"author_profile": "https://wordpress.stackexchange.com/users/86502",
"pm_score": 0,
"selected": false,
"text": "<p>The answers given above aren't wrong, but they both lean on jQuery. That is not a good idea because jQuery is slowly being escorted out of the building by the powers that be at Automattic.</p>\n<p>More importantly, when you actually look at the FacetWP documentation on <a href=\"https://facetwp.com/how-to-use-hooks/\" rel=\"nofollow noreferrer\">How to Use FacetWP Hooks</a>, the instructions clearly tell you to put the code somewhere else. Specifically, you are instructed to download their custom hooks plugin and to paste your code in <strong>custom-hooks.php</strong>. Cheers!</p>\n"
}
]
| 2017/10/31 | [
"https://wordpress.stackexchange.com/questions/284508",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130640/"
]
| I am currently developing a website which needs user input on posts. An admin will feed the data and regular visitors can notify the errors/additions to specific post. I am using a hidden login form which contains a contributor username and password to let the public login to the admin and make necessary changes. Its all working fine.
What I am looking for is, I don’t want the ‘Update’ button for the Contributor user when revising a post. Always keep it like ‘Submit for review’.
Any ideas? Thanks in advance! | Your code seems identical to FacetWP's. The only variable I can think of is code placement. You might not be placing the code where it belongs (functions.php or a plugin). A quick fix would be adding their code to your theme's functions.php:
```
function fwp_add_facet_labels() {
?>
<script>
(function($) {
$(document).on('facetwp-loaded', function() {
$('.facetwp-facet').each(function() {
var facet_name = $(this).attr('data-name');
var facet_label = FWP.settings.labels[facet_name];
if ($('.facet-label[data-for="' + facet_name + '"]').length < 1) {
$(this).before('<h3 class="facet-label" data-for="' + facet_name + '">' + facet_label + '</h3>');
}
});
});
})(jQuery);
</script>
<?php
}
add_action( 'wp_head', 'fwp_add_facet_labels', 100 );
```
Or alternatively follow their instructions: [Here](https://facetwp.com/how-to-use-hooks/) |
284,518 | <pre><code>\inc\admin\inc\images
</code></pre>
<p>In the admin, images are kept in the above path. say: <code>image_1.png</code></p>
<p>I have to call these images in the Wordpress Post admin in the "<strong>Edit</strong>" mode.</p>
<p>what is the correct method to include image source?</p>
<p><strong>I am trying to fix it like this →</strong></p>
<pre><code>'img1' => '<img src="<?php echo get_template_directory_uri(); ?>/inc/admin/images/layout.png" alt="Image 1" title="Image 1">'
</code></pre>
<p>but not working</p>
| [
{
"answer_id": 284523,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 0,
"selected": false,
"text": "<p>So, if your question is, how to include these images in a content area wysiwyg, then the answer is as simple as:</p>\n\n<p><code>https://myurl.com/wp-content/themes/your-theme/inc/admin/inc/images/image_1.png</code></p>\n\n<p>When WP injects images from the media gallery, it uses the full URL, because the WYSIWYG doesn't process PHP prior to load, so the full URL is injected, which would be the same treatment I'd give this unless there are other unmentioned parameters to your situation.</p>\n"
},
{
"answer_id": 284557,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": true,
"text": "<p>Unfortunately your question is still unclear after all the explanations, but based on your efforts, I guess you need to pass the image's URL to a meta field or some sort of array. </p>\n\n<p>So, turning your current code into this will fix the issue:</p>\n\n<pre><code>'img1' => '<img src=\"'.get_template_directory_uri().'/inc/admin/images/layout.png\" alt=\"Image 1\" title=\"Image 1\">'\n</code></pre>\n"
}
]
| 2017/10/31 | [
"https://wordpress.stackexchange.com/questions/284518",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
]
| ```
\inc\admin\inc\images
```
In the admin, images are kept in the above path. say: `image_1.png`
I have to call these images in the Wordpress Post admin in the "**Edit**" mode.
what is the correct method to include image source?
**I am trying to fix it like this →**
```
'img1' => '<img src="<?php echo get_template_directory_uri(); ?>/inc/admin/images/layout.png" alt="Image 1" title="Image 1">'
```
but not working | Unfortunately your question is still unclear after all the explanations, but based on your efforts, I guess you need to pass the image's URL to a meta field or some sort of array.
So, turning your current code into this will fix the issue:
```
'img1' => '<img src="'.get_template_directory_uri().'/inc/admin/images/layout.png" alt="Image 1" title="Image 1">'
``` |
284,533 | <p>Take this basic query:</p>
<pre><code>$posts = new WP_Query(array(
'post_type' => 'page'
's' => 'some search query'
));
</code></pre>
<p>WordPress will split the <code>some search query</code> into 3 separate search terms, which is why I need to make this $wpdb function. I want the same functionality, but with the entire query treated as 1 search term.</p>
<p>Here is where I'm at:</p>
<pre><code>global $wpdb;
$post_type = 'product';
$db_matches = $wpdb->get_results("
SELECT ID
FROM $wpdb->posts
INNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.post_title
WHERE post_title LIKE '%$query%'
AND post_type = '$post_type'
AND post_status = 'publish'
");
</code></pre>
<p>This is my first inner join ever, so it's probably all wrong. Two things need to be done to fix this query:</p>
<ol>
<li>Fix the syntax in the inner join line</li>
<li>Add the language filter in the <code>WHERE</code> clauses (should be something like <code>AND term_taxonomy_id = 2</code>, right?). I'm using Polylang, so I just need to check that the <code>object_id</code> exists in the <code>term_relationships</code> table with the value <code>2</code>.</li>
</ol>
<p>So can anyone give me a hand with this? Thanks a lot.</p>
| [
{
"answer_id": 284546,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>WordPress will split the some search query into 3 separate search\n terms, which is why I need to make this $wpdb function. I want the\n same functionality, but with the entire query treated as 1 search\n term.</p>\n</blockquote>\n\n<p>There are the <code>sentence</code> and <code>exact</code> input search parameters for <code>WP_Query</code>.</p>\n\n<p>Instead of manually constructing the search query yourself, please try e.g.</p>\n\n<pre><code>$query = new WP_Query( [\n 'post_type' => 'page',\n 's' => 'some search query',\n 'sentence' => true,\n 'exact' => true,\n] );\n</code></pre>\n\n<p>The generated SQL query will include:</p>\n\n<pre><code>(wp_posts.post_title LIKE 'some search query') OR \n(wp_posts.post_excerpt LIKE 'some search query') OR \n(wp_posts.post_content LIKE 'some search query')\n</code></pre>\n\n<p>With <code>exact</code> as <code>false</code>, it will change to:</p>\n\n<pre><code>(wp_posts.post_title LIKE '%some search query%') OR \n(wp_posts.post_excerpt LIKE '%some search query%') OR \n(wp_posts.post_content LIKE '%some search query%')\n</code></pre>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 284552,
"author": "trevbro",
"author_id": 130664,
"author_profile": "https://wordpress.stackexchange.com/users/130664",
"pm_score": 3,
"selected": true,
"text": "<ol>\n<li><p>It seems that you in your INNER JOIN, you are joining on </p>\n\n<pre><code>wp_term_relationships.object_id == wp_posts.post_title\n</code></pre>\n\n<p>which is erroneous, since <strong><em>object_id</em></strong> is the post-id in this case-scenario.</p>\n\n<p><em>I want all IDs (post-ids)</em></p>\n\n<pre><code>SELECT ID FROM $wpdb->posts\n</code></pre>\n\n<p><em>Who have a record in the wp_term_relationships table</em></p>\n\n<pre><code>// Now we are comparing the correct columns\nINNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.ID \n</code></pre></li>\n<li><p>Adding the additional where clause</p>\n\n<p><em>Where the term_taxonomy_id is equal to 2</em></p>\n\n<pre><code>WHERE $wpdb->term_relationships.term_taxonomy_id = 2\n</code></pre></li>\n</ol>\n"
}
]
| 2017/10/31 | [
"https://wordpress.stackexchange.com/questions/284533",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44937/"
]
| Take this basic query:
```
$posts = new WP_Query(array(
'post_type' => 'page'
's' => 'some search query'
));
```
WordPress will split the `some search query` into 3 separate search terms, which is why I need to make this $wpdb function. I want the same functionality, but with the entire query treated as 1 search term.
Here is where I'm at:
```
global $wpdb;
$post_type = 'product';
$db_matches = $wpdb->get_results("
SELECT ID
FROM $wpdb->posts
INNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.post_title
WHERE post_title LIKE '%$query%'
AND post_type = '$post_type'
AND post_status = 'publish'
");
```
This is my first inner join ever, so it's probably all wrong. Two things need to be done to fix this query:
1. Fix the syntax in the inner join line
2. Add the language filter in the `WHERE` clauses (should be something like `AND term_taxonomy_id = 2`, right?). I'm using Polylang, so I just need to check that the `object_id` exists in the `term_relationships` table with the value `2`.
So can anyone give me a hand with this? Thanks a lot. | 1. It seems that you in your INNER JOIN, you are joining on
```
wp_term_relationships.object_id == wp_posts.post_title
```
which is erroneous, since ***object\_id*** is the post-id in this case-scenario.
*I want all IDs (post-ids)*
```
SELECT ID FROM $wpdb->posts
```
*Who have a record in the wp\_term\_relationships table*
```
// Now we are comparing the correct columns
INNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.ID
```
2. Adding the additional where clause
*Where the term\_taxonomy\_id is equal to 2*
```
WHERE $wpdb->term_relationships.term_taxonomy_id = 2
``` |
284,556 | <p>I'm facing a problem with wp ajax performance. I'm initializing an ajax call from my javascript side but the response takes 3-5 secs to come back. I understand that admin ajax call has to load the whole wp core and that would definitely be a performance hit for us. </p>
<p>Is there a way to still use the admin ajax call, but without loading all plugins? Essentially in my php api, I'm only using some values from wp-config. Or is there any better ajax suggestions given my use case? Is it possible to use regular rest API(without going through admin-ajax) but could still use the values from wp-config?</p>
<p>Here is my js code(ajax.js):</p>
<pre><code>jQuery.ajax({
url: ajax_object.ajax_url,
data: {
action: 'geo_ip_api'
},
type: 'POST',
success: function (output) {
console.log(output);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
}
});
</code></pre>
<p>Here is my php api(api.php):</p>
<pre><code>function geo_ip_api(){
global $bannerRequiredRegions;
global $ipBlackList;
$isInEU = 'null';
$ipAddress = get_ip_address();
if(!in_array(strtolower($ipAddress), array_map('strtolower', $ipBlackList)))
{
try
{
require_once 'HTTP/Request2.php';
/* retrieving values from wp-config */
$api_url = GEO_API_URL;
$request = new Http_Request2($api_url);
$url = $request->getUrl();
//sending HTTP request logic here. No dependency on wordpress
}
catch (Exception $ex)
{
//TODO: put log here
}
}
echo $isInEU;
</code></pre>
<p>}</p>
<p>Any help appreciated! Thanks in advance. I've searched lots of post and none of those could answer my question. </p>
| [
{
"answer_id": 284546,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>WordPress will split the some search query into 3 separate search\n terms, which is why I need to make this $wpdb function. I want the\n same functionality, but with the entire query treated as 1 search\n term.</p>\n</blockquote>\n\n<p>There are the <code>sentence</code> and <code>exact</code> input search parameters for <code>WP_Query</code>.</p>\n\n<p>Instead of manually constructing the search query yourself, please try e.g.</p>\n\n<pre><code>$query = new WP_Query( [\n 'post_type' => 'page',\n 's' => 'some search query',\n 'sentence' => true,\n 'exact' => true,\n] );\n</code></pre>\n\n<p>The generated SQL query will include:</p>\n\n<pre><code>(wp_posts.post_title LIKE 'some search query') OR \n(wp_posts.post_excerpt LIKE 'some search query') OR \n(wp_posts.post_content LIKE 'some search query')\n</code></pre>\n\n<p>With <code>exact</code> as <code>false</code>, it will change to:</p>\n\n<pre><code>(wp_posts.post_title LIKE '%some search query%') OR \n(wp_posts.post_excerpt LIKE '%some search query%') OR \n(wp_posts.post_content LIKE '%some search query%')\n</code></pre>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 284552,
"author": "trevbro",
"author_id": 130664,
"author_profile": "https://wordpress.stackexchange.com/users/130664",
"pm_score": 3,
"selected": true,
"text": "<ol>\n<li><p>It seems that you in your INNER JOIN, you are joining on </p>\n\n<pre><code>wp_term_relationships.object_id == wp_posts.post_title\n</code></pre>\n\n<p>which is erroneous, since <strong><em>object_id</em></strong> is the post-id in this case-scenario.</p>\n\n<p><em>I want all IDs (post-ids)</em></p>\n\n<pre><code>SELECT ID FROM $wpdb->posts\n</code></pre>\n\n<p><em>Who have a record in the wp_term_relationships table</em></p>\n\n<pre><code>// Now we are comparing the correct columns\nINNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.ID \n</code></pre></li>\n<li><p>Adding the additional where clause</p>\n\n<p><em>Where the term_taxonomy_id is equal to 2</em></p>\n\n<pre><code>WHERE $wpdb->term_relationships.term_taxonomy_id = 2\n</code></pre></li>\n</ol>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284556",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125202/"
]
| I'm facing a problem with wp ajax performance. I'm initializing an ajax call from my javascript side but the response takes 3-5 secs to come back. I understand that admin ajax call has to load the whole wp core and that would definitely be a performance hit for us.
Is there a way to still use the admin ajax call, but without loading all plugins? Essentially in my php api, I'm only using some values from wp-config. Or is there any better ajax suggestions given my use case? Is it possible to use regular rest API(without going through admin-ajax) but could still use the values from wp-config?
Here is my js code(ajax.js):
```
jQuery.ajax({
url: ajax_object.ajax_url,
data: {
action: 'geo_ip_api'
},
type: 'POST',
success: function (output) {
console.log(output);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
}
});
```
Here is my php api(api.php):
```
function geo_ip_api(){
global $bannerRequiredRegions;
global $ipBlackList;
$isInEU = 'null';
$ipAddress = get_ip_address();
if(!in_array(strtolower($ipAddress), array_map('strtolower', $ipBlackList)))
{
try
{
require_once 'HTTP/Request2.php';
/* retrieving values from wp-config */
$api_url = GEO_API_URL;
$request = new Http_Request2($api_url);
$url = $request->getUrl();
//sending HTTP request logic here. No dependency on wordpress
}
catch (Exception $ex)
{
//TODO: put log here
}
}
echo $isInEU;
```
}
Any help appreciated! Thanks in advance. I've searched lots of post and none of those could answer my question. | 1. It seems that you in your INNER JOIN, you are joining on
```
wp_term_relationships.object_id == wp_posts.post_title
```
which is erroneous, since ***object\_id*** is the post-id in this case-scenario.
*I want all IDs (post-ids)*
```
SELECT ID FROM $wpdb->posts
```
*Who have a record in the wp\_term\_relationships table*
```
// Now we are comparing the correct columns
INNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.ID
```
2. Adding the additional where clause
*Where the term\_taxonomy\_id is equal to 2*
```
WHERE $wpdb->term_relationships.term_taxonomy_id = 2
``` |
284,558 | <pre><code>// This will replace the login url
add_filter( 'login_url', 'custom_login_url', 10, 2 );
function custom_login_url( $login_url='http://www.example.com/login/', $redirect='http://www.example.com/login/' )
{
// Set your $login_page_id
return get_permalink(207);
}
</code></pre>
| [
{
"answer_id": 284546,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>WordPress will split the some search query into 3 separate search\n terms, which is why I need to make this $wpdb function. I want the\n same functionality, but with the entire query treated as 1 search\n term.</p>\n</blockquote>\n\n<p>There are the <code>sentence</code> and <code>exact</code> input search parameters for <code>WP_Query</code>.</p>\n\n<p>Instead of manually constructing the search query yourself, please try e.g.</p>\n\n<pre><code>$query = new WP_Query( [\n 'post_type' => 'page',\n 's' => 'some search query',\n 'sentence' => true,\n 'exact' => true,\n] );\n</code></pre>\n\n<p>The generated SQL query will include:</p>\n\n<pre><code>(wp_posts.post_title LIKE 'some search query') OR \n(wp_posts.post_excerpt LIKE 'some search query') OR \n(wp_posts.post_content LIKE 'some search query')\n</code></pre>\n\n<p>With <code>exact</code> as <code>false</code>, it will change to:</p>\n\n<pre><code>(wp_posts.post_title LIKE '%some search query%') OR \n(wp_posts.post_excerpt LIKE '%some search query%') OR \n(wp_posts.post_content LIKE '%some search query%')\n</code></pre>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 284552,
"author": "trevbro",
"author_id": 130664,
"author_profile": "https://wordpress.stackexchange.com/users/130664",
"pm_score": 3,
"selected": true,
"text": "<ol>\n<li><p>It seems that you in your INNER JOIN, you are joining on </p>\n\n<pre><code>wp_term_relationships.object_id == wp_posts.post_title\n</code></pre>\n\n<p>which is erroneous, since <strong><em>object_id</em></strong> is the post-id in this case-scenario.</p>\n\n<p><em>I want all IDs (post-ids)</em></p>\n\n<pre><code>SELECT ID FROM $wpdb->posts\n</code></pre>\n\n<p><em>Who have a record in the wp_term_relationships table</em></p>\n\n<pre><code>// Now we are comparing the correct columns\nINNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.ID \n</code></pre></li>\n<li><p>Adding the additional where clause</p>\n\n<p><em>Where the term_taxonomy_id is equal to 2</em></p>\n\n<pre><code>WHERE $wpdb->term_relationships.term_taxonomy_id = 2\n</code></pre></li>\n</ol>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130683/"
]
| ```
// This will replace the login url
add_filter( 'login_url', 'custom_login_url', 10, 2 );
function custom_login_url( $login_url='http://www.example.com/login/', $redirect='http://www.example.com/login/' )
{
// Set your $login_page_id
return get_permalink(207);
}
``` | 1. It seems that you in your INNER JOIN, you are joining on
```
wp_term_relationships.object_id == wp_posts.post_title
```
which is erroneous, since ***object\_id*** is the post-id in this case-scenario.
*I want all IDs (post-ids)*
```
SELECT ID FROM $wpdb->posts
```
*Who have a record in the wp\_term\_relationships table*
```
// Now we are comparing the correct columns
INNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.ID
```
2. Adding the additional where clause
*Where the term\_taxonomy\_id is equal to 2*
```
WHERE $wpdb->term_relationships.term_taxonomy_id = 2
``` |
284,561 | <p>I want to add only 5 or 6 pages in my footer menu, but won't effect that into other menus like as header menu. Whole things need to do with coding not by using php.ini or .htaccess files.</p>
<p><strong>Note:</strong> If anyone try to add more than 5 or 6 pages then it will not take without editing the code.</p>
<p>thanks in advance. </p>
| [
{
"answer_id": 284546,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>WordPress will split the some search query into 3 separate search\n terms, which is why I need to make this $wpdb function. I want the\n same functionality, but with the entire query treated as 1 search\n term.</p>\n</blockquote>\n\n<p>There are the <code>sentence</code> and <code>exact</code> input search parameters for <code>WP_Query</code>.</p>\n\n<p>Instead of manually constructing the search query yourself, please try e.g.</p>\n\n<pre><code>$query = new WP_Query( [\n 'post_type' => 'page',\n 's' => 'some search query',\n 'sentence' => true,\n 'exact' => true,\n] );\n</code></pre>\n\n<p>The generated SQL query will include:</p>\n\n<pre><code>(wp_posts.post_title LIKE 'some search query') OR \n(wp_posts.post_excerpt LIKE 'some search query') OR \n(wp_posts.post_content LIKE 'some search query')\n</code></pre>\n\n<p>With <code>exact</code> as <code>false</code>, it will change to:</p>\n\n<pre><code>(wp_posts.post_title LIKE '%some search query%') OR \n(wp_posts.post_excerpt LIKE '%some search query%') OR \n(wp_posts.post_content LIKE '%some search query%')\n</code></pre>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 284552,
"author": "trevbro",
"author_id": 130664,
"author_profile": "https://wordpress.stackexchange.com/users/130664",
"pm_score": 3,
"selected": true,
"text": "<ol>\n<li><p>It seems that you in your INNER JOIN, you are joining on </p>\n\n<pre><code>wp_term_relationships.object_id == wp_posts.post_title\n</code></pre>\n\n<p>which is erroneous, since <strong><em>object_id</em></strong> is the post-id in this case-scenario.</p>\n\n<p><em>I want all IDs (post-ids)</em></p>\n\n<pre><code>SELECT ID FROM $wpdb->posts\n</code></pre>\n\n<p><em>Who have a record in the wp_term_relationships table</em></p>\n\n<pre><code>// Now we are comparing the correct columns\nINNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.ID \n</code></pre></li>\n<li><p>Adding the additional where clause</p>\n\n<p><em>Where the term_taxonomy_id is equal to 2</em></p>\n\n<pre><code>WHERE $wpdb->term_relationships.term_taxonomy_id = 2\n</code></pre></li>\n</ol>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284561",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108591/"
]
| I want to add only 5 or 6 pages in my footer menu, but won't effect that into other menus like as header menu. Whole things need to do with coding not by using php.ini or .htaccess files.
**Note:** If anyone try to add more than 5 or 6 pages then it will not take without editing the code.
thanks in advance. | 1. It seems that you in your INNER JOIN, you are joining on
```
wp_term_relationships.object_id == wp_posts.post_title
```
which is erroneous, since ***object\_id*** is the post-id in this case-scenario.
*I want all IDs (post-ids)*
```
SELECT ID FROM $wpdb->posts
```
*Who have a record in the wp\_term\_relationships table*
```
// Now we are comparing the correct columns
INNER JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.ID
```
2. Adding the additional where clause
*Where the term\_taxonomy\_id is equal to 2*
```
WHERE $wpdb->term_relationships.term_taxonomy_id = 2
``` |
284,563 | <p>I am going to move from Blogger to WordPress and I also don't want to set earlier Blogger Permalink structure in WordPress.
Now I want to know if there is any way to redirect URLs as mentioned below.</p>
<p>Current (In Blogger):</p>
<pre><code>http://www.example.com/2017/10/seba-online-form-fill-up-2018.html
</code></pre>
<p>After (In WordPress):</p>
<pre><code>http://www.example.com/seba-online-form-fill-up-2018.html
</code></pre>
<p>That means I want to remove my Blogger's year & month from URL from numbers of indexed URL and redirect them to WordPress generated new URLs.</p>
| [
{
"answer_id": 284565,
"author": "Fernando Baltazar",
"author_id": 10218,
"author_profile": "https://wordpress.stackexchange.com/users/10218",
"pm_score": 0,
"selected": false,
"text": "<p>Well, there are some Data base migrator plugins for that porpuse like <a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow noreferrer\">Migrate DB</a>, obviuosly this is for changes inside a SQL data base used for wordpress and basically this plugin will look for the old URL to change it for the new URLS. So you can search and replace like:</p>\n<p>Search: <a href=\"http://yoursite.in/2017/10/\" rel=\"nofollow noreferrer\">http://yoursite.in/2017/10/</a> <br>\nreplace: <a href=\"http://yoursite.in/\" rel=\"nofollow noreferrer\">http://yoursite.in/</a></p>\n<p>you will have <a href=\"http://yoursite.in/xxxxxx.html\" rel=\"nofollow noreferrer\">http://yoursite.in/xxxxxx.html</a></p>\n<p>Also you can do the same with a text editor like NOTEPAD++ in your backup file. Both method works</p>\n"
},
{
"answer_id": 284587,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 2,
"selected": true,
"text": "<p>If <code>/seba-online-form-fill-up-2018.html</code> is an actual WordPress URL then this is relatively trivial to do in <code>.htaccess</code>. For example, the following one-liner using mod_rewrite could be used. This should be placed <em>before</em> the existing WordPress directives in <code>.htaccess</code>:</p>\n\n<pre><code>RewriteRule ^\\d{4}/\\d{1,2}/(.+\\.html)$ /$1 [R=302,L]\n</code></pre>\n\n<p>This redirects a URL of the form <code>/NNNN/NN/<anything>.html</code> to <code>/<anything>.html</code>. Where <code>N</code> is a digit 0-9 and the month (<code>NN</code>) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change <code>\\d{1,2}</code> to <code>\\d\\d</code>.</p>\n\n<p>The <code>$1</code> in the <em>substitution</em> is a backreference to the captured group in the <code>RewriteRule</code> <em>pattern</em>. ie. <code>(.+\\.html)</code>.</p>\n\n<p>Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.)</p>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| I am going to move from Blogger to WordPress and I also don't want to set earlier Blogger Permalink structure in WordPress.
Now I want to know if there is any way to redirect URLs as mentioned below.
Current (In Blogger):
```
http://www.example.com/2017/10/seba-online-form-fill-up-2018.html
```
After (In WordPress):
```
http://www.example.com/seba-online-form-fill-up-2018.html
```
That means I want to remove my Blogger's year & month from URL from numbers of indexed URL and redirect them to WordPress generated new URLs. | If `/seba-online-form-fill-up-2018.html` is an actual WordPress URL then this is relatively trivial to do in `.htaccess`. For example, the following one-liner using mod\_rewrite could be used. This should be placed *before* the existing WordPress directives in `.htaccess`:
```
RewriteRule ^\d{4}/\d{1,2}/(.+\.html)$ /$1 [R=302,L]
```
This redirects a URL of the form `/NNNN/NN/<anything>.html` to `/<anything>.html`. Where `N` is a digit 0-9 and the month (`NN`) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change `\d{1,2}` to `\d\d`.
The `$1` in the *substitution* is a backreference to the captured group in the `RewriteRule` *pattern*. ie. `(.+\.html)`.
Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.) |
284,566 | <p>I've created a WP shortcode to list out pages which has controls to filter via category and also two layout formats. My issue is that the shortcode is not displaying all the pages that I have marked categories against. The 'box' layout is only showing 1 page and then the loop stops. The 'list' layout shows 3/4 pages that have the category applied. </p>
<p>I think my main issue is getting my head around the ob_clean() and ob_start() output buffering methods. I can't seem to figure out what I am doing wrong and I've been pulling my hair out for a few hours (i.e. I've commented out OB on the list format for now). </p>
<p>I'm hoping someone can tell me something obvious that I am doing wrong:</p>
<pre><code><?php
function display_page_categories() {
// Create unique taxonomy just for pages
$tax = array('label' => 'Categories',
'hierarchical' => true,
'publicly_queryable' => true,
'public' => true,
'show_in_menu' => true, );
register_taxonomy('pages_category', 'page', $tax);
}
// Initialise cats for pages
add_action( 'init', 'display_page_categories' );
function qut_research_pages_shortcode($atts, $content = null)
{
$atts = qut_research_subpages_shortcode_atts($atts);
return qut_research_subpages_shortcode_frontend($atts);
}
\add_shortcode('qut-research-subpages', __NAMESPACE__.'\qut_research_pages_shortcode');
function qut_research_subpages_shortcode_atts($atts)
{
$defaults = array(
'sort_by' => 'menu_order',
'sort_order' => 'asc',
'layout' => 'boxes',
'category' => '',
);
return array_replace_recursive($defaults, $atts);
}
function qut_research_subpages_shortcode_frontend($atts)
{
$args = array(
'post_type' => 'page',
'posts_per_page' => '-1',
);
if (!empty($atts['category'])) {
$args['pages_category'] = $atts['category'];
}
$theme_uri = get_template_directory_uri();
$loop = new \WP_Query($args);
$post_featured_image = get_the_post_thumbnail_url($loop->the_post(),'thumbnail');
$output = '';
if ( $atts['layout'] == 'boxes' || $atts['layout'] == '' ) {
ob_start(); ?>
<div class="row" style="margin-top: 20px">
<?php while ($loop->have_posts()) : $loop->the_post(); ?>
<div class="col-xl-2 col-lg-4 col-md-4 col-sm-4 col-xs-6" style="padding: 5px;">
<a class="project-subpage" href="<?= the_permalink(); ?>">
<figure class="project-box" style="height: 120px; position: relative; background-size: cover; background-image: url(
<?php
if (get_the_post_thumbnail_url($loop->the_post()) ) {
echo get_the_post_thumbnail_url($loop->the_post(),'thumbnail');
} else {
echo $theme_uri. '/img/qut-logo.svg';
}
?>
);">
<figcaption style="position: absolute; display: table; height: 35%; width: 100%; background: rgba(0,0,0,0.6); color: white; font-size: 1rem; text-align: center; left: 0; bottom: 0; ">
<div class="site-title" style="display: table-cell; vertical-align: middle; width: 100%; padding: 0px 10px;">
<p style="margin: 0"><?= the_title(); ?></p>
</div>
</figcaption>
</figure>
</a>
</div>
<?php endwhile; ?>
</div>
<?php $output .= ob_get_contents();
ob_end_clean();
return $output;
\wp_reset_query();
} else if ( ($atts['layout'] == 'list') ) {
//ob_start(); ?>
<ul style="margin-top:20px">
<?php while ($loop->have_posts()) : $loop->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php }
\wp_reset_query();
//ob_end_clean();
}
</code></pre>
| [
{
"answer_id": 284565,
"author": "Fernando Baltazar",
"author_id": 10218,
"author_profile": "https://wordpress.stackexchange.com/users/10218",
"pm_score": 0,
"selected": false,
"text": "<p>Well, there are some Data base migrator plugins for that porpuse like <a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow noreferrer\">Migrate DB</a>, obviuosly this is for changes inside a SQL data base used for wordpress and basically this plugin will look for the old URL to change it for the new URLS. So you can search and replace like:</p>\n<p>Search: <a href=\"http://yoursite.in/2017/10/\" rel=\"nofollow noreferrer\">http://yoursite.in/2017/10/</a> <br>\nreplace: <a href=\"http://yoursite.in/\" rel=\"nofollow noreferrer\">http://yoursite.in/</a></p>\n<p>you will have <a href=\"http://yoursite.in/xxxxxx.html\" rel=\"nofollow noreferrer\">http://yoursite.in/xxxxxx.html</a></p>\n<p>Also you can do the same with a text editor like NOTEPAD++ in your backup file. Both method works</p>\n"
},
{
"answer_id": 284587,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 2,
"selected": true,
"text": "<p>If <code>/seba-online-form-fill-up-2018.html</code> is an actual WordPress URL then this is relatively trivial to do in <code>.htaccess</code>. For example, the following one-liner using mod_rewrite could be used. This should be placed <em>before</em> the existing WordPress directives in <code>.htaccess</code>:</p>\n\n<pre><code>RewriteRule ^\\d{4}/\\d{1,2}/(.+\\.html)$ /$1 [R=302,L]\n</code></pre>\n\n<p>This redirects a URL of the form <code>/NNNN/NN/<anything>.html</code> to <code>/<anything>.html</code>. Where <code>N</code> is a digit 0-9 and the month (<code>NN</code>) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change <code>\\d{1,2}</code> to <code>\\d\\d</code>.</p>\n\n<p>The <code>$1</code> in the <em>substitution</em> is a backreference to the captured group in the <code>RewriteRule</code> <em>pattern</em>. ie. <code>(.+\\.html)</code>.</p>\n\n<p>Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.)</p>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284566",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105819/"
]
| I've created a WP shortcode to list out pages which has controls to filter via category and also two layout formats. My issue is that the shortcode is not displaying all the pages that I have marked categories against. The 'box' layout is only showing 1 page and then the loop stops. The 'list' layout shows 3/4 pages that have the category applied.
I think my main issue is getting my head around the ob\_clean() and ob\_start() output buffering methods. I can't seem to figure out what I am doing wrong and I've been pulling my hair out for a few hours (i.e. I've commented out OB on the list format for now).
I'm hoping someone can tell me something obvious that I am doing wrong:
```
<?php
function display_page_categories() {
// Create unique taxonomy just for pages
$tax = array('label' => 'Categories',
'hierarchical' => true,
'publicly_queryable' => true,
'public' => true,
'show_in_menu' => true, );
register_taxonomy('pages_category', 'page', $tax);
}
// Initialise cats for pages
add_action( 'init', 'display_page_categories' );
function qut_research_pages_shortcode($atts, $content = null)
{
$atts = qut_research_subpages_shortcode_atts($atts);
return qut_research_subpages_shortcode_frontend($atts);
}
\add_shortcode('qut-research-subpages', __NAMESPACE__.'\qut_research_pages_shortcode');
function qut_research_subpages_shortcode_atts($atts)
{
$defaults = array(
'sort_by' => 'menu_order',
'sort_order' => 'asc',
'layout' => 'boxes',
'category' => '',
);
return array_replace_recursive($defaults, $atts);
}
function qut_research_subpages_shortcode_frontend($atts)
{
$args = array(
'post_type' => 'page',
'posts_per_page' => '-1',
);
if (!empty($atts['category'])) {
$args['pages_category'] = $atts['category'];
}
$theme_uri = get_template_directory_uri();
$loop = new \WP_Query($args);
$post_featured_image = get_the_post_thumbnail_url($loop->the_post(),'thumbnail');
$output = '';
if ( $atts['layout'] == 'boxes' || $atts['layout'] == '' ) {
ob_start(); ?>
<div class="row" style="margin-top: 20px">
<?php while ($loop->have_posts()) : $loop->the_post(); ?>
<div class="col-xl-2 col-lg-4 col-md-4 col-sm-4 col-xs-6" style="padding: 5px;">
<a class="project-subpage" href="<?= the_permalink(); ?>">
<figure class="project-box" style="height: 120px; position: relative; background-size: cover; background-image: url(
<?php
if (get_the_post_thumbnail_url($loop->the_post()) ) {
echo get_the_post_thumbnail_url($loop->the_post(),'thumbnail');
} else {
echo $theme_uri. '/img/qut-logo.svg';
}
?>
);">
<figcaption style="position: absolute; display: table; height: 35%; width: 100%; background: rgba(0,0,0,0.6); color: white; font-size: 1rem; text-align: center; left: 0; bottom: 0; ">
<div class="site-title" style="display: table-cell; vertical-align: middle; width: 100%; padding: 0px 10px;">
<p style="margin: 0"><?= the_title(); ?></p>
</div>
</figcaption>
</figure>
</a>
</div>
<?php endwhile; ?>
</div>
<?php $output .= ob_get_contents();
ob_end_clean();
return $output;
\wp_reset_query();
} else if ( ($atts['layout'] == 'list') ) {
//ob_start(); ?>
<ul style="margin-top:20px">
<?php while ($loop->have_posts()) : $loop->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php }
\wp_reset_query();
//ob_end_clean();
}
``` | If `/seba-online-form-fill-up-2018.html` is an actual WordPress URL then this is relatively trivial to do in `.htaccess`. For example, the following one-liner using mod\_rewrite could be used. This should be placed *before* the existing WordPress directives in `.htaccess`:
```
RewriteRule ^\d{4}/\d{1,2}/(.+\.html)$ /$1 [R=302,L]
```
This redirects a URL of the form `/NNNN/NN/<anything>.html` to `/<anything>.html`. Where `N` is a digit 0-9 and the month (`NN`) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change `\d{1,2}` to `\d\d`.
The `$1` in the *substitution* is a backreference to the captured group in the `RewriteRule` *pattern*. ie. `(.+\.html)`.
Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.) |
284,568 | <p>I am building a community site like medium.com.</p>
<p>Instead of creating front-end form, I am going to change default role as Contributor or allow subscriber role to insert posts/ CPT....</p>
<p>I need to know that, do I have to face security problems?</p>
| [
{
"answer_id": 284565,
"author": "Fernando Baltazar",
"author_id": 10218,
"author_profile": "https://wordpress.stackexchange.com/users/10218",
"pm_score": 0,
"selected": false,
"text": "<p>Well, there are some Data base migrator plugins for that porpuse like <a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow noreferrer\">Migrate DB</a>, obviuosly this is for changes inside a SQL data base used for wordpress and basically this plugin will look for the old URL to change it for the new URLS. So you can search and replace like:</p>\n<p>Search: <a href=\"http://yoursite.in/2017/10/\" rel=\"nofollow noreferrer\">http://yoursite.in/2017/10/</a> <br>\nreplace: <a href=\"http://yoursite.in/\" rel=\"nofollow noreferrer\">http://yoursite.in/</a></p>\n<p>you will have <a href=\"http://yoursite.in/xxxxxx.html\" rel=\"nofollow noreferrer\">http://yoursite.in/xxxxxx.html</a></p>\n<p>Also you can do the same with a text editor like NOTEPAD++ in your backup file. Both method works</p>\n"
},
{
"answer_id": 284587,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 2,
"selected": true,
"text": "<p>If <code>/seba-online-form-fill-up-2018.html</code> is an actual WordPress URL then this is relatively trivial to do in <code>.htaccess</code>. For example, the following one-liner using mod_rewrite could be used. This should be placed <em>before</em> the existing WordPress directives in <code>.htaccess</code>:</p>\n\n<pre><code>RewriteRule ^\\d{4}/\\d{1,2}/(.+\\.html)$ /$1 [R=302,L]\n</code></pre>\n\n<p>This redirects a URL of the form <code>/NNNN/NN/<anything>.html</code> to <code>/<anything>.html</code>. Where <code>N</code> is a digit 0-9 and the month (<code>NN</code>) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change <code>\\d{1,2}</code> to <code>\\d\\d</code>.</p>\n\n<p>The <code>$1</code> in the <em>substitution</em> is a backreference to the captured group in the <code>RewriteRule</code> <em>pattern</em>. ie. <code>(.+\\.html)</code>.</p>\n\n<p>Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.)</p>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284568",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123092/"
]
| I am building a community site like medium.com.
Instead of creating front-end form, I am going to change default role as Contributor or allow subscriber role to insert posts/ CPT....
I need to know that, do I have to face security problems? | If `/seba-online-form-fill-up-2018.html` is an actual WordPress URL then this is relatively trivial to do in `.htaccess`. For example, the following one-liner using mod\_rewrite could be used. This should be placed *before* the existing WordPress directives in `.htaccess`:
```
RewriteRule ^\d{4}/\d{1,2}/(.+\.html)$ /$1 [R=302,L]
```
This redirects a URL of the form `/NNNN/NN/<anything>.html` to `/<anything>.html`. Where `N` is a digit 0-9 and the month (`NN`) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change `\d{1,2}` to `\d\d`.
The `$1` in the *substitution* is a backreference to the captured group in the `RewriteRule` *pattern*. ie. `(.+\.html)`.
Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.) |
284,595 | <p>I want a certain subfolder excluded from being handled by WP with its 404 - page not found message.</p>
<p>My problem is: </p>
<ul>
<li><code>example.com/Non_WP/myfile.html</code> - <strong>shows correctly</strong> </li>
</ul>
<p><em>but</em></p>
<ul>
<li><code>example.com/Non_WP/myfile.php</code> - will trigger a <strong>WP 404-page not found</strong> message.</li>
</ul>
<p>Both files, <code>myfile.html</code> and <code>myfile.php</code> exist in the <code>Non_WP</code> folder.</p>
<p>My <code>.htaccess</code> file looks like this:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/(Non_WP|Non_WP/.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>It <em>should</em> exclude WP from handling the "Non_WP" folder.</p>
<p>WP is installed in the root folder and there are no redirect-plugins active.</p>
<p><strong>Any idea what I'm doing wrong? Any idea where to locate the problem other than the <code>.htaccess</code> file?</strong></p>
| [
{
"answer_id": 284599,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 0,
"selected": false,
"text": "<p>There's \"something else\" going on. Providing these two files exist (as you say they do) then you shouldn't have to do anything to allow direct access. This is what the two <code>RewriteCond</code> directives do that check against <code>REQUEST_FILENAME</code> - these two conditions ensure that only requests that do not map to existing files/directories are routed through WP. Without these two conditions then none of your static resources (CSS, JS, images, etc.) would work.</p>\n\n<p>Your additional condition to exclude the <code>/Non_WP</code> directory is an optimisation, since it prevents the file/directory checks. However, as mentioned above, this should not be necessary to make it \"work\".</p>\n\n<p>However, this \"optimisation\" should be moved outside of the <code># BEGIN WordPress</code> block, to prevent your modification being overwritten by WordPress later. Instead of modifying the WordPress block, include the following directive <em>before</em> the WordPress directives (before the <code># BEGIN WordPress</code> comment):</p>\n\n<pre><code>RewriteRule ^(Non_WP|Non_WP/.*)$ - [L]\n</code></pre>\n\n<p>This is effectively the reverse of your <em>condition</em>. If the <code>/Non_WP</code> directory is accessed then do nothing. No further processing of the mod_rewrite directives in the <code>.htaccess</code> file will occur.</p>\n"
},
{
"answer_id": 284637,
"author": "Raphael",
"author_id": 130697,
"author_profile": "https://wordpress.stackexchange.com/users/130697",
"pm_score": 1,
"selected": false,
"text": "<p>Well localized the problem (without understanding it so far)</p>\n\n<p>It was <strong>not the .htaccess file</strong>.</p>\n\n<p>It was <strong>not plugins or themes</strong> (which I deactivated all to see what happens)</p>\n\n<p>But my little php app had their own <strong>session handling</strong> and modified <strong>the header</strong>. Just simple textbook stuff (login etc..) which works flawless outside WP.</p>\n\n<p>I didn't analyse why this happens, but without the session/header stuff my php app works fine alongside WP.</p>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130697/"
]
| I want a certain subfolder excluded from being handled by WP with its 404 - page not found message.
My problem is:
* `example.com/Non_WP/myfile.html` - **shows correctly**
*but*
* `example.com/Non_WP/myfile.php` - will trigger a **WP 404-page not found** message.
Both files, `myfile.html` and `myfile.php` exist in the `Non_WP` folder.
My `.htaccess` file looks like this:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/(Non_WP|Non_WP/.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
It *should* exclude WP from handling the "Non\_WP" folder.
WP is installed in the root folder and there are no redirect-plugins active.
**Any idea what I'm doing wrong? Any idea where to locate the problem other than the `.htaccess` file?** | Well localized the problem (without understanding it so far)
It was **not the .htaccess file**.
It was **not plugins or themes** (which I deactivated all to see what happens)
But my little php app had their own **session handling** and modified **the header**. Just simple textbook stuff (login etc..) which works flawless outside WP.
I didn't analyse why this happens, but without the session/header stuff my php app works fine alongside WP. |
284,606 | <p>I have a problem with a custom WP_Query. The query args are:</p>
<pre><code>$args = array(
'posts_per_page' => -1,
'post_type' => 'adressen',
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'adresse_anzeigen_%_anzeige_branche',
'compare' => 'LIKE',
'value' => $clientId
),
array(
'key' => 'adresse_anzeigen_%_anzeige_aktiv',
'compare' => '=',
'value' => "1"
)
)
);
</code></pre>
<p>(The meta key pattern are predefined from Advanced Custom Fields)</p>
<p>My Problem in the dump of the WP_Query Object, WordPress converts it to this:</p>
<pre><code>SELECT wp_2_posts.* FROM wp_2_posts
INNER JOIN wp_2_postmeta ON ( wp_2_posts.ID = wp_2_postmeta.post_id )
INNER JOIN wp_2_postmeta AS mt1 ON ( wp_2_posts.ID = mt1.post_id )
WHERE 1=1 AND
(
(
wp_2_postmeta.meta_key = 'adresse_anzeigen_{783ec3ed63725295bd6fd75a91ca47bfebd15fa5b4aac1ab7eafd49f682034e6}_anzeige_branche' AND
wp_2_postmeta.meta_value LIKE '{783ec3ed63725295bd6fd75a91ca47bfebd15fa5b4aac1ab7eafd49f682034e6}203{783ec3ed63725295bd6fd75a91ca47bfebd15fa5b4aac1ab7eafd49f682034e6}'
)
AND
(
mt1.meta_key = 'adresse_anzeigen_{783ec3ed63725295bd6fd75a91ca47bfebd15fa5b4aac1ab7eafd49f682034e6}_anzeige_aktiv' AND
mt1.meta_value = '1'
)
)
AND wp_2_posts.post_type = 'adressen'
AND
(
wp_2_posts.post_status = 'publish' OR
wp_2_posts.post_status = 'acf-disabled' OR
wp_2_posts.post_status = 'private'
)
GROUP BY wp_2_posts.ID
ORDER BY wp_2_posts.post_title ASC
</code></pre>
<p>The % sign and the quotes are not numbers? Could someone explain why?</p>
| [
{
"answer_id": 284599,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 0,
"selected": false,
"text": "<p>There's \"something else\" going on. Providing these two files exist (as you say they do) then you shouldn't have to do anything to allow direct access. This is what the two <code>RewriteCond</code> directives do that check against <code>REQUEST_FILENAME</code> - these two conditions ensure that only requests that do not map to existing files/directories are routed through WP. Without these two conditions then none of your static resources (CSS, JS, images, etc.) would work.</p>\n\n<p>Your additional condition to exclude the <code>/Non_WP</code> directory is an optimisation, since it prevents the file/directory checks. However, as mentioned above, this should not be necessary to make it \"work\".</p>\n\n<p>However, this \"optimisation\" should be moved outside of the <code># BEGIN WordPress</code> block, to prevent your modification being overwritten by WordPress later. Instead of modifying the WordPress block, include the following directive <em>before</em> the WordPress directives (before the <code># BEGIN WordPress</code> comment):</p>\n\n<pre><code>RewriteRule ^(Non_WP|Non_WP/.*)$ - [L]\n</code></pre>\n\n<p>This is effectively the reverse of your <em>condition</em>. If the <code>/Non_WP</code> directory is accessed then do nothing. No further processing of the mod_rewrite directives in the <code>.htaccess</code> file will occur.</p>\n"
},
{
"answer_id": 284637,
"author": "Raphael",
"author_id": 130697,
"author_profile": "https://wordpress.stackexchange.com/users/130697",
"pm_score": 1,
"selected": false,
"text": "<p>Well localized the problem (without understanding it so far)</p>\n\n<p>It was <strong>not the .htaccess file</strong>.</p>\n\n<p>It was <strong>not plugins or themes</strong> (which I deactivated all to see what happens)</p>\n\n<p>But my little php app had their own <strong>session handling</strong> and modified <strong>the header</strong>. Just simple textbook stuff (login etc..) which works flawless outside WP.</p>\n\n<p>I didn't analyse why this happens, but without the session/header stuff my php app works fine alongside WP.</p>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284606",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130709/"
]
| I have a problem with a custom WP\_Query. The query args are:
```
$args = array(
'posts_per_page' => -1,
'post_type' => 'adressen',
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'adresse_anzeigen_%_anzeige_branche',
'compare' => 'LIKE',
'value' => $clientId
),
array(
'key' => 'adresse_anzeigen_%_anzeige_aktiv',
'compare' => '=',
'value' => "1"
)
)
);
```
(The meta key pattern are predefined from Advanced Custom Fields)
My Problem in the dump of the WP\_Query Object, WordPress converts it to this:
```
SELECT wp_2_posts.* FROM wp_2_posts
INNER JOIN wp_2_postmeta ON ( wp_2_posts.ID = wp_2_postmeta.post_id )
INNER JOIN wp_2_postmeta AS mt1 ON ( wp_2_posts.ID = mt1.post_id )
WHERE 1=1 AND
(
(
wp_2_postmeta.meta_key = 'adresse_anzeigen_{783ec3ed63725295bd6fd75a91ca47bfebd15fa5b4aac1ab7eafd49f682034e6}_anzeige_branche' AND
wp_2_postmeta.meta_value LIKE '{783ec3ed63725295bd6fd75a91ca47bfebd15fa5b4aac1ab7eafd49f682034e6}203{783ec3ed63725295bd6fd75a91ca47bfebd15fa5b4aac1ab7eafd49f682034e6}'
)
AND
(
mt1.meta_key = 'adresse_anzeigen_{783ec3ed63725295bd6fd75a91ca47bfebd15fa5b4aac1ab7eafd49f682034e6}_anzeige_aktiv' AND
mt1.meta_value = '1'
)
)
AND wp_2_posts.post_type = 'adressen'
AND
(
wp_2_posts.post_status = 'publish' OR
wp_2_posts.post_status = 'acf-disabled' OR
wp_2_posts.post_status = 'private'
)
GROUP BY wp_2_posts.ID
ORDER BY wp_2_posts.post_title ASC
```
The % sign and the quotes are not numbers? Could someone explain why? | Well localized the problem (without understanding it so far)
It was **not the .htaccess file**.
It was **not plugins or themes** (which I deactivated all to see what happens)
But my little php app had their own **session handling** and modified **the header**. Just simple textbook stuff (login etc..) which works flawless outside WP.
I didn't analyse why this happens, but without the session/header stuff my php app works fine alongside WP. |
284,611 | <p>Hi I am trying to enqueue bootstrap javascript file. But it depends on JQuery and Popper.js. So, I am loading PopperJS from CDN and I am mentioning both JQuery and PopperJS as dependencies on the Bootstrap enqueue. I am not enqueueing JQuery because if learned that Wordpress loads it if you just mention it as a dependency. Like the following:-</p>
<pre><code>wp_enqueue_script( 'popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js', array(), null, true );
wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js', array('jquery', 'popper'), null, true );
</code></pre>
<p>However, when I view the source code of my Wordpress site, I see the JQuery version loaded is 1.12.4. The current stable version is 3.2.1. So, how do I rectify this problem. Should I do the unrecommended thing of saving JQuery file to server and enqueueing it separately?</p>
| [
{
"answer_id": 284599,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 0,
"selected": false,
"text": "<p>There's \"something else\" going on. Providing these two files exist (as you say they do) then you shouldn't have to do anything to allow direct access. This is what the two <code>RewriteCond</code> directives do that check against <code>REQUEST_FILENAME</code> - these two conditions ensure that only requests that do not map to existing files/directories are routed through WP. Without these two conditions then none of your static resources (CSS, JS, images, etc.) would work.</p>\n\n<p>Your additional condition to exclude the <code>/Non_WP</code> directory is an optimisation, since it prevents the file/directory checks. However, as mentioned above, this should not be necessary to make it \"work\".</p>\n\n<p>However, this \"optimisation\" should be moved outside of the <code># BEGIN WordPress</code> block, to prevent your modification being overwritten by WordPress later. Instead of modifying the WordPress block, include the following directive <em>before</em> the WordPress directives (before the <code># BEGIN WordPress</code> comment):</p>\n\n<pre><code>RewriteRule ^(Non_WP|Non_WP/.*)$ - [L]\n</code></pre>\n\n<p>This is effectively the reverse of your <em>condition</em>. If the <code>/Non_WP</code> directory is accessed then do nothing. No further processing of the mod_rewrite directives in the <code>.htaccess</code> file will occur.</p>\n"
},
{
"answer_id": 284637,
"author": "Raphael",
"author_id": 130697,
"author_profile": "https://wordpress.stackexchange.com/users/130697",
"pm_score": 1,
"selected": false,
"text": "<p>Well localized the problem (without understanding it so far)</p>\n\n<p>It was <strong>not the .htaccess file</strong>.</p>\n\n<p>It was <strong>not plugins or themes</strong> (which I deactivated all to see what happens)</p>\n\n<p>But my little php app had their own <strong>session handling</strong> and modified <strong>the header</strong>. Just simple textbook stuff (login etc..) which works flawless outside WP.</p>\n\n<p>I didn't analyse why this happens, but without the session/header stuff my php app works fine alongside WP.</p>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284611",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130258/"
]
| Hi I am trying to enqueue bootstrap javascript file. But it depends on JQuery and Popper.js. So, I am loading PopperJS from CDN and I am mentioning both JQuery and PopperJS as dependencies on the Bootstrap enqueue. I am not enqueueing JQuery because if learned that Wordpress loads it if you just mention it as a dependency. Like the following:-
```
wp_enqueue_script( 'popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js', array(), null, true );
wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js', array('jquery', 'popper'), null, true );
```
However, when I view the source code of my Wordpress site, I see the JQuery version loaded is 1.12.4. The current stable version is 3.2.1. So, how do I rectify this problem. Should I do the unrecommended thing of saving JQuery file to server and enqueueing it separately? | Well localized the problem (without understanding it so far)
It was **not the .htaccess file**.
It was **not plugins or themes** (which I deactivated all to see what happens)
But my little php app had their own **session handling** and modified **the header**. Just simple textbook stuff (login etc..) which works flawless outside WP.
I didn't analyse why this happens, but without the session/header stuff my php app works fine alongside WP. |
284,622 | <p>When number of posts on tag pages is less than 3. <br>
I want to show more related or random posts, to fill max number of posts per page, which is 10.<br></p>
<p>How to achieve that? Is it possible to check number of posts in loop within default wordpress loop? <br></p>
<p>I use default wordpress loop which essentially looks like that.</p>
<pre><code><?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
// posts
<?php endwhile; ?>
<?php endif; ?>
</code></pre>
<p>I tried changing this loop to wp_query but cannot make it work and would rather stick with default but then with default it might not be possible?</p>
| [
{
"answer_id": 284629,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, you can, although I would not recommend using random pages, as anything involving randomness is very bad for performance, traffic scaling, and page load times</p>\n\n<h2>About <code>$wp_query</code></h2>\n\n<p>The reason swapping <code>have_posts</code> for <code>$wp_query->have_posts()</code> won't do anything is twofold:</p>\n\n<ul>\n<li>you have to actually check for the 3 posts</li>\n<li>they are exactly the same thing</li>\n</ul>\n\n<p><code>$wp_query</code> is a global variable, and represents the main query, <code>have_posts</code> and <code>the_post</code> etc are all wrappers for <code>global $wp_query; $wp_query->the_post()</code> etc, where <code>$wp_query</code> is a <code>WP_Query</code> object</p>\n\n<p>Now that we know it's a <code>WP_Query</code> object, <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">we can google it and look at that classes docs</a> and see that it has a member variable named:</p>\n\n<blockquote>\n <p><strong><code>$found_posts</code></strong></p>\n \n <p>The total number of posts found matching the current query parameters</p>\n</blockquote>\n\n<p>So your check would be:</p>\n\n<pre><code>// after the main loop\nglobal $wp_query;\nif ( 4 > $wp_query->found_posts ) {\n // do something to make up the numbers here\n}\n</code></pre>\n\n<p>That something could be to do another query for the latest posts, or pre-picked posts, an advertisement, who knows, perhaps even a <code>WP_Query</code> loop, but that's the subject of another question</p>\n"
},
{
"answer_id": 284631,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": true,
"text": "<p>There are two steps to get this working:</p>\n\n<ol>\n<li><p>Add a counter to your main loop, so you can check how many posts are output.</p></li>\n<li><p>If your counter is less than 3, run a second query and output.</p></li>\n</ol>\n\n<p>So for step 1, set a counter before your loop and increment it each time the loop runs, like so:</p>\n\n<pre><code><?php\n// create your counter variable\n$counter = 0;\nif (have_posts()) :\n while (have_posts()) : the_post();\n // add 1 to your counter, as 1 post was just output\n $counter++;\n // (display the posts)\n endwhile;\nendif; ?>\n</code></pre>\n\n<p>Step two: check your counter variable, then run another query if needed.</p>\n\n<pre><code><?php\n// if counter is less than 3, run a separate query\nif($counter < 3) {\n // get the ID of the current Tag\n $tag_id = get_queried_object()->term_id;\n // set up query arguments\n $args = array(\n // only pull Posts\n 'post_type' => 'post',\n // don't pull Posts that have the current Tag - prevents duplicates\n 'tag__not_in' => array(\"$tag_id\"),\n // set how many Posts to grab\n 'posts_per_page' => 3\n );\n $extraPosts = new WP_Query($args);\n if($extraPosts->have_posts()):\n while($extraPosts->have_posts()) : $extraPosts->the_post();\n // display the posts)\n endwhile;\n endif;\n} ?>\n</code></pre>\n\n<p>If you want the Tag Archive to always show exactly 3 posts, then right after the opening part of the \"if\" statement, calculate how many to get:</p>\n\n<pre><code>$numberToGet = 3 - $counter;\n</code></pre>\n\n<p>then set <code>'posts_per_page' => \"$numberToGet\"</code> so it's dynamic.</p>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119931/"
]
| When number of posts on tag pages is less than 3.
I want to show more related or random posts, to fill max number of posts per page, which is 10.
How to achieve that? Is it possible to check number of posts in loop within default wordpress loop?
I use default wordpress loop which essentially looks like that.
```
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
// posts
<?php endwhile; ?>
<?php endif; ?>
```
I tried changing this loop to wp\_query but cannot make it work and would rather stick with default but then with default it might not be possible? | There are two steps to get this working:
1. Add a counter to your main loop, so you can check how many posts are output.
2. If your counter is less than 3, run a second query and output.
So for step 1, set a counter before your loop and increment it each time the loop runs, like so:
```
<?php
// create your counter variable
$counter = 0;
if (have_posts()) :
while (have_posts()) : the_post();
// add 1 to your counter, as 1 post was just output
$counter++;
// (display the posts)
endwhile;
endif; ?>
```
Step two: check your counter variable, then run another query if needed.
```
<?php
// if counter is less than 3, run a separate query
if($counter < 3) {
// get the ID of the current Tag
$tag_id = get_queried_object()->term_id;
// set up query arguments
$args = array(
// only pull Posts
'post_type' => 'post',
// don't pull Posts that have the current Tag - prevents duplicates
'tag__not_in' => array("$tag_id"),
// set how many Posts to grab
'posts_per_page' => 3
);
$extraPosts = new WP_Query($args);
if($extraPosts->have_posts()):
while($extraPosts->have_posts()) : $extraPosts->the_post();
// display the posts)
endwhile;
endif;
} ?>
```
If you want the Tag Archive to always show exactly 3 posts, then right after the opening part of the "if" statement, calculate how many to get:
```
$numberToGet = 3 - $counter;
```
then set `'posts_per_page' => "$numberToGet"` so it's dynamic. |
284,635 | <p>I am struggling to implement nonces through XML request to php backend using the Wordpress nonce validation when creating forms dynamically. I am ok with the form built version </p>
<pre><code>wp_nonce_field( 'delete-comment_'.$comment_id );
</code></pre>
<p>So I am trying to use the other nonce options when passing via javascript localization. </p>
<pre><code>$nonce = wp_create_nonce( 'my-action_'.$post->ID );
</code></pre>
<p>Then to verify, there seems to be two options. </p>
<pre><code>check_ajax_referer( 'process-comment' );
wp_verify_nonce( $_REQUEST['my_nonce'], 'process-comment'.$comment_id );
</code></pre>
<p>Both of which I seem unable to make recognised in the validation. There is a number being passed through the post, and I have tried, naming, not naming, and a lot of other options too, but seem unsuccessful to do something that is meant to be simple. The examples given on the codex are mightily confusing too. </p>
<p>eg: here <a href="https://codex.wordpress.org/WordPress_Nonces" rel="nofollow noreferrer">https://codex.wordpress.org/WordPress_Nonces</a></p>
<p>Can anyone shed any light on this frustrating experience? Many Thanks</p>
| [
{
"answer_id": 284648,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>The root problem is that none of your nonces match</p>\n\n<ul>\n<li><p>You create a nonce for: <code>'delete-comment_'.$comment_id</code></p></li>\n<li><p>Then you create a nonce for: <code>'my-action_'.$post->ID</code></p></li>\n<li><p>Then you check the referrer for a completely different nonce: <code>'process-comment'</code></p></li>\n<li><p>Followed by a verification check on the nonce itself using yet another unique nonce name: <code>'process-comment'.$comment_id</code></p></li>\n</ul>\n\n<p>So clearly, since none of them match, the checks will not match either and reject the nonce value passed.</p>\n\n<p>When you generate a nonce, you give it an action/name, and it generates a token from that. You then check the token against the action/name when processing a request to verify the user did indeed intend to do that action.</p>\n\n<p>e.g. create a nonce for <code>'delete-comment_'.$comment_id</code> that you can then send with a delete comment request. Then the handler can check if you intended to delete that comment. It can't do that if the action/name doesn't match.</p>\n\n<h2>A Further Note on Auth</h2>\n\n<p>Nonces are a method of verifying intention, but they are not a method of authentication. Always check the user is logged in, and that the user is actually capable of doing what you intended via the <code>current_user_can</code> function.</p>\n\n<p>A nonce can tell you that the user did indeed click the delete comment button, it doesn't tell you if they're allowed to delete comments though</p>\n"
},
{
"answer_id": 285143,
"author": "digitalcreative.tech",
"author_id": 130700,
"author_profile": "https://wordpress.stackexchange.com/users/130700",
"pm_score": 2,
"selected": true,
"text": "<p>Okay, so I found a working solution which is as simple as I thought the whole process should be. The confusing Wordpress codex made things harder really. </p>\n\n<p>The creation and naming of the nonce is as simple as:<br>\n<code>wp_create_nonce( 'example' );</code> </p>\n\n<p>This is passed though AJAX and localisation of the script to the PHP. </p>\n\n<p>Then during a $_POST verification; all that is needed is to pass the post name as the second parameter in the verification function. eg:<br>\n<code>check_ajax_referer( 'example', 'nonce')</code> </p>\n\n<p><code>nonce</code> is the name of the $_POST identifier eg:<br>\n<code>$_POST['nonce']</code> </p>\n\n<p>Somehow it was really hard to understand this through the codex, and other examples found through the web. I hope this explanation can help someone else struggling with the codex and nonces.</p>\n"
}
]
| 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284635",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130700/"
]
| I am struggling to implement nonces through XML request to php backend using the Wordpress nonce validation when creating forms dynamically. I am ok with the form built version
```
wp_nonce_field( 'delete-comment_'.$comment_id );
```
So I am trying to use the other nonce options when passing via javascript localization.
```
$nonce = wp_create_nonce( 'my-action_'.$post->ID );
```
Then to verify, there seems to be two options.
```
check_ajax_referer( 'process-comment' );
wp_verify_nonce( $_REQUEST['my_nonce'], 'process-comment'.$comment_id );
```
Both of which I seem unable to make recognised in the validation. There is a number being passed through the post, and I have tried, naming, not naming, and a lot of other options too, but seem unsuccessful to do something that is meant to be simple. The examples given on the codex are mightily confusing too.
eg: here <https://codex.wordpress.org/WordPress_Nonces>
Can anyone shed any light on this frustrating experience? Many Thanks | Okay, so I found a working solution which is as simple as I thought the whole process should be. The confusing Wordpress codex made things harder really.
The creation and naming of the nonce is as simple as:
`wp_create_nonce( 'example' );`
This is passed though AJAX and localisation of the script to the PHP.
Then during a $\_POST verification; all that is needed is to pass the post name as the second parameter in the verification function. eg:
`check_ajax_referer( 'example', 'nonce')`
`nonce` is the name of the $\_POST identifier eg:
`$_POST['nonce']`
Somehow it was really hard to understand this through the codex, and other examples found through the web. I hope this explanation can help someone else struggling with the codex and nonces. |
284,666 | <p>I recently purchased a theme which includes the option to display a banner in the header. The banner can be displayed using either a static image or javascript. The particular javascript code I'm using is for an Amazon banner ad and is displayed on the frontend via an iframe.</p>
<p>Using a static image the banner displays correctly as you can see here: <a href="http://capethemes.com/demo/portal/review/" rel="nofollow noreferrer">http://capethemes.com/demo/portal/review/</a></p>
<p>When using the javascript code, however, the banner is not visible. Upon inspecting the source code, I discovered that the script tags and html containing block are there but the iframe element is missing.</p>
<p>Anyway, I was able to ascertain that it is a styling issue but am not sure how to resolve it. The following default theme styles are being applied to the <code>.headad</code> element:</p>
<pre><code>.headad {
float: right;
position: absolute;
top: 50%;
right: 0;
margin: -65px 0 0 0;
}
</code></pre>
<p>...and here's the snippet used to display the banner:</p>
<pre><code>echo '<div class="clearfix"></div><div class="headad">';
echo htmlspecialchars_decode($themnific_redux['tmnf-headad-script']);
echo '</div>';
</code></pre>
<h2>UPDATE #1</h2>
<p>I've found I need to set a value for the width property on the <code>.headad</code> div to get the banner to display. Presumably this is because it's a responsive banner and therefore there has to be a width specified for the containing element so the appropriately sized banner image can be served.</p>
<p>Here's an overview of all the relevant details:</p>
<h2>HTML markup of banner ad and containing div (I have only included the outer HTML)</h2>
<pre><code><div class="headad">
<script type="text/javascript"></script>
<script></script>
<div ><iframe></iframe></div>
</div>
</code></pre>
<h2>CSS for <code>.headad</code> element</h2>
<pre><code>.headad {
float: right;
position: absolute;
top: 50%;
right: 0;
margin: -65px 0 0 0;
}
</code></pre>
<p>This is the default theme CSS. I have changed <code>float: right;</code> to <code>float: none;</code> because <code>position: absolute;</code> is already being applied to the element. As I have already mentioned, to get the banner to display I have to set a value for the width property.</p>
<h2>iframe CSS</h2>
<pre><code>iframe {
border: none;
display: inline-block;
width: 728px;
height: 90px;
}
</code></pre>
<h2>UPDATE #2</h2>
<p>I reproduced this on jsfiddle. You can view it <a href="https://jsfiddle.net/Lmee6nhp/1/" rel="nofollow noreferrer">here</a>.
Because this is a responsive banner, the width of the containing element has to be specified so the appropriately sized image can be returned. Maybe have to define a set of width property values using media queries for the <code>.headad</code> element? </p>
| [
{
"answer_id": 285305,
"author": "GDY",
"author_id": 52227,
"author_profile": "https://wordpress.stackexchange.com/users/52227",
"pm_score": 0,
"selected": false,
"text": "<p>Just digged into this problem with dev tools. Somehow it gets computed with display none ... i don't know exactly why this happens. Seems like there is some strange inline style that gets added async …</p>\n\n<p>Try this:</p>\n\n<pre><code>#header.left-header .headad {\n display: block !important;\n}\n</code></pre>\n"
},
{
"answer_id": 285308,
"author": "Kumar",
"author_id": 32466,
"author_profile": "https://wordpress.stackexchange.com/users/32466",
"pm_score": 1,
"selected": false,
"text": "<p>It's there and visible in Incognito mode, it's being blocked by one of the adBlocker extension that you might be using in your browser.</p>\n\n<p>The best workaround would be is to change the class from <code>headad</code> to something more generic like <code>head-banner</code>.</p>\n\n<p>Make sure you update the style in your theme/plugin.</p>\n\n<p><a href=\"https://i.stack.imgur.com/roegS.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/roegS.jpg\" alt=\"Blocked by adblock\"></a></p>\n\n<p>Banner with updated class: </p>\n\n<p><a href=\"https://i.stack.imgur.com/pTyOH.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pTyOH.jpg\" alt=\"Banner with updated class and style\"></a></p>\n"
},
{
"answer_id": 285487,
"author": "jrcollins",
"author_id": 68414,
"author_profile": "https://wordpress.stackexchange.com/users/68414",
"pm_score": -1,
"selected": true,
"text": "<p>As already stated in my question, to display the banner ad a width has to be specified for the containing <code>.headad</code> element so the correctly sized image can be displayed. This is because the <code>.headad</code> element has <code>position:absolute</code> applied to it and so has no inherent width.</p>\n\n<p>The only way to display the banner ad across the full range of browser/screen sizes is to use multiple CSS media queries. Even then, it is necessary to make a number of other styling adjustments to account for changes in the relative heights of the various elements.</p>\n\n<p>Anyway, I've decided it's just not worth pursuing this any further. I will edit the style sheet so that the banner ad is only displayed when the browser/screen size is large enough to accommodate the full sized banner.</p>\n\n<p>Thank you to everyone who helped out with this question.</p>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284666",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
]
| I recently purchased a theme which includes the option to display a banner in the header. The banner can be displayed using either a static image or javascript. The particular javascript code I'm using is for an Amazon banner ad and is displayed on the frontend via an iframe.
Using a static image the banner displays correctly as you can see here: <http://capethemes.com/demo/portal/review/>
When using the javascript code, however, the banner is not visible. Upon inspecting the source code, I discovered that the script tags and html containing block are there but the iframe element is missing.
Anyway, I was able to ascertain that it is a styling issue but am not sure how to resolve it. The following default theme styles are being applied to the `.headad` element:
```
.headad {
float: right;
position: absolute;
top: 50%;
right: 0;
margin: -65px 0 0 0;
}
```
...and here's the snippet used to display the banner:
```
echo '<div class="clearfix"></div><div class="headad">';
echo htmlspecialchars_decode($themnific_redux['tmnf-headad-script']);
echo '</div>';
```
UPDATE #1
---------
I've found I need to set a value for the width property on the `.headad` div to get the banner to display. Presumably this is because it's a responsive banner and therefore there has to be a width specified for the containing element so the appropriately sized banner image can be served.
Here's an overview of all the relevant details:
HTML markup of banner ad and containing div (I have only included the outer HTML)
---------------------------------------------------------------------------------
```
<div class="headad">
<script type="text/javascript"></script>
<script></script>
<div ><iframe></iframe></div>
</div>
```
CSS for `.headad` element
-------------------------
```
.headad {
float: right;
position: absolute;
top: 50%;
right: 0;
margin: -65px 0 0 0;
}
```
This is the default theme CSS. I have changed `float: right;` to `float: none;` because `position: absolute;` is already being applied to the element. As I have already mentioned, to get the banner to display I have to set a value for the width property.
iframe CSS
----------
```
iframe {
border: none;
display: inline-block;
width: 728px;
height: 90px;
}
```
UPDATE #2
---------
I reproduced this on jsfiddle. You can view it [here](https://jsfiddle.net/Lmee6nhp/1/).
Because this is a responsive banner, the width of the containing element has to be specified so the appropriately sized image can be returned. Maybe have to define a set of width property values using media queries for the `.headad` element? | As already stated in my question, to display the banner ad a width has to be specified for the containing `.headad` element so the correctly sized image can be displayed. This is because the `.headad` element has `position:absolute` applied to it and so has no inherent width.
The only way to display the banner ad across the full range of browser/screen sizes is to use multiple CSS media queries. Even then, it is necessary to make a number of other styling adjustments to account for changes in the relative heights of the various elements.
Anyway, I've decided it's just not worth pursuing this any further. I will edit the style sheet so that the banner ad is only displayed when the browser/screen size is large enough to accommodate the full sized banner.
Thank you to everyone who helped out with this question. |
284,683 | <p>I have written a simple code to do something after a post is updated or published (its related to the varnish purge). I put my code inside post.php file. Everything was just fine before the latest update (4.8.3), after that all my codes were vanished!! of course it is a normal behavior because the post.php file has been replaced with a new one from update patch. I want to know how can I execute some code after a post is updated or published and my codes do not disappear after a Wordpress update? I don't want to use plugins too :D. Thank you.</p>
| [
{
"answer_id": 284686,
"author": "Jlil",
"author_id": 83204,
"author_profile": "https://wordpress.stackexchange.com/users/83204",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\nadd_action( 'save_post', 'varnish_purge' );\nfunction varnish_purge()\n{\n // code here\n} \n</code></pre>\n"
},
{
"answer_id": 284687,
"author": "Jesse Vlasveld",
"author_id": 87884,
"author_profile": "https://wordpress.stackexchange.com/users/87884",
"pm_score": 2,
"selected": true,
"text": "<p>You're looking for the <code>save_post</code> <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">action</a>. This allows you to add a function when a post is saved (updated).</p>\n\n<p>You can hook into it like this:</p>\n\n<pre><code>function your_save_post_function( $post_id ) {\n}\n\nadd_action( 'save_post', 'your_save_post_function' );\n</code></pre>\n\n<p>Remember to not change WordPress Core files, as these will be overwritten when WordPress is updated. You can put this code in your <code>functions.php</code> file, or anywhere else in your theme folder.</p>\n"
},
{
"answer_id": 284690,
"author": "Malay Solanki",
"author_id": 130744,
"author_profile": "https://wordpress.stackexchange.com/users/130744",
"pm_score": 0,
"selected": false,
"text": "<p>You can replace publish_{post} , where {post} is any wordpress post type. </p>\n\n<pre><code>function post_published_notification( $ID, $post ) {\n $author = $post->post_author; /* Post author ID. */\n $name = get_the_author_meta( 'display_name', $author );\n $email = get_the_author_meta( 'user_email', $author );\n $title = $post->post_title;\n $permalink = get_permalink( $ID );\n $edit = get_edit_post_link( $ID, '' );\n $to[] = sprintf( '%s <%s>', $name, $email );\n $subject = sprintf( 'Published: %s', $title );\n $message = sprintf ('Congratulations, %s! Your article “%s” has been published.' . \"\\n\\n\", $name, $title );\n $message .= sprintf( 'View: %s', $permalink );\n $headers[] = '';\n wp_mail( $to, $subject, $message, $headers );\n}\nadd_action( 'publish_post', 'post_published_notification', 10, 2 );\n</code></pre>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284683",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122813/"
]
| I have written a simple code to do something after a post is updated or published (its related to the varnish purge). I put my code inside post.php file. Everything was just fine before the latest update (4.8.3), after that all my codes were vanished!! of course it is a normal behavior because the post.php file has been replaced with a new one from update patch. I want to know how can I execute some code after a post is updated or published and my codes do not disappear after a Wordpress update? I don't want to use plugins too :D. Thank you. | You're looking for the `save_post` [action](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post). This allows you to add a function when a post is saved (updated).
You can hook into it like this:
```
function your_save_post_function( $post_id ) {
}
add_action( 'save_post', 'your_save_post_function' );
```
Remember to not change WordPress Core files, as these will be overwritten when WordPress is updated. You can put this code in your `functions.php` file, or anywhere else in your theme folder. |
284,692 | <p>I use a third party plugin that saves events locations addresses as a custom <em>locations</em> post type in a separate table - <em>wp_em_locations</em>. </p>
<p>Because events are created by multiple authors, they write sometimes differently the name of the same town, using different languages. <strong>How can I filter dynamically that names when the post is created and replace them with a default one?</strong> </p>
<p>For example, the Kiev town name can be written as Kiev, Киев, Kyiv and Київ, but I want to save only one of them. Town names are saved in the <em>location_town</em> column.</p>
| [
{
"answer_id": 284686,
"author": "Jlil",
"author_id": 83204,
"author_profile": "https://wordpress.stackexchange.com/users/83204",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\nadd_action( 'save_post', 'varnish_purge' );\nfunction varnish_purge()\n{\n // code here\n} \n</code></pre>\n"
},
{
"answer_id": 284687,
"author": "Jesse Vlasveld",
"author_id": 87884,
"author_profile": "https://wordpress.stackexchange.com/users/87884",
"pm_score": 2,
"selected": true,
"text": "<p>You're looking for the <code>save_post</code> <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">action</a>. This allows you to add a function when a post is saved (updated).</p>\n\n<p>You can hook into it like this:</p>\n\n<pre><code>function your_save_post_function( $post_id ) {\n}\n\nadd_action( 'save_post', 'your_save_post_function' );\n</code></pre>\n\n<p>Remember to not change WordPress Core files, as these will be overwritten when WordPress is updated. You can put this code in your <code>functions.php</code> file, or anywhere else in your theme folder.</p>\n"
},
{
"answer_id": 284690,
"author": "Malay Solanki",
"author_id": 130744,
"author_profile": "https://wordpress.stackexchange.com/users/130744",
"pm_score": 0,
"selected": false,
"text": "<p>You can replace publish_{post} , where {post} is any wordpress post type. </p>\n\n<pre><code>function post_published_notification( $ID, $post ) {\n $author = $post->post_author; /* Post author ID. */\n $name = get_the_author_meta( 'display_name', $author );\n $email = get_the_author_meta( 'user_email', $author );\n $title = $post->post_title;\n $permalink = get_permalink( $ID );\n $edit = get_edit_post_link( $ID, '' );\n $to[] = sprintf( '%s <%s>', $name, $email );\n $subject = sprintf( 'Published: %s', $title );\n $message = sprintf ('Congratulations, %s! Your article “%s” has been published.' . \"\\n\\n\", $name, $title );\n $message .= sprintf( 'View: %s', $permalink );\n $headers[] = '';\n wp_mail( $to, $subject, $message, $headers );\n}\nadd_action( 'publish_post', 'post_published_notification', 10, 2 );\n</code></pre>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284692",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25187/"
]
| I use a third party plugin that saves events locations addresses as a custom *locations* post type in a separate table - *wp\_em\_locations*.
Because events are created by multiple authors, they write sometimes differently the name of the same town, using different languages. **How can I filter dynamically that names when the post is created and replace them with a default one?**
For example, the Kiev town name can be written as Kiev, Киев, Kyiv and Київ, but I want to save only one of them. Town names are saved in the *location\_town* column. | You're looking for the `save_post` [action](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post). This allows you to add a function when a post is saved (updated).
You can hook into it like this:
```
function your_save_post_function( $post_id ) {
}
add_action( 'save_post', 'your_save_post_function' );
```
Remember to not change WordPress Core files, as these will be overwritten when WordPress is updated. You can put this code in your `functions.php` file, or anywhere else in your theme folder. |
284,696 | <p>Is there a way to override woocommerce core functions in functions.php ?</p>
<p>for example file location in:
wp-content/plugins/woocommerce/includes/class-wc-order-item-shipping.php</p>
<p>there is a following public function</p>
<pre><code>public function set_method_title( $value ) {
$this->set_prop( 'name', wc_clean($value) );
$this->set_prop( 'method_title', wc_clean($value) );
}
</code></pre>
<p>How to change it to this:</p>
<pre><code>public function set_method_title( $value ) {
$this->set_prop( 'name', $value );
$this->set_prop( 'method_title', $value );
}
</code></pre>
| [
{
"answer_id": 284702,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<p>You can't replace just any plugin function with your own code, <em>unless</em>:</p>\n\n<ol>\n<li>The plugin is wrapped in a <code>function_exists()</code> check. This makes the function <em>pluggable</em>, which means that if you define it first the plugin won't try to define it again, and yours will be used. This function is not pluggable.</li>\n<li>There is a filter somewhere, indicated by the use of the <code>apply_filters()</code> function, that lets you replace a value. That value might be the output of a function, and by using the filter you could replace the output with your own.</li>\n</ol>\n\n<p>The specific function you identify does not have either, so cannot be replaced. I'd consider that WooCommerce probably has a very good reason for applying <code>wc_clean()</code> to these properties, and if it weren't there things might not function as expected, or it could pose a security risk.</p>\n"
},
{
"answer_id": 284811,
"author": "Erica",
"author_id": 31889,
"author_profile": "https://wordpress.stackexchange.com/users/31889",
"pm_score": 2,
"selected": false,
"text": "<p>Removing those functions is very ill-advised. It is prepping the data for entry into the database. Those entries only accept simple text, so the <strong>wc_clean</strong> function runs the WordPress <strong>sanitize_text_field</strong> function. As per <a href=\"https://developer.wordpress.org/reference/functions/sanitize_text_field/\" rel=\"nofollow noreferrer\">WordPress documentation</a>, this function:</p>\n\n<ul>\n<li>Checks for invalid UTF-8</li>\n<li>Converts single < characters to entities</li>\n<li>Strips all tags Removes line breaks, tabs, and extra whitespace</li>\n<li>Strips octets</li>\n</ul>\n\n<p>Even if you could remove them, they may not save correctly in the database. It would also open you up to possible attacks because it would allow potentially harmful code to be injected. Data should always be sanitized before saving it, and the data must match the table column settings to avoid some being cut off.</p>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78475/"
]
| Is there a way to override woocommerce core functions in functions.php ?
for example file location in:
wp-content/plugins/woocommerce/includes/class-wc-order-item-shipping.php
there is a following public function
```
public function set_method_title( $value ) {
$this->set_prop( 'name', wc_clean($value) );
$this->set_prop( 'method_title', wc_clean($value) );
}
```
How to change it to this:
```
public function set_method_title( $value ) {
$this->set_prop( 'name', $value );
$this->set_prop( 'method_title', $value );
}
``` | You can't replace just any plugin function with your own code, *unless*:
1. The plugin is wrapped in a `function_exists()` check. This makes the function *pluggable*, which means that if you define it first the plugin won't try to define it again, and yours will be used. This function is not pluggable.
2. There is a filter somewhere, indicated by the use of the `apply_filters()` function, that lets you replace a value. That value might be the output of a function, and by using the filter you could replace the output with your own.
The specific function you identify does not have either, so cannot be replaced. I'd consider that WooCommerce probably has a very good reason for applying `wc_clean()` to these properties, and if it weren't there things might not function as expected, or it could pose a security risk. |
284,699 | <pre><code>if(have_posts()):
while(have_posts()):
the_post();
the_content();
endwhile;
endif;
</code></pre>
<p>Without if condition this below code also works fine:</p>
<pre><code>while(have_posts()):
the_post();
the_content();
endwhile;
</code></pre>
<p>Thanks.</p>
| [
{
"answer_id": 284700,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 2,
"selected": false,
"text": "<p>You're right, it's not necessary. </p>\n\n<p>However, you'll often want to wrap your post-output in a <code><div class=\"posts\"></code> or something similar, and you can make outputting that div conditional based on whether there will actually be anything in it, which makes it much cleaner to style in my opinion, because you won't end up with <code><div class=\"posts\"></div></code> if there are no posts. You won't need to use any <code>:empty</code> selectors in your CSS to hide this empty div, since it won't be in the DOM at all.</p>\n"
},
{
"answer_id": 284701,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You only need the <code>if ( have_posts() ) :</code> if, as the name of the function suggets, you need to do something different if you don't have posts. This would be something like displaying a \"No posts found.\" message.</p>\n\n<p>But you'd only need that on templates that <em>could</em> show no posts, like archives and search. For single post and page templates the <code>if</code> is unnecessary.</p>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284699",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130750/"
]
| ```
if(have_posts()):
while(have_posts()):
the_post();
the_content();
endwhile;
endif;
```
Without if condition this below code also works fine:
```
while(have_posts()):
the_post();
the_content();
endwhile;
```
Thanks. | You only need the `if ( have_posts() ) :` if, as the name of the function suggets, you need to do something different if you don't have posts. This would be something like displaying a "No posts found." message.
But you'd only need that on templates that *could* show no posts, like archives and search. For single post and page templates the `if` is unnecessary. |
284,706 | <p>Custom form is taking decimal but db inserts whole numbers but with a .0 behind. Why won't it give me the correct decimal number ?</p>
<p>Db field</p>
<pre><code> fiske_vaegt DECIMAL( 2,1 ) NOT NULL,
</code></pre>
<p>Form input field</p>
<pre><code> <p><input type="number" step="any" name="fiske_vaegt" id="fiske_vaegt" />kg</p>
</code></pre>
<p>CHECK the fiske_vaegt field if i Input 2.4 it changes it to 2.0 and 2.7 to 3.0
<a href="https://i.stack.imgur.com/FzZ71.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FzZ71.png" alt="enter image description here"></a></p>
<p>Anyone who have any experience with this goddamned problem? </p>
<p>post</p>
<pre><code> if ( isset( $_POST['submit'] ) ){
$fiske_vaegt = $_POST['fiske_vaegt'];
</code></pre>
<p>}</p>
<p>insert </p>
<pre><code>$registrering = $wpdb->insert(
$wpdb->prefix . 'registreringer',
array(
'fiske_vaegt' => $fiske_vaegt
),
array(
'%d'
)
);
</code></pre>
| [
{
"answer_id": 284708,
"author": "sakibmoon",
"author_id": 23214,
"author_profile": "https://wordpress.stackexchange.com/users/23214",
"pm_score": 3,
"selected": true,
"text": "<p>Within <code>$wpdb->insert</code>, you are using <code>%d</code> which is used to store integer, use <code>%f</code> instead which will store float/decimal values.</p>\n\n<pre><code>$registrering = $wpdb->insert( \n $wpdb->prefix . 'registreringer',\n array(\n 'fiske_vaegt' => $fiske_vaegt\n ),\n array(\n '%f'\n )\n);\n</code></pre>\n"
},
{
"answer_id": 284709,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 2,
"selected": false,
"text": "<p>'%d' modifier is for integers, not decimals use the %f (floats or the %s strings) and it would save it correctly.</p>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284706",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129518/"
]
| Custom form is taking decimal but db inserts whole numbers but with a .0 behind. Why won't it give me the correct decimal number ?
Db field
```
fiske_vaegt DECIMAL( 2,1 ) NOT NULL,
```
Form input field
```
<p><input type="number" step="any" name="fiske_vaegt" id="fiske_vaegt" />kg</p>
```
CHECK the fiske\_vaegt field if i Input 2.4 it changes it to 2.0 and 2.7 to 3.0
[](https://i.stack.imgur.com/FzZ71.png)
Anyone who have any experience with this goddamned problem?
post
```
if ( isset( $_POST['submit'] ) ){
$fiske_vaegt = $_POST['fiske_vaegt'];
```
}
insert
```
$registrering = $wpdb->insert(
$wpdb->prefix . 'registreringer',
array(
'fiske_vaegt' => $fiske_vaegt
),
array(
'%d'
)
);
``` | Within `$wpdb->insert`, you are using `%d` which is used to store integer, use `%f` instead which will store float/decimal values.
```
$registrering = $wpdb->insert(
$wpdb->prefix . 'registreringer',
array(
'fiske_vaegt' => $fiske_vaegt
),
array(
'%f'
)
);
``` |
284,719 | <p>I get my posts of an cpt like this:
<a href="http://www.mywebsite.com/wp-json/wp/v2/cpt" rel="nofollow noreferrer">http://www.mywebsite.com/wp-json/wp/v2/cpt</a></p>
<p>at this posts there are shown post_meta values.</p>
<p>Does anyone know a way to order the posts by the meta like this:
<a href="http://www.mywebsite.com/wp-json/wp/v2/cpt?orderby=my_meta_field" rel="nofollow noreferrer">http://www.mywebsite.com/wp-json/wp/v2/cpt?orderby=my_meta_field</a></p>
<p>I found some solutions, but none of them are working for me….
Please help!
Thanks! Stefan</p>
| [
{
"answer_id": 284722,
"author": "Isu",
"author_id": 102934,
"author_profile": "https://wordpress.stackexchange.com/users/102934",
"pm_score": 1,
"selected": false,
"text": "<p>Since wordpress 4.7, it has build in Rest Api 2. And since then there is no args like that. \nSo you can write your own endopint and create what you want. </p>\n\n<p>Check out answer: \n<a href=\"https://wordpress.stackexchange.com/questions/271877/how-to-do-a-meta-query-using-rest-api-in-wordpress-4-7\">How to do a meta query using REST-API in WordPress 4.7+?</a></p>\n\n<p>Or use: <a href=\"https://github.com/WP-API/rest-filter\" rel=\"nofollow noreferrer\">https://github.com/WP-API/rest-filter</a></p>\n"
},
{
"answer_id": 284725,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this filter to change order : </p>\n\n<pre><code>$type = \"cptCode\";\n\nadd_filter(\"rest_\" . $type . \"_query\", function ($args, $query) {\n\n $args[\"orderby\"] = \"meta_value\";\n $args[\"meta_key\"] = \"my_meta_field\";\n\n return $args;\n\n}, 10, 2);\n</code></pre>\n\n<p>You can also test <code>$_GET</code> to change the order conditionally.</p>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284719",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130761/"
]
| I get my posts of an cpt like this:
<http://www.mywebsite.com/wp-json/wp/v2/cpt>
at this posts there are shown post\_meta values.
Does anyone know a way to order the posts by the meta like this:
<http://www.mywebsite.com/wp-json/wp/v2/cpt?orderby=my_meta_field>
I found some solutions, but none of them are working for me….
Please help!
Thanks! Stefan | You can use this filter to change order :
```
$type = "cptCode";
add_filter("rest_" . $type . "_query", function ($args, $query) {
$args["orderby"] = "meta_value";
$args["meta_key"] = "my_meta_field";
return $args;
}, 10, 2);
```
You can also test `$_GET` to change the order conditionally. |
284,720 | <p>I want to use his image zoom function on my wordpress site:
<a href="https://github.com/spinningarrow/zoom-vanilla.js" rel="nofollow noreferrer">Medium's Image Zoom in vanilla JS</a></p>
<p>but I'm not sure how to add</p>
<pre><code>data-action="zoom"
</code></pre>
<p>attribute to all images attached in posts. What function I need to use? Can somebody help me?</p>
| [
{
"answer_id": 284724,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 3,
"selected": true,
"text": "<p>You have a number of options.</p>\n\n<p>You could use the <code>add_filter( 'the_content', 'add_data_attributes' );</code>\nAnd after that find the images attached to the post.</p>\n\n<p>Or you can use the <code>image_send_to_editor</code> filter more <a href=\"https://developer.wordpress.org/reference/hooks/image_send_to_editor/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 284734,
"author": "DHL17",
"author_id": 125227,
"author_profile": "https://wordpress.stackexchange.com/users/125227",
"pm_score": 0,
"selected": false,
"text": "<p>Place this code where you run the post loop after <code><?php get_footer(); ?></code></p>\n\n<pre><code> <script>\n jQuery('.wp-post-image').attr('data-action','zoom')\n </script>\n</code></pre>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284720",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76748/"
]
| I want to use his image zoom function on my wordpress site:
[Medium's Image Zoom in vanilla JS](https://github.com/spinningarrow/zoom-vanilla.js)
but I'm not sure how to add
```
data-action="zoom"
```
attribute to all images attached in posts. What function I need to use? Can somebody help me? | You have a number of options.
You could use the `add_filter( 'the_content', 'add_data_attributes' );`
And after that find the images attached to the post.
Or you can use the `image_send_to_editor` filter more [here](https://developer.wordpress.org/reference/hooks/image_send_to_editor/). |
284,767 | <p>I am creating a child theme for my site and inside my functions.php I added a code to load a specific css file ONLY where it is the HOME page:</p>
<pre><code> // enqueue styles for child theme
function wowdental_enqueue_styles() {
// enqueue parent styles
wp_enqueue_style('Divi', get_template_directory_uri() .'/style.css', get_the_time() );
// Flip3d css
wp_enqueue_style( 'flip', get_stylesheet_directory_uri() . '/css/flip.css', get_the_time() );
// flip3d only on home page
if( is_home() ) {
wp_enqueue_style('flip');
}
}
add_action('wp_enqueue_scripts', 'wowdental_enqueue_styles');
</code></pre>
<p>I placed the condition for if is_home() but the stylesheet gets pulled in ALL pages regardless of whether home page or not. </p>
<p>I have also used if (is_home() || is_front_page() ) but I get the same result. </p>
<p>What am I doing wrong here??</p>
| [
{
"answer_id": 284770,
"author": "Laxmana",
"author_id": 40948,
"author_profile": "https://wordpress.stackexchange.com/users/40948",
"pm_score": 1,
"selected": false,
"text": "<p>From the <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">docs</a>:</p>\n\n<blockquote>\n <p>Registers the style if source provided (does NOT overwrite) and enqueues.</p>\n</blockquote>\n\n<p>That means that when you use <code>wp_enqueue_style</code> the css file will be registered and enqueued for output.</p>\n\n<p>Before the <code>if</code> condition you have to register the css file with the use of <code>wp_register_style</code> and then inside the condition to enqueue it.</p>\n"
},
{
"answer_id": 284771,
"author": "James",
"author_id": 122472,
"author_profile": "https://wordpress.stackexchange.com/users/122472",
"pm_score": 1,
"selected": true,
"text": "<p>You'll need to put the if statement around the line that enqueues in the first place.</p>\n\n<pre><code>// enqueue styles for child theme\nfunction wowdental_enqueue_styles() {\n\n // enqueue parent styles\n wp_enqueue_style('Divi', get_template_directory_uri() .'/style.css', \n get_the_time() );\n\n // Flip3d css\n // flip3d only on home page\n if( is_home() ) {\n wp_enqueue_style( 'flip', get_stylesheet_directory_uri() . \n'/css/flip.css', get_the_time() );\n }\n\n\n }\nadd_action('wp_enqueue_scripts', 'wowdental_enqueue_styles');\n</code></pre>\n\n<p>To do it like you have it in the original code, you'd need to use wp_register_style first, then keep the enqueue in the if.</p>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284767",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130781/"
]
| I am creating a child theme for my site and inside my functions.php I added a code to load a specific css file ONLY where it is the HOME page:
```
// enqueue styles for child theme
function wowdental_enqueue_styles() {
// enqueue parent styles
wp_enqueue_style('Divi', get_template_directory_uri() .'/style.css', get_the_time() );
// Flip3d css
wp_enqueue_style( 'flip', get_stylesheet_directory_uri() . '/css/flip.css', get_the_time() );
// flip3d only on home page
if( is_home() ) {
wp_enqueue_style('flip');
}
}
add_action('wp_enqueue_scripts', 'wowdental_enqueue_styles');
```
I placed the condition for if is\_home() but the stylesheet gets pulled in ALL pages regardless of whether home page or not.
I have also used if (is\_home() || is\_front\_page() ) but I get the same result.
What am I doing wrong here?? | You'll need to put the if statement around the line that enqueues in the first place.
```
// enqueue styles for child theme
function wowdental_enqueue_styles() {
// enqueue parent styles
wp_enqueue_style('Divi', get_template_directory_uri() .'/style.css',
get_the_time() );
// Flip3d css
// flip3d only on home page
if( is_home() ) {
wp_enqueue_style( 'flip', get_stylesheet_directory_uri() .
'/css/flip.css', get_the_time() );
}
}
add_action('wp_enqueue_scripts', 'wowdental_enqueue_styles');
```
To do it like you have it in the original code, you'd need to use wp\_register\_style first, then keep the enqueue in the if. |
284,773 | <p>I'm doing a plugin using Shortcodes.
I have some classes which extend an abstract class calls Shortcode.</p>
<pre><code>abstract class Shortcode {
public $tag;
public $attrs;
public $function;
public function __construct($tag) {
$this->attrs = array();
$this->tag = $tag;
$this->function = static::className().'::getCallBack';
add_shortcode( $this->tag, $this->function );
$this->init();
}
protected function init(){
if( !is_admin() ){
//Front-end
error_log('test 1');
add_action('wp', array( $this , 'check_page' ) );
}
}
abstract public function check_page();
abstract public static function className();
abstract public static function getCallBack( $attrs );
}
</code></pre>
<p><strong>My Shortcode class</strong></p>
<pre><code>class MyShortcode extends Shortcode {
public function check_page(){
error_log( "test 2" );
global $post;
$pattern = '/(\['.$this->tag.'\])/';
if( !empty( $post->post_content ) && preg_match( $pattern, $post->post_content ) ){
add_action('wp_enqueue_scripts', array( $this , 'set_styles'));
}
}
public static function getCallBack( $attrs = null ){
...
}
//CSS stylesheets
public function set_styles() {
//wp_enqueue_style( 'wgsstyle', PLUGIN_DIR_URL . 'front-end/views/css/wgs-front-end.css' );
//wp_enqueue_style( 'wgscardsstyle', PLUGIN_DIR_URL . 'front-end/views/css/wgs-cards.css' );
}
public static function className(){
return __CLASS__;
}
}
</code></pre>
<p>Something happens is weird... In debug.log, it's written "test 1" but not "test 2" and css stylesheets are still loaded.</p>
<p>Is there a cache for Shortcodes ? How can I reinitialize this code ?</p>
| [
{
"answer_id": 284809,
"author": "plushyObject",
"author_id": 76522,
"author_profile": "https://wordpress.stackexchange.com/users/76522",
"pm_score": 0,
"selected": false,
"text": "<p>You should think about setting up an Amazon S3 or something like that. You can scale if things get bigger, and only pay for a smaller bucket to start out. It's pretty easy to set up.</p>\n"
},
{
"answer_id": 390317,
"author": "Fabian Mossberg",
"author_id": 207387,
"author_profile": "https://wordpress.stackexchange.com/users/207387",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest that you use a CDN to host your image files.</p>\n<p>For starters you could move the images over to the new hosting though. Or is it many terrabytes of images? If so, I don't think it's a good idea to have them in Wordpress.</p>\n<p>Regarding hosting the image library, have you considered using a CDN?</p>\n<p>There are a bunch of plugins that would help you with this, they are all pretty straight forward:</p>\n<ul>\n<li><a href=\"https://wordpress.org/plugins/w3-total-cache/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/w3-total-cache/</a></li>\n<li><a href=\"https://wordpress.org/plugins/amazon-s3-and-cloudfront/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/amazon-s3-and-cloudfront/</a></li>\n<li><a href=\"https://wordpress.org/plugins/aws-cdn-by-wpadmin/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/aws-cdn-by-wpadmin/</a></li>\n<li><a href=\"https://wordpress.org/plugins/cdn-enabler/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/cdn-enabler/</a></li>\n</ul>\n<p>Personally, I've ended up using WP Rocket: <a href=\"https://wp-rocket.me/\" rel=\"nofollow noreferrer\">https://wp-rocket.me/</a>\nIt's working really well, and there are a lot of settings to tweak performance.</p>\n<p>I'm using S3 + Cloudfront from Amazon on some projects. My favourite one so far though, has been StackPath: <a href=\"https://www.stackpath.com/\" rel=\"nofollow noreferrer\">https://www.stackpath.com/</a>, it's running really nice with WP Rocket.</p>\n<p>But before you enable any CDN, I'd actually move over the images to the new VPS. I assume that you will be keeping the whole website, all posts etc.</p>\n<ul>\n<li>Dump the DB on the old site</li>\n<li>Copy the files from the old to the new using rsync, directly from the old server to the new.</li>\n<li>Import the DB dump on the new server.</li>\n</ul>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284773",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128094/"
]
| I'm doing a plugin using Shortcodes.
I have some classes which extend an abstract class calls Shortcode.
```
abstract class Shortcode {
public $tag;
public $attrs;
public $function;
public function __construct($tag) {
$this->attrs = array();
$this->tag = $tag;
$this->function = static::className().'::getCallBack';
add_shortcode( $this->tag, $this->function );
$this->init();
}
protected function init(){
if( !is_admin() ){
//Front-end
error_log('test 1');
add_action('wp', array( $this , 'check_page' ) );
}
}
abstract public function check_page();
abstract public static function className();
abstract public static function getCallBack( $attrs );
}
```
**My Shortcode class**
```
class MyShortcode extends Shortcode {
public function check_page(){
error_log( "test 2" );
global $post;
$pattern = '/(\['.$this->tag.'\])/';
if( !empty( $post->post_content ) && preg_match( $pattern, $post->post_content ) ){
add_action('wp_enqueue_scripts', array( $this , 'set_styles'));
}
}
public static function getCallBack( $attrs = null ){
...
}
//CSS stylesheets
public function set_styles() {
//wp_enqueue_style( 'wgsstyle', PLUGIN_DIR_URL . 'front-end/views/css/wgs-front-end.css' );
//wp_enqueue_style( 'wgscardsstyle', PLUGIN_DIR_URL . 'front-end/views/css/wgs-cards.css' );
}
public static function className(){
return __CLASS__;
}
}
```
Something happens is weird... In debug.log, it's written "test 1" but not "test 2" and css stylesheets are still loaded.
Is there a cache for Shortcodes ? How can I reinitialize this code ? | I would suggest that you use a CDN to host your image files.
For starters you could move the images over to the new hosting though. Or is it many terrabytes of images? If so, I don't think it's a good idea to have them in Wordpress.
Regarding hosting the image library, have you considered using a CDN?
There are a bunch of plugins that would help you with this, they are all pretty straight forward:
* <https://wordpress.org/plugins/w3-total-cache/>
* <https://wordpress.org/plugins/amazon-s3-and-cloudfront/>
* <https://wordpress.org/plugins/aws-cdn-by-wpadmin/>
* <https://wordpress.org/plugins/cdn-enabler/>
Personally, I've ended up using WP Rocket: <https://wp-rocket.me/>
It's working really well, and there are a lot of settings to tweak performance.
I'm using S3 + Cloudfront from Amazon on some projects. My favourite one so far though, has been StackPath: <https://www.stackpath.com/>, it's running really nice with WP Rocket.
But before you enable any CDN, I'd actually move over the images to the new VPS. I assume that you will be keeping the whole website, all posts etc.
* Dump the DB on the old site
* Copy the files from the old to the new using rsync, directly from the old server to the new.
* Import the DB dump on the new server. |
284,789 | <p>how to remove slug from url ?</p>
<pre><code>example.com/example/new-post/
</code></pre>
<p>how to remove <code>/example/</code>?</p>
| [
{
"answer_id": 284790,
"author": "Mouad DB",
"author_id": 119622,
"author_profile": "https://wordpress.stackexchange.com/users/119622",
"pm_score": -1,
"selected": false,
"text": "<p>Admin Dashboard > Settings > Permalink: Choose Custom Structure then set your custom structure.</p>\n"
},
{
"answer_id": 284806,
"author": "plushyObject",
"author_id": 76522,
"author_profile": "https://wordpress.stackexchange.com/users/76522",
"pm_score": 0,
"selected": false,
"text": "<p>Whenever you <code>register_post_type()</code>, one of the args is <code>rewrite</code> where you can reset the URL to something else. Maybe you can play with this -- try leaving it blank?</p>\n\n<p>Pro tip: You will have to reset permalinks after you do this.</p>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284789",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129421/"
]
| how to remove slug from url ?
```
example.com/example/new-post/
```
how to remove `/example/`? | Whenever you `register_post_type()`, one of the args is `rewrite` where you can reset the URL to something else. Maybe you can play with this -- try leaving it blank?
Pro tip: You will have to reset permalinks after you do this. |
284,797 | <p>how to redirect the error message page "Sorry, you are not allowed to access this page." to the Home page?</p>
| [
{
"answer_id": 284802,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I think that is a function of the theme, which will return that message under whatever conditions it defined. (Hard to say exactly what file of the theme, since you didn't specify the theme name. But a search for that phrase should find the file.)</p>\n\n<p>If I am correct, then you should (best practice) make a child theme, then copy the theme's PHP file that displays that message into the child theme folder. Then edit the file in the child theme folder to change the part of the code that displays the message to a <code>wp_redirect()</code> (see <a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_redirect/</a> ) . Make sure you include the <code>exit</code> command after the <code>wp_direct()</code> .</p>\n"
},
{
"answer_id": 383285,
"author": "Axel",
"author_id": 87156,
"author_profile": "https://wordpress.stackexchange.com/users/87156",
"pm_score": 1,
"selected": false,
"text": "<p>Accroding to the file "wp-content/languages/admin-[lang].po" and an additional search inside of a local copy of WP 5.6.1 the phrase is used 17 times. Not in all contexts there is an obvious hook to catch the error screen but in a lot of cases the error screen appears when a user wants to access an area of the backend where he has no appropriate permissions (eg role "editor" in "wp-admin/plugins.php").</p>\n<p>If this is the case the error screen is triggered in "wp-admin/includes/menu.php" and luckily sinve WP 2.5.0 there is a hook right before the triggering <code>wp_die</code>-function, which is <code>do_action('admin_page_access_denied')</code>.</p>\n<p>So in this case one could redirect the error screen like so.</p>\n<pre><code>add_action( 'admin_page_access_denied', function()\n{\n die( // make shure execution dies right after redirect\n wp_redirect( // redirect\n site_url() // to the home page\n )\n );\n // short: die( wp_redirect( site_url() ) );\n} );\n</code></pre>\n<h3>Appearance of the Phrase "Sorry, you are not allowed to access this page."</h3>\n<blockquote>\n<p>#: wp-admin/includes/menu.php:350 wp-admin/my-sites.php:17<br />\n#: wp-admin/network/site-info.php:32 wp-admin/network/user-new.php:37<br />\n#: wp-admin/network/index.php:17 wp-admin/network/site-users.php:50<br />\n#: wp-admin/network/upgrade.php:38 wp-admin/network/users.php:14<br />\n#: wp-admin/network/users.php:24 wp-admin/network/users.php:46<br />\n#: wp-admin/network/users.php:60 wp-admin/network/users.php:150<br />\n#: wp-admin/network/site-themes.php:57 wp-admin/network/settings.php:17<br />\n#: wp-admin/network/site-settings.php:32 wp-admin/network/sites.php:14<br />\n#: wp-admin/network/sites.php:140</p>\n</blockquote>\n<p>source: "wp-content/languages/admin-[lang].po"</p>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284797",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66393/"
]
| how to redirect the error message page "Sorry, you are not allowed to access this page." to the Home page? | Accroding to the file "wp-content/languages/admin-[lang].po" and an additional search inside of a local copy of WP 5.6.1 the phrase is used 17 times. Not in all contexts there is an obvious hook to catch the error screen but in a lot of cases the error screen appears when a user wants to access an area of the backend where he has no appropriate permissions (eg role "editor" in "wp-admin/plugins.php").
If this is the case the error screen is triggered in "wp-admin/includes/menu.php" and luckily sinve WP 2.5.0 there is a hook right before the triggering `wp_die`-function, which is `do_action('admin_page_access_denied')`.
So in this case one could redirect the error screen like so.
```
add_action( 'admin_page_access_denied', function()
{
die( // make shure execution dies right after redirect
wp_redirect( // redirect
site_url() // to the home page
)
);
// short: die( wp_redirect( site_url() ) );
} );
```
### Appearance of the Phrase "Sorry, you are not allowed to access this page."
>
> #: wp-admin/includes/menu.php:350 wp-admin/my-sites.php:17
>
> #: wp-admin/network/site-info.php:32 wp-admin/network/user-new.php:37
>
> #: wp-admin/network/index.php:17 wp-admin/network/site-users.php:50
>
> #: wp-admin/network/upgrade.php:38 wp-admin/network/users.php:14
>
> #: wp-admin/network/users.php:24 wp-admin/network/users.php:46
>
> #: wp-admin/network/users.php:60 wp-admin/network/users.php:150
>
> #: wp-admin/network/site-themes.php:57 wp-admin/network/settings.php:17
>
> #: wp-admin/network/site-settings.php:32 wp-admin/network/sites.php:14
>
> #: wp-admin/network/sites.php:140
>
>
>
source: "wp-content/languages/admin-[lang].po" |
284,798 | <p>I have this code and the $var1 arrives empty to my function i dont know why, i've tested declaring the variable inside the function and it does work but when i try to declare it outside the function and pass it as a parameter with the do_action it doesn't work, any insights on this ? thanks</p>
<p>The add_shortcode works fine</p>
<pre><code>$name="link";
add_shortcode($name, 'aa_link_shortcode' );
function shorcode_resources($var1) {
global $post;
$shortcode_found = false;
if ( has_shortcode($post->post_content, $var1) ) {
$shortcode_found = true;
}
if ( $shortcode_found ) {
wp_enqueue_style( 'core', ABS_URL . '/shortcode/css/flipbox.css' , false );
wp_enqueue_script( 'my-js',ABS_URL . '/shortcode/js/flipbox('.$var1.').js', false );
}
}
do_action( 'wp_enqueue_scripts', $name);
add_action( 'wp_enqueue_scripts', 'shorcode_resources', 10, 1 );
</code></pre>
| [
{
"answer_id": 284799,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 3,
"selected": true,
"text": "<p>You are doing the <code>do_action</code> before the action is add, try moving it:</p>\n\n<pre><code>$name = \"link\";\nadd_shortcode($name, 'aa_link_shortcode');\n\nfunction shorcode_resources($var1) {\n global $post;\n $shortcode_found = false;\n\n if (has_shortcode($post->post_content, $var1)) {\n $shortcode_found = true;\n }\n\n if ($shortcode_found) {\n wp_enqueue_style('core', ABS_URL . '/shortcode/css/flipbox.css', false);\n wp_enqueue_script('my-js', ABS_URL . '/shortcode/js/flipbox(' . $var1 . ').js', false);\n }\n}\n\n//first we add the action\nadd_action('wp_enqueue_scripts', 'shorcode_resources', 10, 1);\n//then we do the action\ndo_action('wp_enqueue_scripts', $name);\n</code></pre>\n\n<p>also remember that <code>wp_enqueue_scripts</code> its an action that WP will trigger too</p>\n"
},
{
"answer_id": 284810,
"author": "Erica",
"author_id": 31889,
"author_profile": "https://wordpress.stackexchange.com/users/31889",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not really sure of the intent of this code, but more than likely the problem is that you are trying to change a built in hook. <strong>wp_enqueue_scripts</strong> is an actual WordPress hook that does not accept any arguments. Even though you declared you are passing one, when WP runs its <strong>wp_enqueue_scripts</strong> hook, it's going to ignore it. Maybe try using a global variable instead.</p>\n\n<pre><code>$shortcode_name=\"link\"; \nadd_shortcode($shortcode_name, 'aa_link_shortcode' );\n\nfunction shorcode_resources() {\n global $post, $shortcode_name;\n $shortcode_found = false;\n\n if ( has_shortcode($post->post_content, $shortcode_name) ) {\n $shortcode_found = true;\n } \n\n if ( $shortcode_found ) {\n wp_enqueue_style( 'core', ABS_URL . '/shortcode/css/flipbox.css' , false ); \n wp_enqueue_script( 'my-js',ABS_URL . '/shortcode/js/flipbox('.$shortcode_name.').js', false );\n }\n}\n\nadd_action( 'wp_enqueue_scripts', 'shorcode_resources', 10 ); \n</code></pre>\n"
}
]
| 2017/11/02 | [
"https://wordpress.stackexchange.com/questions/284798",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130802/"
]
| I have this code and the $var1 arrives empty to my function i dont know why, i've tested declaring the variable inside the function and it does work but when i try to declare it outside the function and pass it as a parameter with the do\_action it doesn't work, any insights on this ? thanks
The add\_shortcode works fine
```
$name="link";
add_shortcode($name, 'aa_link_shortcode' );
function shorcode_resources($var1) {
global $post;
$shortcode_found = false;
if ( has_shortcode($post->post_content, $var1) ) {
$shortcode_found = true;
}
if ( $shortcode_found ) {
wp_enqueue_style( 'core', ABS_URL . '/shortcode/css/flipbox.css' , false );
wp_enqueue_script( 'my-js',ABS_URL . '/shortcode/js/flipbox('.$var1.').js', false );
}
}
do_action( 'wp_enqueue_scripts', $name);
add_action( 'wp_enqueue_scripts', 'shorcode_resources', 10, 1 );
``` | You are doing the `do_action` before the action is add, try moving it:
```
$name = "link";
add_shortcode($name, 'aa_link_shortcode');
function shorcode_resources($var1) {
global $post;
$shortcode_found = false;
if (has_shortcode($post->post_content, $var1)) {
$shortcode_found = true;
}
if ($shortcode_found) {
wp_enqueue_style('core', ABS_URL . '/shortcode/css/flipbox.css', false);
wp_enqueue_script('my-js', ABS_URL . '/shortcode/js/flipbox(' . $var1 . ').js', false);
}
}
//first we add the action
add_action('wp_enqueue_scripts', 'shorcode_resources', 10, 1);
//then we do the action
do_action('wp_enqueue_scripts', $name);
```
also remember that `wp_enqueue_scripts` its an action that WP will trigger too |
284,801 | <p>First off I know there are tons of other "jQuery is not defined" threads and I have gone through them all and can't seem to find a solution. Trying to add jQuery functionality to a custom made theme nav and I cannot seem to get around this problem. Code is working fine in jsfiddle <a href="https://jsfiddle.net/TonyTheOnly/h7xwcb8h/" rel="nofollow noreferrer">https://jsfiddle.net/TonyTheOnly/h7xwcb8h/</a></p>
<p>But when I try to attempt this in my wordpress theme i get the error "jQuery is not defined" </p>
<p>Header</p>
<p>
</p>
<pre><code></head>
<body <?php body_class( $awesome_classes ); ?>>
<div class="topBar">
<img src="<?php header_image();?>" height="120px;" width="100px;" alt=""/ class="siteLogo">
<div class="topBarMiddle">
<p>español | ENGLISH</p>
</div>
<div class="topBarRight">
<nav>
<a class="burger-nav"></a>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</div>
</div>
</code></pre>
<p>functions</p>
<pre><code><?php
function paramo_script_enqueue() {
wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/paramo.css', array(), '1.0.0', 'all');
wp_enqueue_script('customjs', get_template_directory_uri() . '/js/paramo.js', array('jQuery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'paramo_script_enqueue');
function paramo_theme_setup() {
add_theme_support('menus');
register_nav_menu('primary', 'Primary Header Navigation');
register_nav_menu('secondary', 'Footer Navigation');
}
add_action('init', 'paramo_theme_setup');
add_theme_support('custom-header');
</code></pre>
<p>jQuery</p>
<pre><code>/*global $, jQuery, alert*/
jQuery(function () {
"use strict";
$(".burger-nav").on("click", function () {
$("nav ul").toggleClass("open");
});
});
</code></pre>
<p>Any help is greatly appreciated and thank you for your time!</p>
| [
{
"answer_id": 284803,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": true,
"text": "<p>The dependencies argument of <code>wp_enqueue_script()</code> is case sensetive:</p>\n\n<pre><code>wp_enqueue_script('customjs', get_template_directory_uri() . '/js/paramo.js', array('jQuery'), '1.0.0', true);\n</code></pre>\n\n<p>That <code>array('jQuery')</code> needs to be <code>array( 'jquery' )</code>.</p>\n\n<p>You can see the handles for bundled scripts on the documentation page for <code>wp_enqueue_script()</code>: \n<a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_script/</a></p>\n"
},
{
"answer_id": 284896,
"author": "jdp",
"author_id": 115910,
"author_profile": "https://wordpress.stackexchange.com/users/115910",
"pm_score": 1,
"selected": false,
"text": "<p>I can't comment quite yet but it's a good idea to move away from using the ready method to load your jQuery script. Start your WordPress scripts with <code>jQuery(function(){code here});</code> jQuery 3.x deprecates the formerly acceptable <code>jQuery(document).ready(function()....</code>. <a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">More info here</a></p>\n"
}
]
| 2017/11/03 | [
"https://wordpress.stackexchange.com/questions/284801",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130812/"
]
| First off I know there are tons of other "jQuery is not defined" threads and I have gone through them all and can't seem to find a solution. Trying to add jQuery functionality to a custom made theme nav and I cannot seem to get around this problem. Code is working fine in jsfiddle <https://jsfiddle.net/TonyTheOnly/h7xwcb8h/>
But when I try to attempt this in my wordpress theme i get the error "jQuery is not defined"
Header
```
</head>
<body <?php body_class( $awesome_classes ); ?>>
<div class="topBar">
<img src="<?php header_image();?>" height="120px;" width="100px;" alt=""/ class="siteLogo">
<div class="topBarMiddle">
<p>español | ENGLISH</p>
</div>
<div class="topBarRight">
<nav>
<a class="burger-nav"></a>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</div>
</div>
```
functions
```
<?php
function paramo_script_enqueue() {
wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/paramo.css', array(), '1.0.0', 'all');
wp_enqueue_script('customjs', get_template_directory_uri() . '/js/paramo.js', array('jQuery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'paramo_script_enqueue');
function paramo_theme_setup() {
add_theme_support('menus');
register_nav_menu('primary', 'Primary Header Navigation');
register_nav_menu('secondary', 'Footer Navigation');
}
add_action('init', 'paramo_theme_setup');
add_theme_support('custom-header');
```
jQuery
```
/*global $, jQuery, alert*/
jQuery(function () {
"use strict";
$(".burger-nav").on("click", function () {
$("nav ul").toggleClass("open");
});
});
```
Any help is greatly appreciated and thank you for your time! | The dependencies argument of `wp_enqueue_script()` is case sensetive:
```
wp_enqueue_script('customjs', get_template_directory_uri() . '/js/paramo.js', array('jQuery'), '1.0.0', true);
```
That `array('jQuery')` needs to be `array( 'jquery' )`.
You can see the handles for bundled scripts on the documentation page for `wp_enqueue_script()`:
<https://developer.wordpress.org/reference/functions/wp_enqueue_script/> |
284,819 | <p>I have been using, <a href="https://de.wordpress.org/plugins/http2-server-push/" rel="nofollow noreferrer">this plugin</a> and its says </p>
<blockquote>
<p>WordPress 4.6 <a href="https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/" rel="nofollow noreferrer">introduced native support</a> for resource hints.
By default, this plugin defers to WordPress 4.6 and theme/plugin developers to responsibly prefetch the right assets. Sites running
on older versions of WordPress will continue to get the previous behavior where all JavaScript and stylesheets had resource hints
printed for them.</p>
<p>I’ve added a filter To restore the old behavior (hint everything) on WordPress 4.6 and above. To use it, add this line to
your theme’s functions.php file or a custom plugin:</p>
</blockquote>
<p>I have looked at the code and it seems extremely hacky and horrible to me (not the way it is done, the way it seems it had to be done at that point)</p>
<p>I actually am using the filter to hint everything right now (probably bad idea). I once stumbled on a thread on wp core track about this but I can not find it. From the introduction posts code I am really not learning that much.</p>
<p>What I would like is just something like</p>
<pre><code>wp_register_script( ..., $http_prefech = true );
</code></pre>
<p>I think that was also discussed on trac somewhere.</p>
<p>Can there be a wrapper like this or can you show me in the most simple, more native to WP way how I set a specific asset to prefetch? </p>
| [
{
"answer_id": 284832,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>Support for resource hints in WordPress is done through <a href=\"https://w3c.github.io/resource-hints/\" rel=\"nofollow noreferrer\"><code>rel</code> attribute of <code><link></code> elements</a> whithin the HTML docuemnt, not with HTTP/2 server push (which uses <code>Link</code> headers in the HTTP response). You can use <a href=\"https://developer.wordpress.org/reference/hooks/wp_resource_hints/\" rel=\"nofollow noreferrer\"><code>wp_resource_hints</code> filter</a> to add the URLs you need the prefetch like this:</p>\n\n<pre><code>add_filter( 'wp_resource_hints', 'cyb_resource_hints', 10, 2 );\nfunction cyb_resource_hints( $urls, $relation_type ) {\n\n if( 'prefetch' == $relation_type ) {\n\n $urls[] = 'https://exmaple.com/assets/script.js';\n\n }\n\n return $urls;\n\n}\n</code></pre>\n\n<p>If you prefer to use HTTP/2 server push, you can set the <code>Link</code> header with PHP, .htaccess on Apache, etc.</p>\n\n<p>For example, with PHP:</p>\n\n<pre><code>header(\"Link: </css/styles.css>; rel=preload; as=style\");\n</code></pre>\n\n<p>And you can integrate it with WordPress at multiple levels, usually <code>template_redirect</code> action, for example:</p>\n\n<pre><code>add_action( 'template_redirect', 'cyb_push_styles' );\nfunciton cyb_push_styles() {\n\n header(\"Link: </css/styles.css>; rel=preload; as=style\"); \n\n}\n</code></pre>\n"
},
{
"answer_id": 304864,
"author": "Alex MacArthur",
"author_id": 89080,
"author_profile": "https://wordpress.stackexchange.com/users/89080",
"pm_score": 0,
"selected": false,
"text": "<p>First off, there's a difference between preloading and prefetching an asset, which isn't something that plugin is super clear about. Prefetching an asset is done in low priority, so it's best for resources that will be used on future page loads. Preloading assets is best for assets needed on the same page. All that said, you should be leveraging both. </p>\n\n<p>As far as specifically sending prefetch/preload headers for an asset, you could use a plugin I built. It allows you to prefetch or preload assets by their registered handles. Just save the handle, specify if you want to send headers, and save your settings. Relatively straightforward, and a bit more fleshed out than the other plugin you mentioned. </p>\n\n<p><a href=\"https://wordpress.org/plugins/better-resource-hints/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-resource-hints/</a></p>\n"
}
]
| 2017/11/03 | [
"https://wordpress.stackexchange.com/questions/284819",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38602/"
]
| I have been using, [this plugin](https://de.wordpress.org/plugins/http2-server-push/) and its says
>
> WordPress 4.6 [introduced native support](https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/) for resource hints.
> By default, this plugin defers to WordPress 4.6 and theme/plugin developers to responsibly prefetch the right assets. Sites running
> on older versions of WordPress will continue to get the previous behavior where all JavaScript and stylesheets had resource hints
> printed for them.
>
>
> I’ve added a filter To restore the old behavior (hint everything) on WordPress 4.6 and above. To use it, add this line to
> your theme’s functions.php file or a custom plugin:
>
>
>
I have looked at the code and it seems extremely hacky and horrible to me (not the way it is done, the way it seems it had to be done at that point)
I actually am using the filter to hint everything right now (probably bad idea). I once stumbled on a thread on wp core track about this but I can not find it. From the introduction posts code I am really not learning that much.
What I would like is just something like
```
wp_register_script( ..., $http_prefech = true );
```
I think that was also discussed on trac somewhere.
Can there be a wrapper like this or can you show me in the most simple, more native to WP way how I set a specific asset to prefetch? | Support for resource hints in WordPress is done through [`rel` attribute of `<link>` elements](https://w3c.github.io/resource-hints/) whithin the HTML docuemnt, not with HTTP/2 server push (which uses `Link` headers in the HTTP response). You can use [`wp_resource_hints` filter](https://developer.wordpress.org/reference/hooks/wp_resource_hints/) to add the URLs you need the prefetch like this:
```
add_filter( 'wp_resource_hints', 'cyb_resource_hints', 10, 2 );
function cyb_resource_hints( $urls, $relation_type ) {
if( 'prefetch' == $relation_type ) {
$urls[] = 'https://exmaple.com/assets/script.js';
}
return $urls;
}
```
If you prefer to use HTTP/2 server push, you can set the `Link` header with PHP, .htaccess on Apache, etc.
For example, with PHP:
```
header("Link: </css/styles.css>; rel=preload; as=style");
```
And you can integrate it with WordPress at multiple levels, usually `template_redirect` action, for example:
```
add_action( 'template_redirect', 'cyb_push_styles' );
funciton cyb_push_styles() {
header("Link: </css/styles.css>; rel=preload; as=style");
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.